How to get AppSearch private api key in integration test - java

I am using EnterpriseElasticSearch (AppSearch) and ElasticSearch for my web application. In integration test I use testcontainer to setup real database. To call api of AppSearch you need to provide AppSearch api private key. My question is how to get private api key in my integration test?
Below is my config for AppSearch & ElasticSearch by using testcontainer
/**
* The base class for all integration test classes.
*/
public abstract class AbstractTest {
private static final Logger log = LoggerFactory.getLogger(AbstractTest.class);
// ElasticSearch
public static final String ELASTICSEARCH_VERSION = "7.12.0";
public static final String ELASTICSEARCH_USERNAME = "elastic";
private static final String ELASTICSEARCH_PASSWORD = "elasticsearch";
private static final String ELASTICSEARCH_HOSTNAME = "elasticsearch";
private static final int ELASTICSEARCH_PORT = 9200;
private static final Duration ELASTICSEARCH_STARTUP_TIMEOUT = Duration.ofMinutes(10);
private static final DockerImageName ELASTICSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch")
.withTag(ELASTICSEARCH_VERSION);
protected static final ElasticsearchContainer ELASTICSEARCH =
new ElasticsearchContainer(ELASTICSEARCH_IMAGE);
// EnterpriseSearch
private static final String APPSEARCH_HOSTNAME = "enterprisesearch";
private static final Duration APPSEARCH_STARTUP_TIMEOUT = Duration.ofMinutes(10);
private static final DockerImageName APPSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/enterprise-search/enterprise-search")
.withTag(ELASTICSEARCH_VERSION);
protected static final GenericContainer APPSEARCH =
new GenericContainer(APPSEARCH_IMAGE);
private static void startElasticSearch() {
ELASTICSEARCH.withPassword(ELASTICSEARCH_PASSWORD)
.withNetworkAliases(ELASTICSEARCH_HOSTNAME)
.withStartupTimeout(ELASTICSEARCH_STARTUP_TIMEOUT)
.start();
}
private static void startAppSearch() {
APPSEARCH.withNetworkAliases(APPSEARCH_HOSTNAME)
.withEnv("elasticsearch.host", String.format("http://%s:%s", ELASTICSEARCH_HOSTNAME, ELASTICSEARCH_PORT))
.withEnv("ent_search.auth.source", "standard")
.withEnv("elasticsearch.username", ELASTICSEARCH_USERNAME)
.withEnv("elasticsearch.password", ELASTICSEARCH_PASSWORD)
.withEnv("JAVA_OPTS", " $JAVA_OPTS -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8")
.withEnv("ENT_SEARCH_DEFAULT_PASSWORD", ELASTICSEARCH_PASSWORD)
.withEnv("allow_es_settings_modification", "true")
.withStartupTimeout(APPSEARCH_STARTUP_TIMEOUT)
.start();
}
}

Related

Unit Test for Redis cache in Java

