问:
MockK class verification breaking with Dagger

Overview

Expected: Testing Dagger created repository class with empty constructor

Issue: Mockk verification is breaking with mockkConstructor and confirmVerified using Dagger dependency injection to create a repository class.

When implementing a repository with Dagger's Android constructor pattern, an empty constructor with @Inject is required in order for the Dagger app component, AppComponent.kt, to know to create the class.

When confirmVerified is commented out, the tests pass. When confirmVerified is implemented, the methods from prior tests are being called and tracked causing verification to fail.

Working as expected — Singleton repository without Dagger creation

In the unit test mockkObject is used to mock SomeRepository.kt object because it is an object created manually in Kotlin.

SomeRepository.kt

```<code>object SomeRepository {
    someMethod(...){...}
}
</code>```

SomeParamUnitTest.kt

```<code>@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private lateinit var someViewModel: SomeViewModel

    @BeforeAll
    fun beforeAll() {
        mockkObject(SomeRepository)
        ...
    }

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            SomeRepository.someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            SomeRepository.someMethod(test.isRealtime, any())
        }
        confirmVerified(SomeRepository)
    }
}
</code>```

Not working — confirmVerified with injected Dagger repository

Instead of using mockkObject for SomeRepository.kt in the unit test, mockkConstructor is implemented per the MockK author's documentation because the Dagger injected repository has a constructor. In addition, anyConstructed is used to mock SomeRepository.kt's methods and listen for verification of the methods being called.

Implementation

App.kt

```<code>class App : Application() {
    val appComponent = DaggerAppComponent.create()
    ...
}
</code>```

AppComponent.kt

```<code>@Singleton
@Component
interface AppComponent {
    fun someRepository(): SomeRepository

    // The repository is injected inside of a fragment, then passed as a parameter into the ViewModel.
    fun inject(someFragment: SomeFragment)
}
</code>```

SomeRepository.kt

```<code>@Singleton
class SomeRepository @Inject constructor() {
    someMethod(...){...}
}
</code>```

SomeParamUnitTest.kt

```<code>@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private lateinit var repository: SomeRepository
    private lateinit var someViewModel: SomeViewModel

    @BeforeAll
    fun beforeAll() {
        mockkConstructor(SomeRepository::class)
        ...
    }

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        repository = SomeRepository()
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            anyConstructed<SomeRepository>().someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            anyConstructed<SomeRepository>().someMethod(test.isRealtime, any())
        }
        confirmVerified(repository)
    }
}
</code>```

Tests failed

For each parameterized test that runs, the verified and recorded call counts are cumulatively increasing.

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 368
  Recorded call count: 57

Not verified calls:

Stack traces:

at io.mockk.impl.recording.CommonVerificationAcknowledger.acknowledgeVerified(CommonVerificationAcknowledger.kt:36)
      at io.mockk.MockKDsl.internalConfirmVerified(API.kt:272)
      at io.mockk.MockKKt.confirmVerified(MockK.kt:314)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.verifyTests(FeedLoadTests.kt:201)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.access$verifyTests(FeedLoadTests.kt:35)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests$Feed Load$1.invokeSuspend(FeedLoadTests.kt:67)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests$Feed Load$1.invoke(FeedLoadTests.kt)
      at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
      at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
      at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
      at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:142)
      at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:423)
      at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:26)
      at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109)
      at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:154)
      at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:89)
      at kotlinx.coroutines.BuildersKt.async(Unknown Source)
      at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
      at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
      at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
      at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:78)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.Feed Load(FeedLoadTests.kt:56)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
      at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
      at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestTemplateMethod(TimeoutExtension.java:81)
      at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask$DefaultDynamicTestExecutor.execute(NodeTestTask.java:198)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:138)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.lambda$execute$2(TestTemplateTestDescriptor.java:106)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:373)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
      at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:106)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:41)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at java.util.ArrayList.forEach(ArrayList.java:1257)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at java.util.ArrayList.forEach(ArrayList.java:1257)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
      at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
      at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
      at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
      at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
      at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
      at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
      at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Attempted Solutions

1. Move mockkConstructor from beforeAll to beforeEach JUnit 5 test lifecycle method.

This seems to be an improvement as the verified and recorded tests are not accumulating each parameterized test round like before. Rather, the correct method signature is not being found.

Tests failed

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 0
  Recorded call count: 2

Not verified calls:
  1) SomeRepository(mockkConstructor()).getMainFeedNetwork(false, Timestamp(seconds=1581980238, nanoseconds=352000000))
  2) SomeRepository(mockkConstructor()).getMainFeedRoom(Timestamp(seconds=1581980238, nanoseconds=352000000))

2. Remove test class level instance variable for repository and pass repository via method parameters.

The repository is created as a new value inside of each parameterized test, then passed as a parameter to mockComponents and verifyTests.

The stack trace errors do not indicate any methods are missing. Not verified calls is empty.

Tests failed

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 2
  Recorded call count: 2

Not verified calls:

3. Clear/unmock repository in beforeEach using clearConstructorMockk and unmockkConstructor.

clearConstructorMockk and unmockkConstructor were tested individually and received the same failure messages as Attempted Solution #2.

答:
Mock the repository class using mockkClass() and store as instance value

```<code>@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private val repository = mockkClass(SomeRepository::class)
    private lateinit var someViewModel: SomeViewModel

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            repository.someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            repository.someMethod(test.isRealtime, any())
        }
        confirmVerified(repository)
    }
}
</code>```

Body:
Overview

