在伞中集成测试Web应用程序的问题

时间:2016-11-26 10:51:09

标签: elixir phoenix-framework ecto ex-unit

我正在研究凤凰应用程序。此应用程序是伞应用程序的一部分。在这个保护伞中,我有一些小应用程序负责应用程序的不同领域,它们是:

  • phoenix web api(" api")
  • 核心业务逻辑("核心")
  • 用户身份验证(" auth")
  • 数据库架构(" db")

" API"取决于"核心"和#34; auth",而这两个应用程序依赖于" db"。

只有" db"应用程序有一个ecto repo,所有其他应用程序都没有。回购是由" db"应用程序并受到监督。

现在我想在" api"中测试我的控制器。应用。这是我遇到ecto问题的地方。当我测试控制器动作时,此动作将调用来自" auth"或"核心",它调用来自" db"的Repo的函数。 (例如Repo.insert/2)。这会产生OwnershipError

** (DBConnection.OwnershipError) cannot find ownership process for #PID<0.458.0>.

When using ownership, you must manage connections in one                         
of the three ways:                                                               

  * By explicitly checking out a connection                                      
  * By explicitly allowing a spawned process                                     
  * By running the pool in shared mode                                           

The first two options require every new process to explicitly                    
check a connection out or be allowed by calling checkout or                      
allow respectively.                                                              

The third option requires a {:shared, pid} mode to be set.                       
If using shared mode in tests, make sure your tests are not                      
async.                                                                           

If you are reading this error, it means you have not done one                    
of the steps above or that the owner process has crashed.                        

See Ecto.Adapters.SQL.Sandbox docs for more information.                         

我现在的问题是,我不知道如何使用&#34; api&#34;中的建议解决方案来解决此错误。测试为&#34; api&#34;应用程序不知道&#34; db&#34;应用程序因此无法进行连接检查。当我在直接依赖于&#34; db&#34;的应用程序上遇到此错误时项目我能够应用&#34;共享模式&#34;溶液

我的问题是如何用我的&#34; api&#34;来解决所有权问题。集成测试。

1 个答案:

答案 0 :(得分:1)

以下是一些在伞形模式下运行测试的警告(如错误消息中所述)

  1. 您的受托回购需要“签出”
  2. 你的依赖回购可能永远不会开始
  3. 您的从属回购可能无法以“共享”模式运行
  4. 从那里开始,也许你的test_helper.exs可能看起来像这样(伪代码):

    ExUnit.start
    
    Db.Repo.start_link()
    Core.Repo.start_link()
    Auth.Repo.start_link()
    
    Ecto.Adapters.SQL.Sandbox.checkout(Db.Repo)
    Ecto.Adapters.SQL.Sandbox.checkout(Core.Repo)
    Ecto.Adapters.SQL.Sandbox.checkout(Auth.Repo)
    
    Ecto.Adapters.SQL.Sandbox.mode(Api.Repo, :manual)
    Ecto.Adapters.SQL.Sandbox.mode(Db.Repo, :shared)
    Ecto.Adapters.SQL.Sandbox.mode(Core.Repo, :shared)
    Ecto.Adapters.SQL.Sandbox.mode(Auth.Repo, :shared)
    

    <强>更新

    不要忘记在mix.exs

    中包含DB的项目路径
    defp deps do
       [
          ...
          {:db, path: "path/to/db"},
          ...
       ]
    end