Note: I already look at and tried some approaches on SO e.g. How to test Spring's declarative caching support on Spring Data repositories?, but as most of them old, I cannot make them work properly and I need a solution with the latest library versions. So, I would be appreciated if you have a look at the question and help.
#Service
#EnableCaching
#RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {
private static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
private final LabelTranslatableRepository translatableRepository;
private final LanguageService languageService;
#Override
public LabelDTO findByUuid(UUID uuid) {
final Label label = labelRepository.findByUuid(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
final List<LabelTranslatable> translatableList = translatableRepository.findAllByEntityUuid(uuid);
return new LabelDTO(Pair.of(label.getUuid(), label.getKey()), translatableList);
}
}
I created the following Unit Test to test caching for the nethod above:
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
#ExtendWith(MockitoExtension.class)
class TextLabelServiceImpl_deneme_Test {
#Autowired
private CacheManager cacheManager;
#InjectMocks
private LabelService labelService;
#Mock
private LabelRepository labelRepository;
#Mock
private LabelTranslatableRepository translatableRepository;
#Test
void test_Cache() {
UUID uuid = UUID.randomUUID();
final TextLabel textLabel = new TextLabel();
textLabel.setId(1);
textLabel.setKey("key1");
TextLabelTranslatable textLabelTranslatable = new TextLabelTranslatable();
textLabelTranslatable.setEntityUuid(uuid);
textLabelTranslatable.setLanguage(SupportedLanguage.fr);
textLabelTranslatable.setValue("value1");
final List<TextLabelTranslatable> translatableList = new ArrayList<>();
translatableList.add(textLabelTranslatable);
when(labelRepository.findByUuid(uuid)).thenReturn(Optional.of(textLabel));
when(translatableRepository.findAllByEntityUuid(uuid)).thenReturn(translatableList);
TextLabelDTO result1 = labelService.findByUuid(uuid);
TextLabelDTO result2 = labelService.findByUuid(uuid);
assertEquals(result1, result2);
Mockito.verify(translatableRepository, Mockito.times(1)).findAllByEntityUuid(uuid);
}
I am not sure if there is a missing part in my test, but at the last line (Mockito.verify()), it returns 2 instead of 1 that means caching not works. But it is working properly and there is a problem in my test I think. How should I complete the unit test to check the caching properly?
You need to annotate the service class method with #Cacheable. Try to follow the code in this tutorial. The following test code works as expected
#Import({CacheConfig.class, DemoServiceImpl.class})
#ExtendWith(SpringExtension.class)
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
class DemoServiceImplTest {
#MockBean
private LabelRepository labelRepository;
#Autowired
private DemoServiceImpl demoService;
#Autowired
private CacheManager cacheManager;
#TestConfiguration
static class EmbeddedRedisConfiguration {
private final RedisServer redisServer;
public EmbeddedRedisConfiguration() {
this.redisServer = new RedisServer();
}
#PostConstruct
public void startRedis() {
redisServer.start();
}
#PreDestroy
public void stopRedis() {
this.redisServer.stop();
}
}
#Test
void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() {
UUID id = UUID.randomUUID();
Label aLabel = new Label(id, "label");
Mockito.when(labelRepository.findById(id)).thenReturn(Optional.of(aLabel));
Label labelCacheMiss = demoService.findByUuid(id);
Label labelCacheHit = demoService.findByUuid(id);
Mockito.verify(labelRepository, Mockito.times(1)).findById(id);
}
}
With this service class code:
#Service
#RequiredArgsConstructor
#EnableCaching
public class DemoServiceImpl {
public static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
#Cacheable(value = CACHE_NAME)
public Label findByUuid(UUID uuid) {
return labelRepository.findById(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
}
}
And this CacheConfig:
#Configuration
public class CacheConfig {
#Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration(DemoServiceImpl.CACHE_NAME,
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));
}
#Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()));
}
}

Junit test case to mock convertor