Expected: Testing Dagger created repository class with empty constructor

Issue: Mockk verification is breaking with mockkConstructor and confirmVerified using Dagger dependency injection to create a repository class.

When implementing a repository with Dagger's Android constructor pattern, an empty constructor with @Inject is required in order for the Dagger app component, AppComponent.kt, to know to create the class.

When confirmVerified is commented out, the tests pass. When confirmVerified is implemented, the methods from prior tests are being called and tracked causing verification to fail.

Working as expected — Singleton repository without Dagger creation

In the unit test mockkObject is used to mock SomeRepository.kt object because it is an object created manually in Kotlin.

SomeRepository.kt

object SomeRepository {
    someMethod(...){...}
}

SomeParamUnitTest.kt

@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private lateinit var someViewModel: SomeViewModel

    @BeforeAll
    fun beforeAll() {
        mockkObject(SomeRepository)
        ...
    }

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            SomeRepository.someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            SomeRepository.someMethod(test.isRealtime, any())
        }
        confirmVerified(SomeRepository)
    }
}

Not working — confirmVerified with injected Dagger repository

Instead of using mockkObject for SomeRepository.kt in the unit test, mockkConstructor is implemented per the MockK author's documentation because the Dagger injected repository has a constructor. In addition, anyConstructed is used to mock SomeRepository.kt's methods and listen for verification of the methods being called.

Implementation

App.kt

class App : Application() {
    val appComponent = DaggerAppComponent.create()
    ...
}

AppComponent.kt

@Singleton
@Component
interface AppComponent {
    fun someRepository(): SomeRepository

    // The repository is injected inside of a fragment, then passed as a parameter into the ViewModel.
    fun inject(someFragment: SomeFragment)
}

SomeRepository.kt

@Singleton
class SomeRepository @Inject constructor() {
    someMethod(...){...}
}

SomeParamUnitTest.kt

@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private lateinit var repository: SomeRepository
    private lateinit var someViewModel: SomeViewModel

    @BeforeAll
    fun beforeAll() {
        mockkConstructor(SomeRepository::class)
        ...
    }

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        repository = SomeRepository()
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            anyConstructed<SomeRepository>().someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            anyConstructed<SomeRepository>().someMethod(test.isRealtime, any())
        }
        confirmVerified(repository)
    }
}

Tests failed

For each parameterized test that runs, the verified and recorded call counts are cumulatively increasing.

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 368
  Recorded call count: 57

Not verified calls:

Stack traces:

at io.mockk.impl.recording.CommonVerificationAcknowledger.acknowledgeVerified(CommonVerificationAcknowledger.kt:36)
      at io.mockk.MockKDsl.internalConfirmVerified(API.kt:272)
      at io.mockk.MockKKt.confirmVerified(MockK.kt:314)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.verifyTests(FeedLoadTests.kt:201)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.access$verifyTests(FeedLoadTests.kt:35)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests$Feed Load$1.invokeSuspend(FeedLoadTests.kt:67)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests$Feed Load$1.invoke(FeedLoadTests.kt)
      at kotlinx.coroutines.test.TestBuildersKt$runBlockingTest$deferred$1.invokeSuspend(TestBuilders.kt:50)
      at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
      at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
      at kotlinx.coroutines.test.TestCoroutineDispatcher.dispatch(TestCoroutineDispatcher.kt:142)
      at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:423)
      at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:26)
      at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109)
      at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:154)
      at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:89)
      at kotlinx.coroutines.BuildersKt.async(Unknown Source)
      at kotlinx.coroutines.BuildersKt__Builders_commonKt.async$default(Builders.common.kt:82)
      at kotlinx.coroutines.BuildersKt.async$default(Unknown Source)
      at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:49)
      at kotlinx.coroutines.test.TestBuildersKt.runBlockingTest(TestBuilders.kt:78)
      at app.coinverse.contentviewmodel.tests.FeedLoadTests.Feed Load(FeedLoadTests.kt:56)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
      at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
      at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
      at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestTemplateMethod(TimeoutExtension.java:81)
      at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
      at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
      at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
      at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask$DefaultDynamicTestExecutor.execute(NodeTestTask.java:198)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:138)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.lambda$execute$2(TestTemplateTestDescriptor.java:106)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:373)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
      at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:270)
      at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
      at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:106)
      at org.junit.jupiter.engine.descriptor.TestTemplateTestDescriptor.execute(TestTemplateTestDescriptor.java:41)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at java.util.ArrayList.forEach(ArrayList.java:1257)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at java.util.ArrayList.forEach(ArrayList.java:1257)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
      at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
      at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
      at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
      at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
      at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
      at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
      at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
      at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
      at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
      at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
      at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
      at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
      at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Attempted Solutions

1. Move mockkConstructor from beforeAll to beforeEach JUnit 5 test lifecycle method.

This seems to be an improvement as the verified and recorded tests are not accumulating each parameterized test round like before. Rather, the correct method signature is not being found.

Tests failed

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 0
  Recorded call count: 2

Not verified calls:
  1) SomeRepository(mockkConstructor()).getMainFeedNetwork(false, Timestamp(seconds=1581980238, nanoseconds=352000000))
  2) SomeRepository(mockkConstructor()).getMainFeedRoom(Timestamp(seconds=1581980238, nanoseconds=352000000))

2. Remove test class level instance variable for repository and pass repository via method parameters.

The repository is created as a new value inside of each parameterized test, then passed as a parameter to mockComponents and verifyTests.

The stack trace errors do not indicate any methods are missing. Not verified calls is empty.

