Could not find a valid Docker environment when using Gradle Shared Build Service (`ClassNotFoundException` when loading strategies)
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 4/5
- Tempo estimado
- 3-5 dias
- Facilidade para iniciantes
- 25/100
- Tipo de issue
- Bug
- Clareza
- Precisa de esclarecimento
- Status de atividade
- Estagnada
- Stack de tecnologia
- docker, java, mysql
- Domínio
- build-system, databases, devops, testing
Direção de pesquisa
Comece pelo Gradle buildscript e pelo MySQLContainerService mostrados no relatório, depois reproduza :startMySQLContainer com --stacktrace e inspecione a ClassNotFoundException e os logs de descoberta do ambiente Docker. Considera-se concluído quando for identificado por que o classpath do serviço compartilhado ou o carregamento da estratégia diferem entre as execuções e for confirmada uma resolução documentada ou testada para a sequência de build relatada.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Discussed in https://github.com/testcontainers/testcontainers-java/discussions/9034
Originally posted by debapgithub July 30, 2024
Hi,
I am new to testcontainers and setting up for a gradle service where I wanted to achieve the following in sequence.
When gradle build command will run : ./gradlew clean build
- MySql Testcontainer should start
- DB migrations should apply against the testcontainer DB
- generateJooq task should execute against the testcontainer DB
- Run the integration tests against testcontainer
- At the end of the build process, testcotnainer should stop automatically.
I have tried starting MySql testcontainer as a gradle task and I was able to execute the following tasks properly except one issue due to which I have decided to switch to another approach where I can start the MySql testcontainer as a gradle Shared service so that it will automaticllay manage the testcontainer lifecycle.
Here is the code which will start the testcontainer as a gradle shared service and it worked fine as well. But next day when I tried running the gradle command, I started getting the below error.
Error
* What went wrong:
Execution failed for task ':startMySQLContainer'.
> Failed to create service 'mysqlContainerService'.
> Could not create an instance of type MySQLContainerService.
> Could not find a valid Docker environment. Please see logs and check configuration
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.
Gradle Code
import org.testcontainers.containers.MySQLContainer;
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
buildscript {
repositories {
maven {
name repoName
url repoUrl
credentials() {
username = repoUsername
password = repoPassword
}
}
}
dependencies {
classpath "org.testcontainers:testcontainers:${dependencyManagement.importedProperties['testcontainers.version']}"
classpath "org.testcontainers:mysql:${dependencyManagement.importedProperties['testcontainers.version']}"
classpath "com.mysql:mysql-connector-j:${dependencyManagement.importedProperties['mysql.version']}"
}
}
// Here we register service for providing our database during the build.
gradle.sharedServices.registerIfAbsent('mysqlContainerService', MySQLContainerService) { spec ->
spec.parameters.databaseSchemaName.set(project.ext.databaseSchemaName)
}
/**
* Build service for providing database container.
*/
abstract class MySQLContainerService implements BuildService<MySQLContainerService.Params>, AutoCloseable {
interface Params extends BuildServiceParameters {
Property<String> getDatabaseSchemaName()
}
private final MySQLContainer mysqlContainer;
@javax.inject.Inject
MySQLContainerService(Params params) {
// Services are initialized lazily, on first request to them, so we start container immediately.
long startTime = System.currentTimeMillis()
println("DB Schema Name: ${params.getDatabaseSchemaName().get()}")
mysqlContainer = new MySQLContainer(MySQLContainer.IMAGE).withDatabaseName(params.getDatabaseSchemaName().get())
mysqlContainer.start()
long duration = System.currentTimeMillis() - startTime
println("MySQL Testcontainer Started successfully with URL: ${mysqlContainer.getJdbcUrl()}. Total time taken: ${duration} ms")
}
String getJdbcUrl() {
return mysqlContainer.getJdbcUrl()
}
String getUsername() {
return mysqlContainer.getUsername()
}
String getPassword() {
return mysqlContainer.getPassword()
}
String getDriverClassName() {
return mysqlContainer.getDriverClassName()
}
@Override
void close() {
// Ensure to stop container in the end
if (mysqlContainer != null) {
try {
mysqlContainer.stop()
println("MySQL container stopped successfully.")
} catch (Exception e) {
println("Failed to stop MySQL container: ${e.message}")
}
} else {
println("MySQL container is already null (was not started).")
}
}
}
tasks.register('startMySQLContainer') {
doLast {
gradle.sharedServices.getRegistrations().getByName('mysqlContainerService')
}
}
// Ensure the integrationTest uses the same container and stops it after
tasks.named('integrationTest').configure {
dependsOn 'startMySQLContainer'
doFirst {
def service = gradle.sharedServices.getRegistrations().getByName('mysqlContainerService').service.get()
systemProperty 'spring.datasource.url', service.getJdbcUrl()
systemProperty 'spring.datasource.username', service.getUsername()
systemProperty 'spring.datasource.password', service.getPassword()
systemProperty 'spring.datasource.driver-class-name', service.getDriverClassName()
}
doLast {
systemProperties.remove('spring.datasource.url')
systemProperties.remove('spring.datasource.username')
systemProperties.remove('spring.datasource.password')
systemProperties.remove('spring.datasource.driver-class-name')
}
}
Not sure whats going wrong and how it worked first time when I did this code.
Thanks in advance!!
-Deba
- Linguagem predominante
- Java
- Estrelas
- 8.8k
- Forks
- 2k
- Merge médio
- 5d 21h
- PRs com merge (30d)
- 15
Preparar o ambiente
Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.
- Inclui um Dockerfile ou arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de testcontainers/testcontainers-java
-
[Bug]: withStartupTimeout() changes the startup timeout of all containers that use the default wait strategyTalvez já em andamento @aymenjamaaoui assumiu há 1 dia. Abertatype/bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 64/100
testcontainers/testcontainers-java#12171 ·
Mantenedores costumam responder em até 1 dia
-
[Enhancement]: Document why singleton containers are required under Spring's test context cachingTalvez já em andamento @zakaullah075 assumiu há 95 dias. Abertatype/enhancement
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 85/100
testcontainers/testcontainers-java#11967 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
[Bug]: Cannot reuse Selenium BrowserWebDriverContainers under LinuxTalvez já em andamento @kdelay assumiu há 116 dias. Abertatype/bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
testcontainers/testcontainers-java#11941 ·
Mantenedores costumam responder em até 1 dia
-
[Bug]: DockerDesktopClientProviderStrategy is always applicableTalvez já em andamento @seonwooj0810 assumiu há 165 dias. Abertatype/bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 74/100
testcontainers/testcontainers-java#11829 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
[Enhancement]: cleanup document after removing junit4 supportTalvez já em andamento @SJvaca30 assumiu há 173 dias. Abertatype/enhancement
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
testcontainers/testcontainers-java#11578 ·
Mantenedores costumam responder em até 1 dia
Todas as issues de testcontainers/testcontainers-java
Issues semelhantes
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 68/100
pact-foundation/pact-plugins#125 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 66/100
opencollab/flexdock#28 · 1 comentário ·
-
Page header disappearsAbertaMVP
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
OpenConext/OpenConext-access#1145 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 85/100
yegor256/jping#122 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 75/100
SAP/ai-sdk-java#1206 ·
Mantenedores costumam responder em até 1 dia