繁体   English   中英

在测试环境中创建的新用户的 ID 使用 Wallaby/Phoenix 不断增加

[英]New users being created in test environment have their IDs continually incrementing using Wallaby/Phoenix

我是 Elixir/Phoenix 的新手,所以我不确定这是否按预期工作或我应该解决的问题。

我有一个 Phoenix 应用程序,我刚刚开始向其中添加集成测试。 经过几天的设置和测试用户注册功能,我现在开始测试登录。

我正在使用小袋鼠:

测试.exs:

config :happy_app, :sql_sandbox, true
config :wallaby,
  driver: Wallaby.Experimental.Chrome,
  chrome: [headless: true],
  screenshot_on_failure: true

test_helper.exs:

ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(HappyApp.Repo, :manual)
{:ok, _} = Application.ensure_all_started(:wallaby)
Application.put_env(:wallaby, :base_url, HappyAppWeb.Endpoint.url())

我的测试是这样的:

defmodule HappyAppWeb.UserLoginTest do
  use HappyAppWeb.IntegrationCase, async: true

  alias HappyApp.Accounts
  import HappyAppWeb.IntegrationSteps

  @tag integration: true
  test "user can login", %{session: session} do
    email = "test-user@example.com"
    password = "12345678"

    # seed user into db
    user = Accounts.create_user(%{email: email, password: password})
    IO.inspect user

    # logging in with the user's email and password

    # asserting the view is correct
  end
end

当我检查用户时: IO.inspect user我得到:

IO.inspect user


=>
{:ok,
 %HappyApp.Accounts.User{
   __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
   email: "test-user@example.com",
   id: 449,
   inserted_at: ~N[2019-11-24 13:20:33],
   password: nil,
   password_hash: "shhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
   updated_at: ~N[2019-11-24 13:20:33]
 }}

注意id: 449, 那是对的吗? 这不应该在测试之间重置回 1 吗?

手动查看 postgres 我发现 happy_app_test db 确实是空的。 数据在别处吗?

看看凤凰测试文档 happy_app_test db 为空的原因:

默认的测试帮助文件 test/test_helper.exs 为我们创建和迁移我们的测试数据库。 它还为每个要运行的测试启动一个事务。这将通过在每个测试完成时回滚事务来“清理”数据库。

以及为什么 id 不从 1 开始是数据库保留 AUTO_INCREMENT id 除非您重置数据库或指定 postgres database

更新:查看 mix.exs 文件

  defp aliases do
    [
      "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
      "ecto.reset": ["ecto.drop", "ecto.setup"],
      test: ["ecto.create --quiet", "ecto.migrate", "test"]
    ]
  end

当您运行mix test 时,它实际上会调用 3 个命令: "ecto.create --quiet", "ecto.migrate", "test" 这就是为什么每次测试后数据库都是干净的。

这个东西跟数据库引擎有关。 我找不到可以肯定的信息,但是我怀疑回滚正在删除以前插入的行。

删除行时,id 计数器不会重置,它会继续递增。 基本上你需要删除/更新表来重置计数器,或者如果你真的需要,你可以手动重置它。

如果您重新启动测试,您会注意到插入记录的第一个测试将从 1 开始,其他测试将继续计数器,因为在测试之前您运行迁移并创建一个带有新串行计数器的新表。

如果您有兴趣了解有关 id 自动递增的更多信息,您可以在这里阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM