cannot get docker image while using TestContainer - elasticsearch

I am having a junit test written using test container (https://www.testcontainers.org/). when I run my test I get the following stack trace.
com.github.dockerjava.api.exception.UnauthorizedException: Status 401: {"message":"Get https://registry-1.docker.io/v2/testcontainers/ryuk/manifests/0.3.1: unauthorized: incorrect username or password"}
at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:239)
at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.lambda$executeAndStream$1(DefaultInvocationBuilder.java:269)
at java.lang.Thread.run(Thread.java:748)
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 6.797 sec <<< FAILURE! - in com.openmind.primecast.web.rest.MessageHistoryReportingResourceIntTest
com.openmind.primecast.web.rest.MessageHistoryReportingResourceIntTest Time elapsed: 6.796 sec <<< ERROR!
org.testcontainers.containers.ContainerFetchException: Can't get Docker image: RemoteDockerImage(imageName=docker.elastic.co/elasticsearch/elasticsearch:7.11.2, imagePullPolicy=DefaultPullPolicy())
at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1286)
at org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:615)
at org.testcontainers.elasticsearch.ElasticsearchContainer.<init>(ElasticsearchContainer.java:73)
at com.openmind.primecast.web.rest.MessageHistoryReportingResourceIntTest.startElasticServer(MessageHistoryReportingResourceIntTest.java:132)
Caused by: com.github.dockerjava.api.exception.UnauthorizedException: Status 401: {"message":"Get https://registry-1.docker.io/v2/testcontainers/ryuk/manifests/0.3.1: unauthorized: incorrect username or password"}
at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:239)
at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.lambda$executeAndStream$1(DefaultInvocationBuilder.java:269)
at java.lang.Thread.run(Thread.java:748)
2021-03-24 20:30:31.584 WARN --- [r1-nio-worker-1] io.netty.channel.DefaultChannelPipeline : An exception '{}' [enable DEBUG level for full stacktrace] was thrown by a user handler's exceptionCaught() method while handling the following exception:
This is the code in the my junit test . Basically its trying to download elastic search docker image with version 7.11.2 . However i am unable to do so and an error is thrown on the console when i run my junit test.
public class MessageHistoryReportingResourceIntTest extends AbstractCassandraTest {
/**
* Elasticsearch version which should be used for the Tests
*/
private static final String ELASTICSEARCH_VERSION = "7.11.2";
private static final DockerImageName ELASTICSEARCH_IMAGE = DockerImageName
.parse("docker.elastic.co/elasticsearch/elasticsearch").withTag(ELASTICSEARCH_VERSION);
#BeforeClass
public static void startElasticServer() throws Exception {
container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE);
container.start();
}
}
this is my docker version
-bash-4.2$ docker --version
Docker version 17.03.1-ce_omn3, build 9b1cd46
in the pom.xml i have added the library
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>elasticsearch</artifactId>
<version>1.15.2</version>
<scope>test</scope>
</dependency>
appreciate if you can help
thank you

Apparently in https://github.com/testcontainers/testcontainers-java/issues/5121#issuecomment-1102909375 they suggested the following:
docker login index.docker.io
which fix my problem

Related

How can I get my Maven/Mockito mock MVC test to print out a more detailed stack trace?