I am trying to mock convertors method using 'when---thenReturn'
In my serviceTest file but still its throwing null pointer exception.
Is there any good way to mock convertor?
Thanks in advance.
For examples, you can refer to OOTB Test classes. (Note: The classes uses given-willReturn, but you can adjust it for when-thenReturn. These are just different approaches to testing using Mockito)
If you are looking for a Converter testing its attribute values, check de.hybris.platform.commercefacades.user.converters.populator.AddressPopulatorTest.
#UnitTest
public class AddressPopulatorTest
{
private AbstractPopulatingConverter<AddressModel, AddressData> addressConverter;
private final AddressPopulator addressPopulator = new AddressPopulator();
#Mock
private Map<String, Converter<AddressModel, StringBuilder>> addressFormatConverterMap;
#Mock
private Converter<AddressModel, StringBuilder> defaultAddressFormatConverter;
#Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
addressPopulator.setAddressFormatConverterMap(addressFormatConverterMap);
addressPopulator.setDefaultAddressFormatConverter(defaultAddressFormatConverter);
addressConverter = new ConverterFactory<AddressModel, AddressData, AddressPopulator>().create(AddressData.class,
addressPopulator);
}
#Test
public void testConvert()
{
final AddressModel addressModel = mock(AddressModel.class);
final PK pk = PK.parse("123");
final TitleModel titleModel = mock(TitleModel.class);
final CountryModel countryModel = mock(CountryModel.class);
given(addressModel.getPk()).willReturn(pk);
given(addressModel.getBillingAddress()).willReturn(Boolean.TRUE);
given(addressModel.getShippingAddress()).willReturn(Boolean.TRUE);
given(addressModel.getTitle()).willReturn(titleModel);
given(addressModel.getFirstname()).willReturn("firstName");
given(addressModel.getLastname()).willReturn("lastname");
given(titleModel.getName()).willReturn("titleName");
given(titleModel.getCode()).willReturn("titleCode");
given(addressModel.getCompany()).willReturn("companyName");
given(addressModel.getLine1()).willReturn("line1");
given(addressModel.getLine2()).willReturn("line2");
given(addressModel.getTown()).willReturn("town");
given(addressModel.getPostalcode()).willReturn("postalCode");
given(addressModel.getPhone1()).willReturn("phone");
given(addressModel.getEmail()).willReturn("email");
given(addressModel.getCountry()).willReturn(countryModel);
given(countryModel.getIsocode()).willReturn("countryCode");
given(countryModel.getName()).willReturn("countryName");
given(defaultAddressFormatConverter.convert(Mockito.any(AddressModel.class))).willReturn(
new StringBuilder("singleLineAddress"));
final AddressData addressData = addressConverter.convert(addressModel);
Assert.assertEquals("123", addressData.getId());
Assert.assertTrue(addressData.isBillingAddress());
Assert.assertTrue(addressData.isShippingAddress());
Assert.assertEquals("titleName", addressData.getTitle());
Assert.assertEquals("titleCode", addressData.getTitleCode());
Assert.assertEquals("firstName", addressData.getFirstName());
Assert.assertEquals("lastname", addressData.getLastName());
Assert.assertEquals("companyName", addressData.getCompanyName());
Assert.assertEquals("line1", addressData.getLine1());
Assert.assertEquals("line2", addressData.getLine2());
Assert.assertEquals("town", addressData.getTown());
Assert.assertEquals("postalCode", addressData.getPostalCode());
Assert.assertEquals("phone", addressData.getPhone());
Assert.assertEquals("email", addressData.getEmail());
Assert.assertEquals("countryCode", addressData.getCountry().getIsocode());
Assert.assertEquals("countryName", addressData.getCountry().getName());
}
}
If you are looking for a Facade that is using a Converter, check de.hybris.platform.commercefacades.customer.impl.DefaultCustomerFacadeTest
#UnitTest
public class DefaultCustomerFacadeTest
{
private static final String TEST_DUMMY = "dummy";
private static final String TEST_OLD_PASS = "oldPass";
private static final String TEST_NEW_PASS = "newPass";
private static final String TEST_USER_UID = "testUid";
private static final String TEST_TOKEN = "token";
private DefaultCustomerFacade defaultCustomerFacade;
#Mock
private UserService userService;
#Mock
private UserModel user;
#Mock
private CustomerAccountService customerAccountService;
#Mock
private ModelService mockModelService;
#Mock
private AbstractPopulatingConverter<AddressModel, AddressData> addressConverter;
#Mock
private AbstractPopulatingConverter<UserModel, CustomerData> customerConverter;
#Mock
private AddressReversePopulator addressReversePopulator;
#Mock
private AbstractPopulatingConverter<CreditCardPaymentInfoModel, CCPaymentInfoData> creditCardPaymentInfoConverter;
#Mock
private CommonI18NService commonI18NService;
#Mock
private StoreSessionFacade storeSessionFacade;
#Mock
private CartService cartService;
#Mock
private CommerceCartService commerceCartService;
#Mock
private UserFacade userFacade;
#Mock
private SessionService sessionService;
#Mock
private OrderFacade orderFacade;
#Mock
private CartCleanStrategy cartCleanStrategy;
private CustomerModel customerModel;
private CustomerModel guestCustomerModel;
private AddressModel addressModel;
private AddressModel addressModel2;
private AddressData addressData;
private CreditCardPaymentInfoModel creditCardPaymentInfoModel;
private CCPaymentInfoData ccPaymentInfoData;
private CustomerNameStrategy customerNameStrategy;
private CurrencyData defaultCurrencyData;
private LanguageData defaultLanguageData;
protected static class MockAddressModel extends AddressModel
{
private final long id;
public MockAddressModel(final long id)
{
this.id = id;
}
#Override
public PK getPk()
{
return de.hybris.platform.core.PK.fromLong(id);
}
}
#Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
defaultCustomerFacade = new DefaultCustomerFacade();
defaultCustomerFacade.setUserService(userService);
defaultCustomerFacade.setModelService(mockModelService);
defaultCustomerFacade.setCustomerAccountService(customerAccountService);
defaultCustomerFacade.setAddressConverter(addressConverter);
defaultCustomerFacade.setCustomerConverter(customerConverter);
defaultCustomerFacade.setAddressReversePopulator(addressReversePopulator);
defaultCustomerFacade.setCreditCardPaymentInfoConverter(creditCardPaymentInfoConverter);
defaultCustomerFacade.setCommonI18NService(commonI18NService);
defaultCustomerFacade.setStoreSessionFacade(storeSessionFacade);
defaultCustomerFacade.setCartService(cartService);
defaultCustomerFacade.setCommerceCartService(commerceCartService);
defaultCustomerFacade.setUserFacade(userFacade);
defaultCustomerFacade.setSessionService(sessionService);
defaultCustomerFacade.setOrderFacade(orderFacade);
defaultCustomerFacade.setCartCleanStrategy(cartCleanStrategy);
customerNameStrategy = new DefaultCustomerNameStrategy();
defaultCustomerFacade.setCustomerNameStrategy(customerNameStrategy);
addressModel = new MockAddressModel(9999L);
addressModel2 = new MockAddressModel(8888L);
addressData = new AddressData();
addressData.setId("9999");
customerModel = new CustomerModel();
customerModel.setDefaultShipmentAddress(addressModel2);
creditCardPaymentInfoModel = new CreditCardPaymentInfoModel();
final List<CreditCardPaymentInfoModel> creditCards = new ArrayList<CreditCardPaymentInfoModel>();
creditCards.add(creditCardPaymentInfoModel);
ccPaymentInfoData = new CCPaymentInfoData();
guestCustomerModel = new CustomerModel();
guestCustomerModel.setUid(TEST_USER_UID + "|" + TEST_DUMMY);
guestCustomerModel.setDefaultShipmentAddress(addressModel);
guestCustomerModel.setDefaultPaymentAddress(addressModel2);
given(addressConverter.convert(addressModel)).willReturn(addressData);
given(creditCardPaymentInfoConverter.convert(creditCardPaymentInfoModel)).willReturn(ccPaymentInfoData);
given(userService.getCurrentUser()).willReturn(customerModel);
given(customerAccountService.getAddressForCode(customerModel, "9999")).willReturn(addressModel);
given(customerAccountService.getCreditCardPaymentInfos(customerModel, true)).willReturn(creditCards);
given(customerAccountService.getCreditCardPaymentInfoForCode(customerModel, "code")).willReturn(creditCardPaymentInfoModel);
given(mockModelService.create(CustomerModel.class)).willReturn(new CustomerModel());
defaultCurrencyData = new CurrencyData();
defaultCurrencyData.setIsocode("GBP");
defaultLanguageData = new LanguageData();
defaultLanguageData.setIsocode("en");
given(storeSessionFacade.getDefaultCurrency()).willReturn(defaultCurrencyData);
given(storeSessionFacade.getDefaultLanguage()).willReturn(defaultLanguageData);
}

