LoadingCache mocking for JUnit testing - spring-boot

I need to test this method.
public String getTenantName(String tenantId) {
var tenant = getTenant(tenantId);
if (tenant == null) {
throw new TenantNotFoundException(tenantId);
}
return tenant.getTenantname();
}
but I am having problems with mocking the below loading cache
LoadingCache<String, Tenant> tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
#Override
public Tenant load(String tenantId) {
return tenantClient.getTenant(tenantId);
}
});
as this is being called by another private method
private Tenant getTenant(String tenantId) {
try {
if (StringUtils.isBlank(tenantId)) {
return null;
}
return tenantCache.get(tenantId);
} catch (TenantNotFoundException | ExecutionException e) {
logger.error(tenantId, e);
throw new TenantNotFoundException(tenantId);
}
}
I would really appreciate some help here.
I mocked loading cache
#mock
LoadingCache<String, Tenant> tenantCache;
and then in my test function I create a tenant object and return that on tenantCache.get() call.
tenantCache = CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterAccess(24, TimeUnit.HOURS).build(new CacheLoader<String, Tenant>() {
#Override
public Tenant load(String tenantId) {
return tenantClient.getTenant(tenantId);
}
});
Map<String, Tenant> map = new HashMap<String, Tenant>();
map.put("test", tenant);
tenantCache.putAll(map);
also for tenantClient I changed that to return tenant.
return tenantClient.getTenant(id) =>> return tenant;
as tenantClient is calling another API.

So, LoadingCache appears as a variable inside the service but it is implemented as an anonymous class. Therefore we need to mock LoadingCache and use
when(tenantCache.get(anyString())).thenReturn(new Tenant());

Related

Using Baggage in OpenTelemetry Spring application

I have a spring boot application where i have instrumented my code using automatic instrumentation.
Now in my application i am trying to attach a baggage in the traces or some specific span.
I know it uses contextPropagation. but i am not able to implement how contextPropagator, baggage and span work together.
Here is my relevant code implementation:
#WithSpan
private void doSomeWorkNewSpan() {
logger.info("Doing some work In New span");
Span span = Span.current();
ContextPropagators contextPropagators = new ContextPropagators() {
#Override
public TextMapPropagator getTextMapPropagator() {
return null;
}
};
Context context = new Context() {
#Override
public <V> V get(ContextKey<V> contextKey) {
return null;
}
#Override
public <V> Context with(ContextKey<V> contextKey, V v) {
return null;
}
};
Baggage baggage = new Baggage() {
#Override
public int size() {
return 0;
}
#Override
public void forEach(BiConsumer<? super String, ? super BaggageEntry> biConsumer) {
}
#Override
public Map<String, BaggageEntry> asMap() {
return null;
}
#Override
public String getEntryValue(String s) {
return null;
}
#Override
public BaggageBuilder toBuilder() {
return null;
}
};
baggage.storeInContext(context);
// span.storeInContext();
span.setAttribute("crun","yes");
span.addEvent("app.processing2.start", atttributes("321"));
span.addEvent("app.processing2.end", atttributes("321"));
}
private Attributes atttributes(String id) {
return Attributes.of(AttributeKey.stringKey("app.id"), id);
}

Spring-Boot | Test Service Containing Call to #Async Method