I'm using JUnit 5 and the spring-boot-starter-test (v 1.5) for Maven. I would want to test a controller method using mock MVC ...
#ExtendWith(MockitoExtension.class)
public class MyControllerTest {
...
MockMvc mockMvc;
...
#BeforeEach
public void setup() throws Exception {
...
mockMvc =
MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new RestResponseEntityExceptionHandler())
.build();
}
void testGetMethod() throws Exception {
... mocking ...
mockMvc
.perform(get("/mypath").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
Is there a way to get a more verbose stack trace when the test fails? When I run the test and there is a NullPointerException within the controller, the stack trace only prints the line where the unit test was failing
> mvn clean test -Dtest=MyControllerTest
...
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.676 s <<< FAILURE! - in com.rmyco.feature.controller.MyControllerTest
[ERROR] com.rmyco.feature.controller.MyControllerTest.testGetMethod Time elapsed: 1.663 s <<< ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at com.rmyco.feature.controller.MyControllerTest.testGetMethod(MyControllerTest.java:103)
Caused by: java.lang.NullPointerException
at com.rmyco.feature.controller.MyControllerTest.testGetMethod(MyControllerTest.java:103)
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] MyControllerTest.testGetMethod:103 ยป NestedServlet
I would like to know the exact line in the controller where things were blowing up.

Starting RabbitMq as GenerigContainer in Gitlab Ci

I have a Spring Boot 2.1 Application which has integration tests. For integration tests purposes i want start a RabbitMq container with testcontainers framework. When I start those on my local machine everything seems to work i can access my rabbitMQ during the IT tests. However once i execute under gitlab-ci i constantly get connection refused exceptions
Here is my application-it-properties
spring.rabbitmq.host=localhost
spring.rabbitmq.virtualHost=/
spring.rabbitmq.port=5673
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.dynamic=true
spring.rabbitmq.template.retry.enabled=true
spring.rabbitmq.listener.simple.acknowledgeMode=AUTO
spring.rabbitmq.listener.simple.concurrency=5
This is my verify step in gitlab-ci
verify:feature:
stage: verify
script:
- git config --global user.email gitlab#test.de
- git config --global user.name gitlab
- git fetch --all
- git checkout origin/develop
- git merge $CI_BUILD_REF --no-commit --no-ff
- mvn $MAVEN_CLI_OPTS verify sonar:sonar $SONAR_PREVIEW_CLI_OPTS
only:
- /feature.*/
And this is how i start my testcontainer RabbitMQ
#Slf4j
#RunWith(SpringRunner.class)
#TestPropertySource(locations = {"classpath:application-it.properties"})
#SpringBootTest
public class TransformerServiceApplicationIt {
private static final int EXPOSED_RABBITMQ_PORT = 5672;
private static final int EXPORTED_RABBITMQ_PORT = 5673;
/**
* Start the rabbitmq.
*/
static {
final Consumer<CreateContainerCmd> rabbitCmd = e -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(EXPORTED_RABBITMQ_PORT), new ExposedPort(EXPOSED_RABBITMQ_PORT)));
final GenericContainer rabbitMq = new GenericContainer("rabbitmq:3-management").withExposedPorts(EXPOSED_RABBITMQ_PORT)
.withCreateContainerCmdModifier(rabbitCmd);
rabbitMq.start();
}....
}
And this is my exception
[org.springframework.amqp.rabbit.core.RabbitTemplate]: Factory method 'rabbitTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itRabbitMQConfig': Invocation of init method failed; nested exception is org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)
My guess is that it has something to do with the hostname resolving for localhost on gitlab.
Try this:
static {
final GenericContainer rabbitMq = new GenericContainer("rabbitmq:3-management").withExposedPorts(EXPOSED_RABBITMQ_PORT);
rabbitMq.start();
// Pass the properties directly to the app. Do not use properties file.
System.setProperty("spring.rabbitmq.host", rabbitMq.getContainerIpAddress());
System.setProperty("spring.rabbitmq.port", rabbitMq.getMappedPort(5672).toString());
}

spring boot stater parent 2.0.1 entityManagerFactory Bean creation exception

I am getting following error when I change my spring boot stater parent 1.5.9 RELEASE to 2.0.1 RELEASE
target/surefire-reports
-------------------------------------------------------------------------------
Test set: com.restapispringboot.RestApiSpringbootApplicationTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.158 s <<< FAILURE! - in com.restapispringboot.RestApiSpringbootApplicationTests
contextLoads(com.restapispringboot.RestApiSpringbootApplicationTests) Time elapsed: 0.001 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
Caused by: java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
Caused by: java.lang.ClassNotFoundException: javassist.bytecode.ClassFile
Could it be something in my config that I need to change to make it work?
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/boot_rest_api
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
# spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.ddl-auto=create
logging.level.root=DEBUG
Application main
#SpringBootApplication
#EnableJpaRepositories("com.restapispringboot.repo")
#EntityScan("com.restapispringboot.model")
public class RestApiSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(RestApiSpringbootApplication.class, args);
}
}
Entity
#Entity
#Table(name = "customer")
public class Customer implements Serializable {
// getters and setters
}
Repo
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
Update
I just notice when I mvn clean install I also get the following errors. But I checked my build path both JRE[JavaSE-1.8] and maven dependencies are build path...
ERROR] error reading /Users/erichuang/.m2/repository/org/aspectj/aspectjweaver/1.8.13/aspectjweaver-1.8.13.jar; invalid CEN header (bad signature)
[ERROR] error reading /Users/erichuang/.m2/repository/org/javassist/javassist/3.22.0-GA/javassist-3.22.0-GA.jar; invalid LOC header (bad signature)
As discussed in the comments, your error says, java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile.
As you were migrating from spring boot version 1.5.9 RELEASE to 2.0.1 RELEASE, there might be some conflict in the javassist jar (3.20.0-GA vs 3.22.0-GA).
So you can clean your maven repo (delete the localRepository) and run your command once again.

SpringBoot Fails now when I switch from spring data neo4j 4.1.3 to 5.0.0

