如何解决GOOGLE_APPLICATION_CREDENTIALS在测试中运行应用程序时,Spring Boot ?

idfiyjo8  于 2023-01-09  发布在  Spring
关注(0)|答案(1)|浏览(194)

我有一个依赖于Google PubSub的Sping Boot 应用程序。我想使用Google Cloud PubSub模拟器运行它。如何解析GOOGLE_APPLICATION_CREDENTIALS,以便应用程序启动并使用来自本地模拟器的消息,而不是外部项目?
现在,如果我把GOOGLE_APPLICATION_CREDENTIALS设置为dev.json,如果我不设置这个变量,PubSub就不会被调用,测试崩溃。我该如何克服呢?我无法把谜题放在一起。

**注意:**我正在编写一个完整的Sping Boot 启动的集成测试。

我的发布订阅实现:

import com.github.dockerjava.api.exception.DockerClientException
import com.google.api.gax.core.NoCredentialsProvider
import com.google.api.gax.grpc.GrpcTransportChannel
import com.google.api.gax.rpc.FixedTransportChannelProvider
import com.google.api.gax.rpc.TransportChannelProvider
import com.google.cloud.pubsub.v1.*
import com.google.cloud.pubsub.v1.stub.GrpcSubscriberStub
import com.google.cloud.pubsub.v1.stub.SubscriberStubSettings
import com.google.protobuf.ByteString
import com.google.pubsub.v1.*
import com.greenbird.server.contracts.TestServer
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import org.testcontainers.containers.PubSubEmulatorContainer
import org.testcontainers.utility.DockerImageName
import java.util.concurrent.TimeUnit

class PubSubTestServer(private val projectName: ProjectName, private val ports: Array<Int> = arrayOf(8085)) :
    TestServer {

    constructor(projectId: String): this(ProjectName.of(projectId))

    private val projectId = projectName.project

    var emulator: PubSubEmulatorContainer = PubSubEmulatorContainer(
        DockerImageName.parse("gcr.io/google.com/cloudsdktool/cloud-sdk:latest")
    )

    private var channels: MutableList<ManagedChannel> = mutableListOf()

    private fun channel(): ManagedChannel {
        return if (channels.isEmpty()) {
            val endpoint = emulator.emulatorEndpoint
            val channel = ManagedChannelBuilder
                .forTarget(endpoint)
                .usePlaintext()
                .build()
            channels.add(channel)
            channel
        } else {
            channels.first()
        }
    }

    private val channelProvider: TransportChannelProvider
        get() {
            return FixedTransportChannelProvider
                .create(
                    GrpcTransportChannel.create(channel())
                )
        }

    private val credentialsProvider: NoCredentialsProvider = NoCredentialsProvider.create()

    private val topicAdminSettings: TopicAdminSettings
        get() {
            when {
                emulator.isRunning -> {
                    return buildTopicAdminSettings()
                }
                else -> {
                    throw DockerClientException("Topic admin settings attempted to initialize before starting PubSub emulator")
                }
            }
        }

    private fun buildTopicAdminSettings(): TopicAdminSettings {
        return TopicAdminSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build()
    }

    private val subscriptionAdminSettings: SubscriptionAdminSettings
        get() {
            when {
                emulator.isRunning -> {
                    return buildSubscriptionAdminSettings()
                }
                else -> {
                    throw DockerClientException("Subscription admin settings attempted to initialize before starting PubSub emulator")
                }
            }
        }

    private fun buildSubscriptionAdminSettings(): SubscriptionAdminSettings {
        return SubscriptionAdminSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build()
    }

    override fun start() {
        emulator.withExposedPorts(*ports).start()
    }

    override fun stop() {
        terminate()
        emulator.stop()
    }

    private fun terminate() {
        for (channel in channels) {
            channel.shutdownNow()
            channel.awaitTermination(5, TimeUnit.SECONDS)
        }
    }

    fun createTopic(topicId: String) {
        TopicAdminClient.create(topicAdminSettings).use { topicAdminClient ->
            val topicName = TopicName.of(projectId, topicId)
            topicAdminClient.createTopic(topicName)
        }
    }

    fun listTopics(): List<String> {
        return TopicAdminClient.create(topicAdminSettings)
            .listTopics(projectName)
            .iterateAll()
            .map { it.name }
            .toList()
    }

    fun createSubscription(subscriptionId: String, topicId: String) {
        val subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId)
        SubscriptionAdminClient.create(subscriptionAdminSettings).createSubscription(
            subscriptionName,
            TopicName.of(projectId, topicId),
            PushConfig.getDefaultInstance(),
            10
        )
    }

    fun listSubscriptions(): List<String> {
        return SubscriptionAdminClient.create(subscriptionAdminSettings)
            .listSubscriptions(projectName)
            .iterateAll()
            .map { it.name }
            .toList()
    }

    fun push(topicId: String, message: String) {
        val publisher: Publisher = Publisher.newBuilder(TopicName.of(projectId, topicId))
            .setChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build()

        val pubsubMessage: PubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(message)).build()
        publisher.publish(pubsubMessage).get()
    }

    fun poll(size: Int, subscriptionId: String): List<String> {
        val subscriberStubSettings: SubscriberStubSettings = SubscriberStubSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(credentialsProvider)
            .build()
        GrpcSubscriberStub.create(subscriberStubSettings).use { subscriber ->
            val pullRequest: PullRequest = PullRequest.newBuilder()
                .setMaxMessages(size)
                .setSubscription(ProjectSubscriptionName.format(projectId, subscriptionId))
                .build()
            val pullResponse: PullResponse = subscriber.pullCallable().call(pullRequest)

            return pullResponse.receivedMessagesList
                .map { it.message.data.toStringUtf8() }
                .toList()
        }
    }

}
f4t66c6m

f4t66c6m1#

当我的问题被问到时,我找不到答案。
我找到了一个针对junit-pioneer的Junit5的变通方法,可以在实际测试运行之前将env变量设置为某个值。
因此,代码将与以前相同,但使用@SetEnvironmentVariable进行注解

@SetEnvironmentVariable(key="GOOGLE_APPLICATION_CREDENTIALS", value="dev.json")
class PubSubTestServer {
  ...
}

JUnit-先锋:Maven central.

相关问题