Want to Unit Test a Service that contains call to a #Aysnc method which return CompletableFuture Object.But the future object is always null (during testing) causing NullPointerException.
future.get() causes the error
Test Code
#RunWith(MockitoJUnitRunner.class)
public class ContainerValidatorTest {
#Mock
QueryGenerator queryGenerator;
#Mock
SplunkService splunkService;
#InjectMocks
private ContainerValidatorImpl containerValidatorImpl;
#Test
public void validateContainerTestWithNullData(){
CacheItemId cacheItemId = null;
String container = null;
assertFalse(containerValidatorImpl.validateContainer(cacheItemId,container));
}
}
Service Code
#Override
public boolean validateContainer(CacheItemId cacheItemId, String container) {
Query query = queryGenerator.getUserDetailsFromCacheInfoQuery(cacheItemId);
String response;
try {
CompletableFuture<String> future = splunkService.doExecuteQuery(query);
response = future.get();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error While Fetching User Details : "+ e.getLocalizedMessage());
}
System.out.println(response);
JsonArray jsonArray = new JsonParser().parse(response).getAsJsonArray();
if(!jsonArray.isJsonNull()) {
return jsonArray.get(0).getAsJsonObject().get("TAG").getAsString().equalsIgnoreCase(container);
}
throw new RuntimeException("Not Able to Find UserDetails");
}
You haven’t set any expectations on splunkService mock.
Then you call doExecuteQuery on the mock instance
With no expectations for the method call, Mockito returns default value for the method return type (null for Objects)
To fix, record your expectations with when and thenReturn
Update
#Test
public void validateContainerTestWithNullData(){
CacheItemId cacheItemId = null;
String container = null;
when(splunkService.doExecuteQuery(any())).thenReturn(CompletableFuture.completedFuture("completedVal"));
assertFalse(containerValidatorImpl.validateContainer(cacheItemId,container));
}

transactional unit testing with ObjectifyService - no rollback happening