Tests failed

java.lang.AssertionError: Verification acknowledgment failed

Verified call count: 2
  Recorded call count: 2

Not verified calls:

3. Clear/unmock repository in beforeEach using clearConstructorMockk and unmockkConstructor.

clearConstructorMockk and unmockkConstructor were tested individually and received the same failure messages as Attempted Solution #2.

Body:
Mock the repository class using mockkClass() and store as instance value

@ExtendWith(SomeTestExtension::class)
class SomeParamUnitTest(val testDispatcher: TestCoroutineDispatcher) {

    private fun TestLoad() = teedLoadTestCases()
    private val repository = mockkClass(SomeRepository::class)
    private lateinit var someViewModel: SomeViewModel

    @AfterAll
    fun afterAll() {
        unmockkAll()
    }

    @ParameterizedTest
    @MethodSource("TestLoad")
    fun `Feed Load`(test: FeedLoadTest) = testDispatcher.runBlockingTest {
        mockComponents(test)
        someViewModel = SomeViewModel(...)
        assertContentList(...) // Working as expected.
        verifyTests(test)
    }

    private fun mockComponents(test: FeedLoadTest) {
        ...
        coEvery {
            repository.someMethod(test.isRealtime, any())
        } returns mockSomeMethod(test.mockFeedList, test.status)
        ...
    }

    private fun verifyTests(test: FeedLoadTest) {
        coVerify {
            repository.someMethod(test.isRealtime, any())
        }
        confirmVerified(repository)
    }
}


来源: stackexchange

问:
How do you create custom decorators for discord.py?
I know I asked this question before, but a new update suddenly broke my code. This is what I have:

def predicate(ctx):
    return Moderation.mod_role in ctx.author.roles

has_mod_role = commands.check(predicate)

class Moderation(commands.Cog):
    mod_role = None

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.mod_role = ...

    @commands.command()
    @has_mod_role
    async def command(self, ctx):
        ...
```

This used to work, but now the Moderation.mod_role has changed from the role defined in the function to None, so the commands don't work with any people, even if they have the needed role.

I am using python 3.8 and discord.py 1.3.1.

答:
I fixed the problem using global variables. Here's my code if anyone else has this problem:

def has_mod_role():
    def predicate(ctx):
        return mod_role in ctx.author.roles
    return commands.check(predicate)

class Moderation(commands.Cog):
    mod_role = None

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        global mod_role
        mod_role = ...

    @commands.command()
    @has_mod_role()
    async def command(self, ctx, ...):
        ...
```

ContentLicense: CC BY-SA 4.0

Body:
I know I asked this question before, but a new update suddenly broke my code. This is what I have:

def predicate(ctx):
    return Moderation.mod_role in ctx.author.roles

has_mod_role = commands.check(predicate)

class Moderation(commands.Cog):
    mod_role = None

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.mod_role = ...

    @commands.command()
    @has_mod_role
    async def command(self, ctx):
        ...

This used to work, but now the Moderation.mod_role has changed from the role defined in the function to None, so the commands don't work with any people, even if they have the needed role.

I am using python 3.8 and discord.py 1.3.1.


问:
'Cannot find module error' after I use babel to convert my JS code.(still got a problem even after files are converted well)
So I tried using Babel to convert my code so that I can run this by node. package.json build is this,

```<code>"build": "babel ./public/src -d ./public/lib -w"
</code>```

When I do npm run build

```<code>PS C:\users\leepc\babel\public> npm run build

> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js
</code>```

It works right and shows me exactly what I want.
My .babelrc preset is es2015
I run my main.js code and this is happened.

```<code>PS C:\users\leepc\babel\public\lib> node main.js
internal/modules/cjs/loader.js:984
  throw err;
  ^
    at Function.Module._load
(internal/modules/cjs/loader.js:863:27)
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)      17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1177:
10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)
    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_m
ain.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]
}
</code>```

This is files and folders list in img

My codes are coverted well, but it still got some Module problems. How can I solve this issue? Sorry this is my first time posting question in this website, if I missed some information pls tell me.

edit:

Here is .babelrc

```<code>{
    "presets": ["es2015"]
  }
</code>```

答:
Okay it turns out, I should combine both of answers above.

First, I have to check whether my import plugin is right or wrong. So I just re-installed it.

```<code>npm install babel-plugin-import --save-dev
</code>```

Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc

```<code>{
    "presets": ["es2015"],
    "plugins": [["import", { "libraryName": "antd" }]]
}
</code>```

this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.

And also next stuff, I have to make import path to be corrected.

```<code>import { create as newBlogPost } from "blogpost.js";
</code>```

change this to

```<code>import { create as newBlogPost } from "./blogpost.js";
</code>```

By doing this, now I can get a result that I wanted so far.

```<code>PS C:\Users\leePC\babel\public\lib> node main.js

    Title: For and against let
    By: Kyle Simpson
    October 27, 2014
</code>```

So majorly, 1. Check whether I missed some plugins or packages ( in my cases, I forgot import package ) 2. Make sure to check your import path

Thank you for help guys.

Body:
So I tried using Babel to convert my code so that I can run this by node. package.json build is this,

"build": "babel ./public/src -d ./public/lib -w"

When I do npm run build

PS C:\users\leepc\babel\public> npm run build

> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js

It works right and shows me exactly what I want.
My .babelrc preset is es2015
I run my main.js code and this is happened.

PS C:\users\leepc\babel\public\lib> node main.js
internal/modules/cjs/loader.js:984
  throw err;
  ^
    at Function.Module._load
