如何在测试后重置 Docker 中的 Redis 数据库集合?

huangapple go评论59阅读模式
英文:

How to reset a Redis database set in Docker after a test?

问题

以下是您要翻译的内容:

"I have the user access token saved in the Redis database on a Docker container when running tests.

The first time the test runs, it works well. But because I can not manage to reset the Docker container, the access token leaves on from other tests, which makes the test fails as the user session still exists in between tests.

The access token is used with the AsyncBearerAuthenticator, which ensure that the passed token in the headers validates the user on a desired route.

I have created this helper, to save the token in the Redis database when testing. But I would like to delete the token after each test, or completely reset the database.

extension Application {

  @discardableResult
  func test(
    _ method: HTTPMethod,
    _ path: String,
    user: UserModel? = .none,
    tokenProtected: Bool = true,
    content: (any Content)? = .none,
    afterResponse: (XCTHTTPResponse) throws -> () = { _ in },
    file: StaticString = #file,
    line: UInt = #line
  ) async throws -> XCTApplicationTester {

    var headers: HTTPHeaders = [:]
    if let user, tokenProtected {
      let accessToken = try AccessTokenModel.generate(for: user)
      try await self.redis.set(RedisKey(accessToken.value), toJSON: accessToken)
      headers.add(name: "Authorization", value: "Bearer \(accessToken.value)")
    }

    return try test(
      method,
      path,
      headers: headers,
      file: file,
      line: line,
      beforeRequest: { if let content { try $0.content.encode(content) }},
      afterResponse: afterResponse
    )
  }
}

This is the way I have configure Redis for the tests in the configure.swift file.

app.redis.configuration = try RedisConfiguration(hostname: "localhost", port: 6380)
app.sessions.use(.redis)

This is the way I create the Docker container for Redis.

docker run --name myapp_redis_testing -p 6380:6379 -d redis
```"

<details>
<summary>英文:</summary>

I have the user access token saved in the Redis database on a Docker container when running tests. 

The first time the test runs, it works well. But because I can not manage to reset the Docker container, the access token leaves on from other tests, which makes the test fails as the user session still exists in between tests.

The access token is used with the `AsyncBearerAuthenticator`, which ensure that the passed token in the headers validates the user on a desired route. 

I have created this helper, to save the token in the Redis database when testing. But I would like to delete the token after each test, or completely reset the database. 

```swift
extension Application {

  @discardableResult
  func test(
    _ method: HTTPMethod,
    _ path: String,
    user: UserModel? = .none,
    tokenProtected: Bool = true,
    content: (any Content)? = .none,
    afterResponse: (XCTHTTPResponse) throws -&gt; () = { _ in },
    file: StaticString = #file,
    line: UInt = #line
  ) async throws -&gt; XCTApplicationTester {

    var headers: HTTPHeaders = [:]
    if let user, tokenProtected {
      let accessToken = try AccessTokenModel.generate(for: user)
      try await self.redis.set(RedisKey(accessToken.value), toJSON: accessToken)
      headers.add(name: &quot;Authorization&quot;, value: &quot;Bearer \(accessToken.value)&quot;)
    }

    return try test(
      method,
      path,
      headers: headers,
      file: file,
      line: line,
      beforeRequest: { if let content { try $0.content.encode(content) }},
      afterResponse: afterResponse
    )
  }
}

This is the way I have configure Redis for the tests in the configure.swift file.

app.redis.configuration = try RedisConfiguration(hostname: &quot;localhost&quot;, port: 6380)
app.sessions.use(.redis)

This is the way I create the Docker container for Redis.

docker run --name myapp_redis_testing -p 6380:6379 -d redis

答案1

得分: 1

要在每次测试后清除在Docker上设置的Redis数据库,必须在测试套件的拆卸过程中触发FLUSHALL命令。

因此,在方法func tearDownWithError() throws中添加Redis命令以清除数据库。

var sut: Application!

override func setUpWithError() throws {
  try super.setUpWithError()
  sut = Application(.testing)
  try configure(sut)
  try sut.boot()
}

override func tearDownWithError() throws {
  _ = try sut.redis.send(command: "FLUSHALL").wait() // 重置Redis容器
  sut.shutdown()
  sut = .none
  try super.tearDownWithError()
}
英文:

To clear the Redis database set on Docker after each test, the command FLUSHALL must be triggered within the tear down of the test suit.

So in the method func tearDownWithError() throws add the redis command to clear the database.

var sut: Application!

override func setUpWithError() throws {
  try super.setUpWithError()
  sut = Application(.testing)
  try configure(sut)
  try sut.boot()
}

override func tearDownWithError() throws {
  _ = try sut.redis.send(command: &quot;FLUSHALL&quot;).wait() // Reset Redis container
  sut.shutdown()
  sut = .none
  try super.tearDownWithError()
}

huangapple
  • 本文由 发表于 2023年6月25日 20:18:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定