We are trying to use google cloud datastore in our project and trying to use objectify as the ORM since google recommends it. I have carefully used and tried everything i could read about and think of but somehow the transactions don't seem to work. Following is my code and setup.
#RunWith(SpringRunner.class)
#EnableAspectJAutoProxy(proxyTargetClass = true)
#ContextConfiguration(classes = { CoreTestConfiguration.class })
public class TestObjectifyTransactionAspect {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
// Our tests assume strong consistency
new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(),
new LocalMemcacheServiceTestConfig(), new LocalTaskQueueTestConfig());
private Closeable closeableSession;
#Autowired
private DummyService dummyService;
#BeforeClass
public static void setUpBeforeClass() {
// Reset the Factory so that all translators work properly.
ObjectifyService.setFactory(new ObjectifyFactory());
}
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
System.setProperty("DATASTORE_EMULATOR_HOST", "localhost:8081");
ObjectifyService.register(UserEntity.class);
this.closeableSession = ObjectifyService.begin();
this.helper.setUp();
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
AsyncCacheFilter.complete();
this.closeableSession.close();
this.helper.tearDown();
}
#Test
public void testTransactionMutationRollback() {
// save initial list of users
List<UserEntity> users = new ArrayList<UserEntity>();
for (int i = 1; i <= 10; i++) {
UserEntity user = new UserEntity();
user.setAge(i);
user.setUsername("username_" + i);
users.add(user);
}
ObjectifyService.ofy().save().entities(users).now();
try {
dummyService.mutateDataWithException("username_1", 6L);
} catch (Exception e) {
e.printStackTrace();
}
List<UserEntity> users2 = this.dummyService.findAllUsers();
Assert.assertEquals("Size mismatch on rollback", users2.size(), 10);
boolean foundUserIdSix = false;
for (UserEntity userEntity : users2) {
if (userEntity.getUserId() == 1) {
Assert.assertEquals("Username update failed in transactional context rollback.", "username_1",
userEntity.getUsername());
}
if (userEntity.getUserId() == 6) {
foundUserIdSix = true;
}
}
if (!foundUserIdSix) {
Assert.fail("Deleted user with userId 6 but it is not rolledback.");
}
}
}
Since I am using spring, idea is to use an aspect with a custom annotation to weave objectify.transact around the spring service beans methods that are calling my daos.
But somehow the update due to ObjectifyService.ofy().save().entities(users).now(); is not gettign rollbacked though the exception throws causes Objectify to run its rollback code. I tried printing the ObjectifyImpl instance hashcodes and they are all same but still its not rollbacking.
Can someone help me understand what am i doing wrong? Havent tried the actual web based setup yet...if it cant pass transnational test cases there is no point in actual transaction usage in a web request scenario.
Update: Adding aspect, services, dao as well to make a complete picture. The code uses spring boot.
DAO class. Note i am not using any transactions here because as per code of com.googlecode.objectify.impl.TransactorNo.transactOnce(ObjectifyImpl<O>, Work<R>) a transnational ObjectifyImpl is flushed and committed in this method which i don't want. I want commit to happen once and rest all to join in on that transaction. Basically this is the wrong code in com.googlecode.objectify.impl.TransactorNo ..... i will try to explain my understanding a later in the question.
#Component
public class DummyDaoImpl implements DummyDao {
#Override
public List<UserEntity> loadAll() {
Query<UserEntity> query = ObjectifyService.ofy().transactionless().load().type(UserEntity.class);
return query.list();
}
#Override
public List<UserEntity> findByUserId(Long userId) {
Query<UserEntity> query = ObjectifyService.ofy().transactionless().load().type(UserEntity.class);
//query = query.filterKey(Key.create(UserEntity.class, userId));
return query.list();
}
#Override
public List<UserEntity> findByUsername(String username) {
return ObjectifyService.ofy().transactionless().load().type(UserEntity.class).filter("username", username).list();
}
#Override
public void update(UserEntity userEntity) {
ObjectifyService.ofy().save().entity(userEntity);
}
#Override
public void update(Iterable<UserEntity> userEntities) {
ObjectifyService.ofy().save().entities(userEntities);
}
#Override
public void delete(Long userId) {
ObjectifyService.ofy().delete().key(Key.create(UserEntity.class, userId));
}
}
Below is the Service class
#Service
public class DummyServiceImpl implements DummyService {
private static final Logger LOGGER = LoggerFactory.getLogger(DummyServiceImpl.class);
#Autowired
private DummyDao dummyDao;
public void saveDummydata() {
List<UserEntity> users = new ArrayList<UserEntity>();
for (int i = 1; i <= 10; i++) {
UserEntity user = new UserEntity();
user.setAge(i);
user.setUsername("username_" + i);
users.add(user);
}
this.dummyDao.update(users);
}
/* (non-Javadoc)
* #see com.bbb.core.objectify.test.services.DummyService#mutateDataWithException(java.lang.String, java.lang.Long)
*/
#Override
#ObjectifyTransactional
public void mutateDataWithException(String usernameToMutate, Long userIdToDelete) throws Exception {
//update one
LOGGER.info("Attempting to update UserEntity with username={}", "username_1");
List<UserEntity> mutatedUsersList = new ArrayList<UserEntity>();
List<UserEntity> users = dummyDao.findByUsername(usernameToMutate);
for (UserEntity userEntity : users) {
userEntity.setUsername(userEntity.getUsername() + "_updated");
mutatedUsersList.add(userEntity);
}
dummyDao.update(mutatedUsersList);
//delete another
UserEntity user = dummyDao.findByUserId(userIdToDelete).get(0);
LOGGER.info("Attempting to delete UserEntity with userId={}", user.getUserId());
dummyDao.delete(user.getUserId());
throw new RuntimeException("Dummy Exception");
}
/* (non-Javadoc)
* #see com.bbb.core.objectify.test.services.DummyService#findAllUsers()
*/
#Override
public List<UserEntity> findAllUsers() {
return dummyDao.loadAll();
}
Aspect which wraps the method annoted with ObjectifyTransactional as a transact work.
#Aspect
#Component
public class ObjectifyTransactionAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectifyTransactionAspect.class);
#Around(value = "execution(* *(..)) && #annotation(objectifyTransactional)")
public Object objectifyTransactAdvise(final ProceedingJoinPoint pjp, ObjectifyTransactional objectifyTransactional) throws Throwable {
try {
Object result = null;
Work<Object> work = new Work<Object>() {
#Override
public Object run() {
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new ObjectifyTransactionExceptionWrapper(throwable);
}
}
};
switch (objectifyTransactional.propagation()) {
case REQUIRES_NEW:
int limitTries = objectifyTransactional.limitTries();
if(limitTries <= 0) {
Exception illegalStateException = new IllegalStateException("limitTries must be more than 0.");
throw new ObjectifyTransactionExceptionWrapper(illegalStateException);
} else {
if(limitTries == Integer.MAX_VALUE) {
result = ObjectifyService.ofy().transactNew(work);
} else {
result = ObjectifyService.ofy().transactNew(limitTries, work);
}
}
break;
case NOT_SUPPORTED :
case NEVER :
case MANDATORY :
result = ObjectifyService.ofy().execute(objectifyTransactional.propagation(), work);
break;
case REQUIRED :
case SUPPORTS :
ObjectifyService.ofy().transact(work);
break;
default:
break;
}
return result;
} catch (ObjectifyTransactionExceptionWrapper e) {
String packageName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
LOGGER.error("An exception occured while executing [{}.{}] in a transactional context."
, packageName, methodName, e);
throw e.getCause();
} catch (Throwable ex) {
String packageName = pjp.getSignature().getDeclaringTypeName();
String methodName = pjp.getSignature().getName();
String fullyQualifiedmethodName = packageName + "." + methodName;
throw new RuntimeException("Unexpected exception while executing ["
+ fullyQualifiedmethodName + "] in a transactional context.", ex);
}
}
}
Now the problem code part that i see is as follows in com.googlecode.objectify.impl.TransactorNo:
#Override
public <R> R transact(ObjectifyImpl<O> parent, Work<R> work) {
return this.transactNew(parent, Integer.MAX_VALUE, work);
}
#Override
public <R> R transactNew(ObjectifyImpl<O> parent, int limitTries, Work<R> work) {
Preconditions.checkArgument(limitTries >= 1);
while (true) {
try {
return transactOnce(parent, work);
} catch (ConcurrentModificationException ex) {
if (--limitTries > 0) {
if (log.isLoggable(Level.WARNING))
log.warning("Optimistic concurrency failure for " + work + " (retrying): " + ex);
if (log.isLoggable(Level.FINEST))
log.log(Level.FINEST, "Details of optimistic concurrency failure", ex);
} else {
throw ex;
}
}
}
}
private <R> R transactOnce(ObjectifyImpl<O> parent, Work<R> work) {
ObjectifyImpl<O> txnOfy = startTransaction(parent);
ObjectifyService.push(txnOfy);
boolean committedSuccessfully = false;
try {
R result = work.run();
txnOfy.flush();
txnOfy.getTransaction().commit();
committedSuccessfully = true;
return result;
}
finally
{
if (txnOfy.getTransaction().isActive()) {
try {
txnOfy.getTransaction().rollback();
} catch (RuntimeException ex) {
log.log(Level.SEVERE, "Rollback failed, suppressing error", ex);
}
}
ObjectifyService.pop();
if (committedSuccessfully) {
txnOfy.getTransaction().runCommitListeners();
}
}
}
transactOnce is by code / design always using a single transaction to do things. It will either commit or rollback the transaction. there is no provision to chain transactions like a normal enterprise app would want.... service -> calls multiple dao methods in a single transaction and commits or rollbacks depending on how things look.
keeping this in mind, i removed all annotations and transact method calls in my dao methods so that they don't start an explicit transaction and the aspect in service wraps the service method in transact and ultimately in transactOnce...so basically the service method is running in a transaction and no new transaction is getting fired again. This is a very basic scenario, in actual production apps services can call other service methods and they might have the annotation on them and we could still end up in a chained transaction..but anyway...that is a different problem to solve....
I know NoSQLs dont support write consistency at table or inter table levels so am I asking too much from google cloud datastore?