(internal/modules/cjs/loader.js:863:27)
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)      17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1177:
10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)
    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_m
ain.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]
}

This is files and folders list in img

My codes are coverted well, but it still got some Module problems. How can I solve this issue? Sorry this is my first time posting question in this website, if I missed some information pls tell me.

edit:

Here is .babelrc

{
    "presets": ["es2015"]
  }

Body:
Okay it turns out, I should combine both of answers above.

First, I have to check whether my import plugin is right or wrong. So I just re-installed it.

npm install babel-plugin-import --save-dev

Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc

{
    "presets": ["es2015"],
    "plugins": [["import", { "libraryName": "antd" }]]
}

this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.

And also next stuff, I have to make import path to be corrected.

import { create as newBlogPost } from "blogpost.js";

change this to

import { create as newBlogPost } from "./blogpost.js";

By doing this, now I can get a result that I wanted so far.

PS C:\Users\leePC\babel\public\lib> node main.js

    Title: For and against let
    By: Kyle Simpson
    October 27, 2014

So majorly, 1. Check whether I missed some plugins or packages ( in my cases, I forgot import package ) 2. Make sure to check your import path

Thank you for help guys.


问:
Create a new column based on row index
I have a dataframe similar to following,

======================  DATAFRAME ===========================

```<code>     Question Value
0    A          1
1    B          4
2    C          3
3    D          7
4    E          45
5    F          78
6    G          44
7    H          3
8    I          4
9    J          6
</code>```

I want to create a question dimension column based on index number, for example for index = 0 to 3, Question dimension='AA', for index=4 to 5, question dimension ='BB'. The rest is 'CC'.

======================  DATAFRAME ===========================

```<code>     Question Value  Question dimension
0    A          1           AA
1    B          4           AA
2    C          3           AA
3    D          7           AA
4    E          45          BB
5    F          78          BB
6    G          44          CC
7    H          3           CC
8    I          4           CC
9    J          6           CC
</code>```

How can I achieve this? Thank you in advance for your help!!

答:
Use loc

```<code>df.loc[0:3, 'Question dimension'] = 'AA'
df.loc[4:5, 'Question dimension'] = 'BB'
df.loc[6:, 'Question dimension'] = 'CC'
</code>```

```<code>     Question Value  Question dimension
0    A          1           AA
1    B          4           AA
2    C          3           AA
3    D          7           AA
4    E          45          BB
5    F          78          BB
6    G          44          CC
7    H          3           CC
8    I          4           CC
9    J          6           CC
</code>```

Title: Create a new column based on row index

Body:
I have a dataframe similar to following,

======================  DATAFRAME ===========================

     Question Value
0    A          1
1    B          4
2    C          3
3    D          7
4    E          45
5    F          78
6    G          44
7    H          3
8    I          4
9    J          6

I want to create a question dimension column based on index number, for example for index = 0 to 3, Question dimension='AA', for index=4 to 5, question dimension ='BB'. The rest is 'CC'.

======================  DATAFRAME ===========================

     Question Value  Question dimension
0    A          1           AA
1    B          4           AA
2    C          3           AA
3    D          7           AA
4    E          45          BB
5    F          78          BB
6    G          44          CC
7    H          3           CC
8    I          4           CC
9    J          6           CC

How can I achieve this? Thank you in advance for your help!!

Body:
Use loc

df.loc[0:3, 'Question dimension'] = 'AA'
df.loc[4:5, 'Question dimension'] = 'BB'
df.loc[6:, 'Question dimension'] = 'CC'

     Question Value  Question dimension
0    A          1           AA
1    B          4           AA
2    C          3           AA
3    D          7           AA
4    E          45          BB
5    F          78          BB
6    G          44          CC
7    H          3           CC
8    I          4           CC
9    J          6           CC


问:
GNU Radio filter design tool (gr_filter_design)
I am having some trouble getting the filter design tool to even start. When starting the application I get

```<code>"This example requires a Numerical Python Extension, but
 failed to import either NumPy, or numarray, or Numeric.
 NumPy is available at http://sourceforge.net/projects/numpy".
</code>```

I have rebuild GNU Radio a couple of times now, and I am fairly sure that I have every thing installed that is required. I do have numpy installed, and I have tried a couple of versions just to be safe.

Has some one else had this problem?

答:
I ran into a similar issue just now, and had to import fftpack from SciPy instead of NumPy.  NumPy was still needed for actually generating the filters (removing import numpy would cause gr_filter_design to crash when clicking the "Design" button).

/usr/lib/python3.8/site-packages/gnuradio/filter/filter_design.py:

```<code>#    import numpy
#    from numpy.fft import fftpack
#    from scipy import poly1d, signal

    import numpy
    from scipy import fftpack, poly1d, signal
</code>```

Versions: Manjaro Linux, numpy 1.18.1, scipy 1.4.1, and gnuradio 3.8.0.0.

ContentLicense: CC BY-SA 3.0

Body:
I am having some trouble getting the filter design tool to even start. When starting the application I get

"This example requires a Numerical Python Extension, but
 failed to import either NumPy, or numarray, or Numeric.
 NumPy is available at http://sourceforge.net/projects/numpy".

I have rebuild GNU Radio a couple of times now, and I am fairly sure that I have every thing installed that is required. I do have numpy installed, and I have tried a couple of versions just to be safe.

Has some one else had this problem?

Body:
I ran into a similar issue just now, and had to import fftpack from SciPy instead of NumPy.  NumPy was still needed for actually generating the filters (removing import numpy would cause gr_filter_design to crash when clicking the "Design" button).