Background
I have an application with spring data neo4j, and I switched from 4.1.3 to 5.0.0.
I believe that I have made all the necessary changes to convert my code over but I still get errors.
My current version of spring boot is
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
Problem
When I run: mvn spring-boot:run in the command line,
I get an error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field actionRepository in myproject.service.ActionServiceImpl required a bean of type 'myproject.repository.ActionRepository' that could not be found.
Action:
Consider defining a bean of type 'myproject.repository.ActionRepository' in your configuration
My myproject.Application.java is currently
#SpringBootApplication
#EnableTransactionManagement
#EnableSwagger2
#EntityScan(basePackages = "myproject.domain")
public class Application {
public static void main(String[] args) {
new SpringApplication(Application.class).run(args);
}
#Bean
public Docket Api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.apiInfo(apiInfo());
}
private springfox.documentation.service.ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Service API")
}
}
And this does not find any of my controllers like myproject.controller.ActionController.java which contains
...
#RestController
#Api(value = "Action", description = "Actions Management API")
#RequestMapping(value = "/api/action")
public class ActionController extends Controller<Action> {
...
Attempt #1
If I add the annotation #ComponentScan({"myproject.request"}) to my Application class, the error goes away, but spring boot cannot load any controllers and as such my Swagger shows no APIs and no controllers are run. This is not the solution. #SpringBootApplication should take care of all this.
Question
How do I reconfig spring boot to start working like it did in version 4.1.3 of spring data neo4j?
UPDATE 1 ATTEMPT #2
I tried adding this annotation to my class Application
#EnableNeo4jRepositories("myproject.repository")
And the error changed to something less clean:
...
2017-10-05 13:19:46.992 ERROR 561 --- [ main] o.s.boot.SpringApplication : Application startup failed
java.lang.NoSuchMethodError: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional;
at org.springframework.data.neo4j.repository.config.Neo4jRepositoryConfigurationExtension.postProcess(Neo4jRepositoryConfigurationExtension.java:110) ~[spring-data-neo4j-5.0.0.RELEASE.jar:5.0.0.RELEASE]
at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:130) ~[spring-data-commons-1.12.0.RELEASE.jar:na]
at org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport.registerBeanDefinitions(RepositoryBeanDefinitionRegistrarSupport.java:83) ~[spring-data-commons-1.12.0.RELEASE.jar:na]
...
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.1.RELEASE:run (default-cli) on project myproject: An exception occurred while running. null: InvocationTargetException: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional; -> [Help 1]
[ERROR]
...
UPDATE 2
In an attempt to use the #EnableNeo4jRepositories("myproject.repository") and bypass the error in Update 1, I tried:
mvn clean install spring-boot:repackage
And it gave a Build Success, but the same error persists:
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.1.RELEASE:run (default-cli) on project myproject: An exception occurred while running. null: InvocationTargetException: org.springframework.data.repository.config.RepositoryConfigurationSource.getAttribute(Ljava/lang/String;)Ljava/util/Optional; -
UPDATE 3
I have the new annotation and changed my pom from:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.12.0.RELEASE</version>
</dependency>
to
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
and now mvn spring-boot:run
gives the error:
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'getSessionFactory' that could not be found.
Action:
Consider defining a bean named 'getSessionFactory' in your configuration.
Try adding this annotation on your configuration class :
#EnableNeo4jRepositories("myproject.repository")
Update :
I just saw you're on Spring boot 1.4. SDN 5 is only compatible with Spring Boot 2.0.
Details are in the compatibility table.

Maven surefire tests failing in Spring framework project

Maven is unable to successfully run my JUnit tests though they are being run without any problem on my Eclipse. I'm unable to solve it from the debug messages.
It is probably something to do with the Spring config because my other JUnit tests not relying on Spring are working fine.
Adding the surefire plugin forkMode as Always didn't work either.
Maven output
mvn install ... ... [INFO] --- maven-surefire-plugin:2.10:test (default-test) # AppServer --- [INFO] Surefire report directory:
C:..\surefire-reports
Running com.ws.impl.BrowserServiceImplTest Tests run: 2, Failures: 2,
Errors: 0, Skipped: 0, Time elapsed: 0.016 sec <<< FAILURE!
Failed tests: com.ws.impl.BrowserServiceImplTest.testGetStatuses()
com.ws.impl.BrowserServiceImplTest.testGetSellers()
Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:test-context.xml")
public class BrowserServiceImplTest {
#Autowired
private BrowserServiceImpl browserServiceImpl;
#Test
public void testGetStatuses() {
// test code
}
// more code
}
Surefire report
<failure type="java.lang.NullPointerException">java.lang.NullPointerException
at com.ws.impl.BrowserServiceImplTest.testGetStatuses(BrowserServiceImplTest.java:48)
</failure>
Edit
Lines 48-49
List<String> statuses = browserServiceImpl.getStatuses();
assertEquals(12, statuses.size());
Edit 2
test-context.xml
<bean id="browserSvc" class="com.ws.impl.BrowserServiceImpl">
<property name="filterOptionsService" ref="filterOptionsService" />
</bean>
BrowserServiceImpl.java
#WebService(targetNamespace = "http://abc.def.com", portName = "BrowserPort", serviceName = "BrowserService")
public class BrowserServiceImpl implements BrowserService {
private FilterOptionsService filterOptionsService;
// more code
}

Resources