How work with immutable object in mongodb and lombook without #BsonDiscriminator

I tried to work with immutable objects in MongoDB and Lombok. I found a solution to my problem but it needs to write additional code from docs but I need to used Bson annotations and create a constructor where describes fields via annotations. But if I user #AllArgsConstructor catch exception: "Cannot find a public constructor for 'User'" because I can't use default constructor with final fields. I think i can customize CodecRegistry correctly and the example will work correctly but I couldn't find solution for it in docs and google and Stackoverflow.
Is there a way to solve this problem?
#Data
#Builder(builderClassName = "Builder")
#Value
#BsonDiscriminator
public class User {
private final ObjectId id;
private final String name;
private final String pass;
private final String login;
private final Role role;
#BsonCreator
public User(#BsonProperty("id") final ObjectId id,
#BsonProperty("name") final String name,
#BsonProperty("pass") final String pass,
#BsonProperty("login") final String login,
#BsonProperty("role") final Role role) {
this.id = id;
this.name = name;
this.pass = pass;
this.login = login;
this.role = role;
}
#AllArgsConstructor
public enum Role {
USER("USER"),
ADMIN("ADMIN"),
GUEST("GUEST");
#Getter
private String value;
}
public static class Builder {
}
}
Example for MongoDB where I create, save and then update users:
public class ExampleMongoDB {
public static void main(String[] args) {
final MongoClient mongoClient = MongoClients.create();
final MongoDatabase database = mongoClient.getDatabase("db");
database.drop();
final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
final MongoCollection<User> users = database.getCollection("users", User.class).withCodecRegistry(pojoCodecRegistry);
users.insertMany(new ExampleMongoDB().getRandomUsers());
System.out.println("Before updating:");
users.find(new Document("role", "ADMIN")).iterator().forEachRemaining(
System.out::println
);
System.out.println("After updating:");
users.updateMany(eq("role", "ADMIN"), set("role", "GUEST"));
users.find(new Document("role", "GUEST")).iterator().forEachRemaining(
System.out::println
);
}
public List<User> getRandomUsers() {
final ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 15; i++) {
users.add(
User.builder()
.login("log" + i)
.name("name" + i)
.pass("pass" + i)
.role(
(i % 2 == 0) ? User.Role.ADMIN : User.Role.USER
).build()
);
}
return users;
}
}
This should work (it worked for me):
#Builder(builderClassName = "Builder")
#Value
#AllArgsConstructor(onConstructor = #__(#BsonCreator))
#BsonDiscriminator
public class User {
#BsonId
private final ObjectId _id;
#BsonProperty("name")
private final String name;
#BsonProperty("pass")
private final String pass;
#BsonProperty("login")
private final String login;
#BsonProperty("role")
private final Role role;
}
Then in lombok.config add these (in your module/project directory):
lombok.addLombokGeneratedAnnotation=true
lombok.anyConstructor.addConstructorProperties=true
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonProperty
lombok.copyableAnnotations += org.bson.codecs.pojo.annotations.BsonId
Also piece of advice, keep _id if you are going to use automatic conversion to POJOs using PojoCodec, which will save a lot of trouble.