/usr/lib/python3.8/site-packages/gnuradio/filter/filter_design.py:

#    import numpy
#    from numpy.fft import fftpack
#    from scipy import poly1d, signal

    import numpy
    from scipy import fftpack, poly1d, signal

Versions: Manjaro Linux, numpy 1.18.1, scipy 1.4.1, and gnuradio 3.8.0.0.


问:
textArea (or HtmlEditor) extJS (+ruby on rails 2.3.1)
I have text area, i write something there for example:

```<code>hello
All
People!
</code>```

in controller I use command named gsub (for example i write .gsub("\n", "
") to replace "\n" with ). In my database I see

```<code>hello
All
People!
</code>```

its Ok. Next when I trying to update my textarea, I have something like this:

```<code>hello<br>
All<br>
People!<br>
</code>```

How to avoid this? I dont want this br's in my textarea. Maybe i can change or replace in controller again?

Thank yoU!

I tried to htmleditor, but nothing i cant paste in my project (not clickable) :(

答:
I think you should replace
 tags with \n. You can do it with this regex #
#i

Body:
I have text area, i write something there for example:

hello
All
People!

in controller I use command named gsub (for example i write .gsub("\n", "
") to replace "\n" with ). In my database I see

hello
All
People!

its Ok. Next when I trying to update my textarea, I have something like this:

hello

All

People!

How to avoid this? I dont want this br's in my textarea. Maybe i can change or replace in controller again?

Thank yoU!

I tried to htmleditor, but nothing i cant paste in my project (not clickable) :(

Body: I think you should replace <br> tags with \n. You can do it with this regex #<br\s*?/?>#i


问:
How can I search a python script for use of a class method before running?
I would like to be able to scan a python script for uses of a class method before running the script itself. For example, given the following script, get all uses of the "foo" method for class "A" and the arguments passed to the method

```<code>class A():
    def foo(self, val):
        return val + 1

class B():
    def foo(self, val):
        return val - 1

a = A()
b = B()

a_val = a.foo(1)
b_val = b.foo(1)
</code>```

This is an overly simple example, but the goal here is to use something more than regex to search for a foo() pattern so that items like b.foo(1) are not returned. I've looked at the ast and symtable modules, but they don't seem to have the functionality I'm after. I realize this may be a difficult/impossible problem due to python being an interpreted language, but it seems like someone else had to have had this problem before

答:
This sounds like an XY Problem, but alas. You can use the inspect module to inspect classes and functions on runtime:

import inspect

class Foo:
    def bar(self, val):
        return val + 1

    def baz(self, number):
        return number

functions = inspect.getmembers(Foo(), predicate=inspect.ismethod)

for name, function in functions:
    sig = inspect.signature(function)
    print(f'Function "{name}" has a params {sig}')
```

<p>Outputs:</p>

```Function "bar" has a params (val)
Function "baz" has a params (number)
```

Body:
I would like to be able to scan a python script for uses of a class method before running the script itself. For example, given the following script, get all uses of the "foo" method for class "A" and the arguments passed to the method

class A():
    def foo(self, val):
        return val + 1

class B():
    def foo(self, val):
        return val - 1

a = A()
b = B()

a_val = a.foo(1)
b_val = b.foo(1)

This is an overly simple example, but the goal here is to use something more than regex to search for a foo() pattern so that items like b.foo(1) are not returned. I've looked at the ast and symtable modules, but they don't seem to have the functionality I'm after. I realize this may be a difficult/impossible problem due to python being an interpreted language, but it seems like someone else had to have had this problem before

Body:
This sounds like an XY Problem, but alas. You can use the inspect module to inspect classes and functions on runtime:

import inspect

class Foo:
    def bar(self, val):
        return val + 1

    def baz(self, number):
        return number

functions = inspect.getmembers(Foo(), predicate=inspect.ismethod)

for name, function in functions:
    sig = inspect.signature(function)
    print(f'Function "{name}" has a params {sig}')

Outputs:

Function "bar" has a params (val)
Function "baz" has a params (number)


问:
How to do I start a Spring Boot service before the Serenity integration tests?
I googled a lot but I didn't find a proper solution to my question. So maybe here.

There is a Spring Boot service that I would like to test through REST API in build time. So the service needs to be executed as a standalone service in the build phase before the integration tests are executed.
I can execute somehow it but not the ideal.

I did something similar that the this article

I have a maven project with this pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>my.project.package</groupId>
    <artifactId>my-project-name</artifactId>
    <version>1.0.1</version>
    <packaging>jar</packaging>

    <name>my-project-name</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <parallel.tests>3</parallel.tests>
        <serenity.maven.version>2.0.48</serenity.maven.version>
        <cucumber.version>4.8.0</cucumber.version>
        <serenity.version>2.1.2</serenity.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16-beta1</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber4</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-rest-assured</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-spring</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M1</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>add-test-sources</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/it/java</source>
                            </sources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>add-test-resources</id>
                        <phase>generate-test-resources</phase>
                        <goals>
                            <goal>add-test-resource</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <directory>src/it/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                    <includes>
                        <include>**/*Runner.java</include>
                    </includes>
                    <parallel>classes</parallel>
                    <threadCount>${parallel.tests}</threadCount>
                    <forkCount>${parallel.tests}</forkCount>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.maven.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>io.cucumber</groupId>
                        <artifactId>cucumber-core</artifactId>
                        <version>${cucumber.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
```

<p>I made an entry point for the test execution:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(CucumberWithSerenity.class)
@CucumberOptions(
        features = "src/it/resources/features",
        glue = "my.project.package.integrationtest",
        plugin = {
                "pretty"
        },
        tags = "(not @Ignore) or (not @Manual) or (not @ToBeImplemented)"
)
@ActiveProfiles("integration-test")
public class IntegrationTestRunner {}
</code>```

I have a StepsBase class which starts the app:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("integration-test")
@ContextConfiguration(classes = Application.class)
public class StepsBase {
    public static final String HOST = "http://localhost:";

    @LocalServerPort
    private int serverPort;

    public String getBaseUrl() {
        return  HOST + serverPort;
    }
}
```

<p>And all my steps classes extends the StepsBase class like this</p>

<pre class="lang-java prettyprint-override"><code>public class SimpleSteps extends StepsBase {

    @Given("this is a sample step")
    .
    .
    .
}
</code>```

If I execute the service build with maven clean verify, then I get the following log for the integration tests:

The main problem with this solution is the first scenario execute the Spring Boot service before instantiating the step class, which is counting into the execution time, and the test cases are not compromised if the service is not starting. Bytheway the Serenity before every scenario checks that the service is running or not.

Do you have an idea of how to make that the service is started before Serenity startup?
Or before the first step execution?

答:
If everything is in the same project (or maven module) you can use the Spring Boot Maven plugin (https://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html). A sample configuration is shown below:</p>

```<code>            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.4.RELEASE</version>
                <configuration>
                    <classifier>exec</classifier>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    ```
</code>```

Body:
I googled a lot but I didn't find a proper solution to my question. So maybe here.

There is a Spring Boot service that I would like to test through REST API in build time. So the service needs to be executed as a standalone service in the build phase before the integration tests are executed.
I can execute somehow it but not the ideal.

I did something similar that the this article

I have a maven project with this pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>my.project.package</groupId>
    <artifactId>my-project-name</artifactId>
    <version>1.0.1</version>
    <packaging>jar</packaging>

    <name>my-project-name</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <parallel.tests>3</parallel.tests>
        <serenity.maven.version>2.0.48</serenity.maven.version>
        <cucumber.version>4.8.0</cucumber.version>
        <serenity.version>2.1.2</serenity.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16-beta1</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber4</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-rest-assured</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-spring</artifactId>
            <version>${serenity.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M1</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>add-test-sources</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>src/it/java</source>
                            </sources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>add-test-resources</id>
                        <phase>generate-test-resources</phase>
                        <goals>
                            <goal>add-test-resource</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <directory>src/it/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                    <includes>
                        <include>**/*Runner.java</include>
                    </includes>
                    <parallel>classes</parallel>
                    <threadCount>${parallel.tests}</threadCount>
                    <forkCount>${parallel.tests}</forkCount>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>net.serenity-bdd.maven.plugins</groupId>
                <artifactId>serenity-maven-plugin</artifactId>
                <version>${serenity.maven.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>io.cucumber</groupId>
                        <artifactId>cucumber-core</artifactId>
                        <version>${cucumber.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>serenity-reports</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>aggregate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

I made an entry point for the test execution:

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(
        features = "src/it/resources/features",
        glue = "my.project.package.integrationtest",
        plugin = {
                "pretty"
        },
        tags = "(not @Ignore) or (not @Manual) or (not @ToBeImplemented)"
)
@ActiveProfiles("integration-test")
public class IntegrationTestRunner {}

I have a StepsBase class which starts the app:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles("integration-test")
@ContextConfiguration(classes = Application.class)
public class StepsBase {
    public static final String HOST = "http://localhost:";

    @LocalServerPort
    private int serverPort;

    public String getBaseUrl() {
        return  HOST + serverPort;
    }
}

And all my steps classes extends the StepsBase class like this

public class SimpleSteps extends StepsBase {

    @Given("this is a sample step")
    .
    .
    .
}

If I execute the service build with maven clean verify, then I get the following log for the integration tests:

The main problem with this solution is the first scenario execute the Spring Boot service before instantiating the step class, which is counting into the execution time, and the test cases are not compromised if the service is not starting. Bytheway the Serenity before every scenario checks that the service is running or not.

Do you have an idea of how to make that the service is started before Serenity startup?
Or before the first step execution?

Body:
If everything is in the same project (or maven module) you can use the Spring Boot Maven plugin (https://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html). A sample configuration is shown below:

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.4.RELEASE</version>
                <configuration>
                    <classifier>exec</classifier>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    ```


问:
Cosmos DB error connect ETIMEDOUT when trying to call many times
I have an array of items (to test I used around 250). Within each item is an ID that I am trying to call from CosmosDB. I am doing so in a simple for-loop

```<code>for (i = 0; i < arr.length; k++) {
    var func = find(context, arr[i].id)
}
</code>```

Within find I simply call cosmosDB to read the file. This works fine on individual items, or if I use small arrays (20-50), however with large arrays I get the following error:

```<code>{ FetchError: request to mycosmossite/docs failed, reason: connect ETIMEDOUT
  message:
   'request to mycosmossite/docs failed, reason: connect ETIMEDOUT',
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  headers:
   { 'x-ms-throttle-retry-count': 0,
     'x-ms-throttle-retry-wait-time-ms': 0 } }
</code>```

I am not sure why this is happening. I also get this when using request-promise from time to time but if I try again without changing anything it often works. I am not sure if this is linked

```<code>Exception: RequestError: Error: connect ETIMEDOUT
</code>```

Can someone offer a solution so I can work on larger arrays here? Is this a throttling issue?

Thanks

答:
I maintain the Azure Cosmos DB JS SDK. Are you using the SDK to make these calls? We don't throw ETIMEDOUT anywhere inside the SDK so it is bubbling up from the NodeJS or Browser layer. Possibly you are overwhelming the networking stack or event loop by opening up many downstream connections and promises. As currently written, your code will open arr.length number of concurrent backend requests. Did you mean to await the result of each request? Example:

```<code>for (i = 0; i < arr.length; k++) {
    var func = await find(context, arr[i].id)
}
</code>```

You could also batch the requests using a package like p-map and using the concurrency parameter

Body:
I have an array of items (to test I used around 250). Within each item is an ID that I am trying to call from CosmosDB. I am doing so in a simple for-loop

for (i = 0; i < arr.length; k++) {
    var func = find(context, arr[i].id)
}

Within find I simply call cosmosDB to read the file. This works fine on individual items, or if I use small arrays (20-50), however with large arrays I get the following error:

{ FetchError: request to mycosmossite/docs failed, reason: connect ETIMEDOUT
  message:
   'request to mycosmossite/docs failed, reason: connect ETIMEDOUT',
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  headers:
   { 'x-ms-throttle-retry-count': 0,
     'x-ms-throttle-retry-wait-time-ms': 0 } }

I am not sure why this is happening. I also get this when using request-promise from time to time but if I try again without changing anything it often works. I am not sure if this is linked

Exception: RequestError: Error: connect ETIMEDOUT

Can someone offer a solution so I can work on larger arrays here? Is this a throttling issue?

Thanks

Body:
I maintain the Azure Cosmos DB JS SDK. Are you using the SDK to make these calls? We don't throw ETIMEDOUT anywhere inside the SDK so it is bubbling up from the NodeJS or Browser layer. Possibly you are overwhelming the networking stack or event loop by opening up many downstream connections and promises. As currently written, your code will open arr.length number of concurrent backend requests. Did you mean to await the result of each request? Example:

for (i = 0; i < arr.length; k++) {
    var func = await find(context, arr[i].id)
}

You could also batch the requests using a package like p-map and using the concurrency parameter


问:
Deploy angular 7, mongo, express, node application on own server
I would like to deploy my angular application with nodejs, mongo, express js on my own server.

My way is:
-> ng build --prod (output is dist folder)
-> ng serve on dist folder

Start backend:
-> node server js file

But I think, it is not correct way od production stage. Added http server on express, there I create another index html view file with hbs, and there I use:

```<code><body>
  <my-app>Loading ...</my-app>
  <script src="/dist/bundle.js"></script>
</body>
</code>```

But on dist server, there is multiple js files.

How can I create using ng option (no webpack or must be f.e. webpack?) my angular/mongo/node/express application (in 1, my own server, no aws, heroku, github etc). There is any correct way to do it?

答:
I've been able to deploy an angular app using Caddy Server as the webserver.

Create a build of your Angular code by doing ng build --prod-true.
This creates a set of bundled Js and Html files in the dist
directory.

Copy these files to where you want to run the app.

Next go to the Caddy website and download the version of Caddy for
your os. You can choose all kinds of features but for my deployment
inside a firewall a plain build worked fine.

Drop the caddy file in the directory that you put your compiled
angular code.

Create a caddyfile (just a file named caddyfile), add localhost:(your
favorite port number).

Run caddy and it will automatically serve your app by launching
index.html.  You can view your app at localhost:port.

No messy node installation.  Caddy has all sorts of add-ons to deal with more complicated scenarios but the deployment is caddy.exe, caddyfile and your built code.

Body:
I would like to deploy my angular application with nodejs, mongo, express js on my own server.

My way is:
-> ng build --prod (output is dist folder)
-> ng serve on dist folder

Start backend:
-> node server js file

But I think, it is not correct way od production stage. Added http server on express, there I create another index html view file with hbs, and there I use:

  <my-app>Loading ...</my-app>

But on dist server, there is multiple js files.

How can I create using ng option (no webpack or must be f.e. webpack?) my angular/mongo/node/express application (in 1, my own server, no aws, heroku, github etc). There is any correct way to do it?


问:
Django// How to display complex depth data in template
Django 2.2//

python 3.6//

I have a context created with a combination of 'list' and 'dictionary'.

The data structure is shown below.

```<code>{
   "Mike":[
      {
         "month":"2020-02",
         "consult_counts_total":2,
         "consult_counts_total_uid":2
      },
      {
         "month":"2020-01",
         "consult_counts_total":4,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":6,
         "consult_counts_total_uid":1
      }
   ],
   "Jaden":[
      {
         "month":"2020-02",
         "consult_counts_total":8,
         "consult_counts_total_uid":12
      },
      {
         "month":"2020-01",
         "consult_counts_total":23,
         "consult_counts_total_uid":11
      },
      {
         "month":"2019-12",
         "consult_counts_total":2,
         "consult_counts_total_uid":19
      }
   ],
   "Sarah":[
      {
         "month":"2020-02",
         "consult_counts_total":2,
         "consult_counts_total_uid":2
      },
      {
         "month":"2020-01",
         "consult_counts_total":4,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":6,
         "consult_counts_total_uid":1
      }
   ],
   "John":[
      {
         "month":"2020-02",
         "consult_counts_total":1,
         "consult_counts_total_uid":0
      },
      {
         "month":"2020-01",
         "consult_counts_total":2,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":5,
         "consult_counts_total_uid":1
      }
   ]
}

</code>```

I'm trying to display this data through a loop in template.

First I'v tried. It shows nice result.

```<code>{% for foo in context_data %}
    <p>{{ foo }}</p>
{% endfor %}

# result

Mike
Jaden
Sarah
John
</code>```

But I can't get more depth data.

For example, I want to get Mike's all months (2020-02, 2020-01, 2019-12)

Second tried..

```<code>{% for foo in context_data %}
    <p class="big">This is {{ foo }}'s months.</p>
    {% for foo2 in foo %}
        <p class="small">{{ foo2.months }}</p>
    {% endfor %}
{% endfor %}

# but it's showing nothing
</code>```

Third tried..

```<code>{% for foo in context_data %}
    <p class="big">This is {{ foo }}'s months.</p>
    {% for foo2 in foo %}
        <p class="small">{{ foo2 }}</p>
    {% endfor %}
    <br>
{% endfor %}

# result
This is Mike's months.
M
i
k
e
</code>```

Third code looping "Mike" string.. not Mike's under data.

I expect showing like this.

```<code>This is Mike's months.
2020-02
2020-01
2019-12

This is Jaden's months.
2020-02
2020-01
2019-12

This is Sarah's months.
2020-02
2020-01
2019-12

This is John's months.
2020-02
2020-01
2019-12

</code>```

How can I this?

答:
You are iterating only keys, should iterate values using items to dictionary.

```<code>{% for key, values in context_data.items %}
    <p class="big">This is {{ key }}'s months.</p>
    {% for foo2 in values %}
        <p class="small">{{ foo2.month }}</p>
    {% endfor %}
    <br>
{% endfor %}
</code>```

Body:
Django 2.2//

python 3.6//

I have a context created with a combination of 'list' and 'dictionary'.

The data structure is shown below.

{
   "Mike":[
      {
         "month":"2020-02",
         "consult_counts_total":2,
         "consult_counts_total_uid":2
      },
      {
         "month":"2020-01",
         "consult_counts_total":4,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":6,
         "consult_counts_total_uid":1
      }
   ],
   "Jaden":[
      {
         "month":"2020-02",
         "consult_counts_total":8,
         "consult_counts_total_uid":12
      },
      {
         "month":"2020-01",
         "consult_counts_total":23,
         "consult_counts_total_uid":11
      },
      {
         "month":"2019-12",
         "consult_counts_total":2,
         "consult_counts_total_uid":19
      }
   ],
   "Sarah":[
      {
         "month":"2020-02",
         "consult_counts_total":2,
         "consult_counts_total_uid":2
      },
      {
         "month":"2020-01",
         "consult_counts_total":4,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":6,
         "consult_counts_total_uid":1
      }
   ],
   "John":[
      {
         "month":"2020-02",
         "consult_counts_total":1,
         "consult_counts_total_uid":0
      },
      {
         "month":"2020-01",
         "consult_counts_total":2,
         "consult_counts_total_uid":7
      },
      {
         "month":"2019-12",
         "consult_counts_total":5,
         "consult_counts_total_uid":1
      }
   ]
}

I'm trying to display this data through a loop in template.

First I'v tried. It shows nice result.

{% for foo in context_data %}

{{ foo }}

{% endfor %}

# result

Mike
Jaden
Sarah
John

But I can't get more depth data.

For example, I want to get Mike's all months (2020-02, 2020-01, 2019-12)

Second tried..

{% for foo in context_data %}

This is {{ foo }}'s months.

    {% for foo2 in foo %}

{{ foo2.months }}

    {% endfor %}
{% endfor %}

# but it's showing nothing

Third tried..

{% for foo in context_data %}

This is {{ foo }}'s months.

    {% for foo2 in foo %}

{{ foo2 }}

    {% endfor %}

{% endfor %}

# result
This is Mike's months.
M
i
k
e

Third code looping "Mike" string.. not Mike's under data.

I expect showing like this.

This is Mike's months.
2020-02
2020-01
2019-12

This is Jaden's months.
2020-02
2020-01
2019-12

This is Sarah's months.
2020-02
2020-01
2019-12

This is John's months.
2020-02
2020-01
2019-12

How can I this?

Body:
You are iterating only keys, should iterate values using items to dictionary.

{% for key, values in context_data.items %}
    <p class="big">This is {{ key }}'s months.</p>
    {% for foo2 in values %}
        <p class="small">{{ foo2.month }}</p>
    {% endfor %}
    <br>
{% endfor %}


问:
Highcharts column width with variable x axis point spacing
So I have an x axis of type datetime, and a series of type column:

http://jsfiddle.net/drmrbrewer/215tnLna/3/

Now, in reality, the spacing of points on the x axis may not always be uniform as in the above example.  For example, let's drop a couple of the points to create a non-uniform spacing:

http://jsfiddle.net/drmrbrewer/215tnLna/4/

What I'd like to happen is for each column to fill the entire span from the relevant point to the previous point, so that the gaps would be entirely filled in the above example.

Is that possible?  Hopefully without some horrible hack?  From a quick search it seems that there is a suggestion that different series may be required (one for each column width).  I'm hoping that isn't the case because (a) it's complicated; and (b) I don't know in advance what spacings I'm going to encounter in the data, so it's even more complicated!

Thanks!

答: What you are trying to make is a histogram, not a bar chart (even bar/column widths). Perhaps you need to use the histogram chart type? https://www.highcharts.com/docs/chart-and-series-types/histogram-series</p>