Kotlin test Не удалось проверить соединение mariadb, в конечном итоге не удается с таблицей не выходит - PullRequest
1 голос
/ 20 мая 2019

Получая следующую ошибку, когда я запускаю свои тесты, это проект Kotlin, я запускаю свои тесты снова со встроенной версией Mariadb, эта ошибка отсутствует, когда я запускаю тестовый автономный тест из IntelliJ , Похоже, это может быть проблема тайм-аута с созданием таблицы. Эта таблица, о которой упоминается в журнале, создается в других тестах.

[INFO] Running com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT
2019-05-20 17:31:50.049  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@678c1c13 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.055  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@4c8a0916 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.056  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@3d189ad8 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.057  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@110ff601 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.060  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@2cdda367 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.061  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@43bcef96 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.063  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@6bfcf5f (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.064  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@62a8e057 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.065  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@19fc522c (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
2019-05-20 17:31:50.066  WARN 45164 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-84 - Failed to validate connection org.mariadb.jdbc.MariaDbConnection@19201d11 (Connection.setNetworkTimeout cannot be called on a closed connection). Possibly consider using a shorter maxLifetime value.
Hibernate: select reportdefi0_.id as id1_9_, reportdefi0_.delivery_policy as delivery2_9_, reportdefi0_.enabled as enabled3_9_, reportdefi0_.name as name4_9_, reportdefi0_.parameter_policy as paramete5_9_, reportdefi0_.pipeline as pipeline6_9_, reportdefi0_.scheduling_policy as scheduli7_9_, reportdefi0_.schema_name as schema_n8_9_, reportdefi0_.transformation_policy as transfor9_9_ from report_definition reportdefi0_
2019-05-20 17:31:50.114  WARN 45164 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1146, SQLState: 42S02
2019-05-20 17:31:50.115 ERROR 45164 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : (conn=2) Table 'qronicle.report_definition' doesn't exist
2019-05-20 17:31:50.139  INFO 45164 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-84 - Shutdown initiated...
2019-05-20 17:31:50.145  INFO 45164 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-84 - Shutdown completed.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 11.041 s <<< FAILURE! - in com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT
[ERROR] ReportJobManager saveDeliverables method should have transactional behavior  Time elapsed: 0.144 s  <<< ERROR!
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT.setupReportDefinition(ReportJobManagerTransactionalIT.kt:83)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT.setupReportDefinition(ReportJobManagerTransactionalIT.kt:83)
Caused by: java.sql.SQLSyntaxErrorException: (conn=2) Table 'qronicle.report_definition' doesn't exist
    at com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT.setupReportDefinition(ReportJobManagerTransactionalIT.kt:83)
Caused by: java.sql.SQLException: 
Table 'qronicle.report_definition' doesn't exist
Query is: select reportdefi0_.id as id1_9_, reportdefi0_.delivery_policy as delivery2_9_, reportdefi0_.enabled as enabled3_9_, reportdefi0_.name as name4_9_, reportdefi0_.parameter_policy as paramete5_9_, reportdefi0_.pipeline as pipeline6_9_, reportdefi0_.scheduling_policy as scheduli7_9_, reportdefi0_.schema_name as schema_n8_9_, reportdefi0_.transformation_policy as transfor9_9_ from report_definition reportdefi0_
java thread: main
    at com.netapp.qronicle.jobs.ReportJobManagerTransactionalIT.setupReportDefinition(ReportJobManagerTransactionalIT.kt:83)

вот мой тест

package com.netapp.qronicle.jobs

import com.netapp.qronicle.EmbeddedMariaDBLifecycle
import com.netapp.qronicle.model.internal.ReportDefinition
import com.netapp.qronicle.model.internal.ReportDeliverable
import com.netapp.qronicle.monitoring.PipelineMetrics
import com.netapp.qronicle.monitoring.ReportJobManagerMetrics
import com.netapp.qronicle.pipelines.PipelineFactory.ValidPipeline.AWS_CLOUD_VOLUMES
import com.netapp.qronicle.policies.delivery.Deliverable
import com.netapp.qronicle.policies.delivery.DeliverableType
import com.netapp.qronicle.policies.delivery.createRetentionProcessor
import com.netapp.qronicle.policies.parameters.PipelineParameters
import com.netapp.qronicle.registry.ValidDeliveryPolicy.EMAIL_RETENTION
import com.netapp.qronicle.registry.ValidParameterPolicy.OFFSET_DAILY
import com.netapp.qronicle.registry.ValidTransformationPolicy.NO_TRANSFORMATION
import com.netapp.qronicle.reports.ReportPipeline
import com.netapp.qronicle.reports.ReportPipelineResult
import com.netapp.qronicle.reports.SingleReportPipelineResult
import com.netapp.qronicle.repositories.internal.ReportDefinitionRepository
import com.netapp.qronicle.repositories.internal.ReportDeliverableRepository
import com.netapp.qronicle.repositories.internal.ReportOutputRepository
import com.netapp.qronicle.repositories.internal.ReportRetentionRepository
import io.micrometer.core.instrument.simple.SimpleMeterRegistry
import io.mockk.every
import io.mockk.mockk
import org.aspectj.lang.Aspects
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.AdviceMode
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.transaction.annotation.EnableTransactionManagement
import javax.inject.Inject

@ExtendWith(SpringExtension::class, EmbeddedMariaDBLifecycle::class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@ActiveProfiles("test")
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
class ReportJobManagerTransactionalIT {
    companion object {
        /**
         * The aspects must be initialized with counters so that the late-init properties are initialized. These
         * counters don't have to specifically be named correctly--just initialized so compile-time weaving code
         * executes properly.
         */
        @BeforeAll
        @JvmStatic
        fun initAspect() {
            val registry = SimpleMeterRegistry()
            val pipelineMetricsAspect = Aspects.aspectOf(PipelineMetrics::class.java)
            pipelineMetricsAspect.pipelinesSucceeded = registry.counter("test.pipelinesSucceeded")
            pipelineMetricsAspect.pipelinesFailed = registry.counter("test.pipelinesFailed")
            pipelineMetricsAspect.pipelineCreateCalls = registry.counter("test.pielinesCreated")

            val reportJobManagerMetricsAspect = Aspects.aspectOf(ReportJobManagerMetrics::class.java)
            reportJobManagerMetricsAspect.errorCount = registry.counter("test.errorCount")
            reportJobManagerMetricsAspect.callCount = registry.counter("test.callCount")
        }
    }

    @Inject
    lateinit var reportOutputRepo: ReportOutputRepository

    @Inject
    lateinit var reportDefinitionRepo: ReportDefinitionRepository

    @Inject
    lateinit var deliverableRepository: ReportDeliverableRepository

    @Inject
    lateinit var retentionRepository: ReportRetentionRepository

    @BeforeEach
    fun setupReportDefinition() {
        reportDefinitionRepo.deleteAll()
        reportOutputRepo.deleteAll()
        deliverableRepository.deleteAll()

        val def = ReportDefinition()
        def.deliveryPolicy = EMAIL_RETENTION
        def.parameterPolicy = OFFSET_DAILY
        def.name = "testDef"
        def.schemaName = "test"
        def.pipeline = AWS_CLOUD_VOLUMES
        def.transformationPolicy = NO_TRANSFORMATION
        def.attributes = mapOf(
            "test.delivery.email.host" to "testhost",
            "test.delivery.email.username" to "testuser",
            "test.delivery.email.password" to "testpw",
            "test.delivery.email.fromAddress" to "guy@place.com",
            "test.delivery.email.toAddresses" to "otherguy@otherplace.com",
            "test.delivery.email.port" to "123",
            "test.delivery.email.composite0.csvFileName" to "test.csv",
            "test.delivery.csvFileName" to "test.csv",
            "test.delivery.retention.reportType" to "MS_INTERNAL_BILLING",
            "test.delivery.retention.customerName" to "Microsoft",
            "test.delivery.retention.dataCenterId" to "DC1",
            "test.delivery.timezone" to "UTC",
            "test.delivery.offsetAmount" to "1",
            "test.delivery.offsetUnit" to "DAYS"
        )

        reportDefinitionRepo.save(def)
    }

    @Test
    @Rollback(false)
    @DirtiesContext
    fun `ReportJobManager saveDeliverables method should have transactional behavior`() {
        val brokenDeliverableRepo = mockk<ReportDeliverableRepository>()
        every { brokenDeliverableRepo.save(any<ReportDeliverable>()) } throws RuntimeException("Oh no")

        val reportJobManager = ReportJobManager(reportOutputRepo, brokenDeliverableRepo, mockk(relaxed = true), mockk(relaxed = true), mockk(relaxed = true))
        val savedDef = reportDefinitionRepo.findByName("testDef") ?: Assertions.fail("Could not find report definition in DB")

        val pipeline = object : ReportPipeline {
            override val isValid = true
            override fun runPipeline(): List<ReportPipelineResult> = emptyList()
            override fun validate(): List<String> = emptyList()
            override val parameterPolicy = object : PipelineParameters {
                override fun generateReportOutputName() = "testOutputName"
            }
            override val postProcessors = listOf(createRetentionProcessor(retentionRepository))
        }

        val deliverable = Deliverable(
            deliverable = "stuff".toByteArray(),
            mimeType = "text/plain",
            deliverableName = "testDeliverableName",
            successful = true,
            type = DeliverableType.AWS_CSV_ROW
        )

        val result = SingleReportPipelineResult(
            deliverables = listOf(deliverable),
            isSuccessful = true,
            error = null
        )

        Assertions.assertThrows(RuntimeException::class.java) {
            reportJobManager.saveOutput(savedDef, pipeline, listOf(result), null)
        }

        Assertions.assertEquals(0, reportOutputRepo.findAll().count()) { "Report outputs should not be found" }
        Assertions.assertEquals(0, deliverableRepository.findAll().count()) { "Deliverables were found" }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...