failed to connect to 192.168.95.2 on port 80

I'm trying to run my android app on real android device and i put the IPv4 address as URL , but i get an error that says failed to connect to 192.168.95.2 on port 80 , i tried all things in previous questions but didn't work out also checked my permissions and make sure that i added internet permission :/
here is the code :
public class Constants {
public static final String BASE_URL = "http://192.168.95.2/";
public static final String REGISTER_OPERATION = "register";
public static final String LOGIN_OPERATION = "login";
public static final String CHANGE_PASSWORD_OPERATION = "chgPass";
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String IS_LOGGED_IN = "isLoggedIn";
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String UNIQUE_ID = "unique_id";
public static final String TAG = "Learn2Crack";

Junit mokito util.properties show null after moking

I write a email testing using greenmail and JUNIT with mokito but
when I use
when(emailproperties.getUsername()).thenReturn("abc#gmail.com");
show null
Here is my code
public class EmailServiceImplTest {
#InjectMocks
EmailServiceImpl emailServiceImpl = new EmailServiceImpl();
#Mock
private MessageTemplateService messageTemplateService;
#Mock
private EmailProperties emailProperties;
//private static final Logger LOGGER = Logger.getLogger(EmailServiceImplTest.class);
private GreenMail greenMail;
private static final String USER_NAME = "hascode";
private static final String EMAIL_USER_ADDRESS = "hascode#localhost";
private static final String EMAIL_TO = "someone#localhost.com";
private static final String EMAIL_SUBJECT = "Test E-Mail";
private static final String EMAIL_TEXT = "This is a test e-mail.";
private static final String LOCALHOST = "localhost";
private static final String USER_PASSWORD = "abcdef123";
#Before
public void testSmtpInit() {
MockitoAnnotations.initMocks(this);
greenMail = new GreenMail(ServerSetupTest.SMTP);
greenMail.start();
greenMail.setUser(EMAIL_USER_ADDRESS, USER_NAME, USER_PASSWORD);
}
#Test
public void sendContactEmail() {
MessageTemplate mock_template=new MessageTemplate();
mock_template.setId(2);
mock_template.setBody("Hi ${name} want to contact");
mock_template.setSubject("Contact EMAIL");
ContactDTO mock_Dto=new ContactDTO();
mock_Dto.setFirstName("abc");
mock_Dto.setLastName("xyz");
Properties mock_props = System.getProperties();
mock_props.put("mail.smtp.host", LOCALHOST);
mock_props.put("mail.smtp.auth", "true");
mock_props.put("mail.smtp.port", ServerSetupTest.SMTP.getPort());
mock_props.put("mail.debug", "true");
when(messageTemplateService.getMessageTemplateById("2")).thenReturn(mock_template);
emailProperties.setAdminTo("abc#mail.com");
when(emailProperties.getAdminTo()).thenReturn("abc#mail.com");
when(emailProperties.getContactMsgKey()).thenReturn("2");
when(emailProperties.getProps()).thenReturn(mock_props);
when(emailProperties.getSenderEmail()).thenReturn(EMAIL_USER_ADDRESS);
when(emailProperties.getSender()).thenReturn(USER_NAME);
when(emailProperties.getHost()).thenReturn(LOCALHOST);
when(emailProperties.getUserName()).thenReturn(EMAIL_USER_ADDRESS);
when(emailProperties.getPassword()).thenReturn(USER_PASSWORD);
emailServiceImpl.sendContactEmail(mock_Dto);
MimeMessage[] messages = greenMail.getReceivedMessages();
assertNotNull(messages);
assertEquals(1, messages.length);
}
when I debug it show null what I am doing wronge
Yes Done.Change to #spy
#Mock
private EmailProperties emailProperties;
and set the value as it is.
15 days effort end to day.

Categories