Choose Class in Birt is empty eventhough I have added jar in Datasource

Even though while creating dataset choose class window is empty. I am using Luna Service Release 2 (4.4.2).
From: http://yaragalla.blogspot.com/2013/10/using-pojo-datasource-in-birt-43.html
In the dataset class the three methods, “public void open(Object obj, Map map)”, “public Object next()” and “public void close()” must be implemented.
Make sure you have implemented these.
Here is a sample that I tested with:
public class UserDataSet {
public Iterator<User> itr;
public List<User> getUsers() throws ParseException {
List<User> users = new ArrayList<>();
// Add to Users
....
return users;
}
public void open(Object obj, Map<String, Object> map) {
try {
itr = getUsers().iterator();
} catch (ParseException e) {
e.printStackTrace();
}
}
public Object next() {
if (itr.hasNext())
return itr.next();
return null;
}
public void close() {
}
}

GWT - Tips Needed - Check and set parameter on the session. Is this the right way?

Im made a sort of autentication on my web application using GWT. So i make these functions in the GWTServiceImpl Class :
public class PageMenuLogin extends FlowPanel {
public PageMenuLogin() {
PageMenuLogin.getService().isSetSession(new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
InlineLabel err=new InlineLabel();
err.setText("Errore Di Connessione");
PageMenuLogin.this.add(err);
}
#Override
public void onSuccess(String result) {
if(result.compareTo("")==0) {
designLogin();
} else {
designLogout(result);
}
}
});
}
public final void designLogin() {
final InlineLabel menu_err=new InlineLabel("");
menu_err.setStyleName("menu_err");
this.add(menu_err);
Button menu_login_button=new Button("Login");
this.add(menu_login_button);
menu_login_button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
getService().checkLogin("nickname", "password", new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
menu_err.setText("Comunicazione Fallita");
}
#Override
public void onSuccess(Boolean result) {
if (result) {
// I LOAD THE PROFILE PAGE
} else {
menu_err.setText("Username e password non validi");
}
}
});
}
});
}
}
********************************************************************************
public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {
HttpServletRequest request;
HttpSession session;
public String isSetSession() {
this.request = this.getThreadLocalRequest();
this.session=this.request.getSession();
if(this.session.getAttribute("nickname")==null) {
return "";
} else {
return (String)this.session.getAttribute("nickname");
}
}
public boolean checkLogin(String username, String password) {
if("i check on the database if the user exist") {
this.session.setAttribute("nickname", value);
return true;
}
return false;
}
}
On client side, i call the GWTServiceImpl functions (server side), i check the return values and i do some operations.
Is this the right way to work with session on GWT? Any suggestion/tips/helps would be appreciated :)
Thanks for your time!!!
EDIT
New GWTServiceImpl :
public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {
HttpSession session;
public String isSetSession() {
HttpSession session=getThreadLocalRequest().getSession();
if(session.getAttribute("nickname")==null) {
return "";
} else {
return (String)session.getAttribute("nickname");
}
}
public boolean checkLogin(String nickname, String password) {
HttpSession session=getThreadLocalRequest().getSession();
Database mydb=Configuration.getDatabase();
mydb.connetti();
// faccio md5 ed escape
String log_check_user=nickname;
String log_check_pass=password;
// controllo che l'utente esista
ArrayList<String[]> db_result=null;
db_result=mydb.selectQuery("SELECT nickname FROM users WHERE nickname='"+log_check_user+"' AND password='"+log_check_pass+"'");
mydb.disconnetti();
if(!db_result.isEmpty()) {
session.setAttribute("nickname", nickname);
return true;
}
return false;
}
public boolean checkLogout() {
HttpSession session=getThreadLocalRequest().getSession();
session.invalidate();
return true;
}
}
Looks like it should work. I do a lot of work with GWT, although I often forego the use of the RemoteServiceServlet in favour of passing data back and forth via JSON.
A few suggestions, though. When you're calling a method or field within the same class, you don't need to include the this keyword. It doesn't hurt, but tends to make your code longer than it needs to be. Feel free to keep it though, if you find it makes things clearer for you.
Also, unless you've got methods that actually use the request, you don't need to create the request object; you can just do
session = getThreadLocalRequest().getSession();
A final suggestion: Since you're using the session in more than one method, it might be a good idea to initialize it right away; So, instead of initializing it in isSetSession(), you could just write HttpSession session = getThreadLocalRequest().getSession();, or initialize it in the class's constructor. As it stands now, if you happen to call checkLogin() before isSetSession(), you'll get a NullPointerException since session hasn't yet been initialized.

Resources