【问题标题】:Create server at the beginning of pytest test在 pytest 测试开始时创建服务器
【发布时间】:2019-11-07 14:06:38
【问题描述】:

我想在测试开始之前创建服务器,然后在所有测试运行后终止它。以下行为描述。

我第一次运行测试:
1.返回错误(下)
2. 测试失败
3. 服务器被调用(现在服务器正在运行)

我第二次运行测试:
1.返回同样的错误(下)
2. 测试通过
3.服务器关闭

错误: 发生异常:RuntimeError 无法启动进程服务器

@pytest.fixture(autouse=True, scope="session")
def start_server(xprocess):
    port = 8000
    server_path = py.path.local(__file__).dirpath("service.py")
    xprocess.ensure("server", lambda cwd: ("started", [sys.executable, server_path, port]))
    yield
    xprocess.getinfo("server").terminate()

【问题讨论】:

    标签: python server pytest fixtures


    【解决方案1】:

    解决方案:

    def server(host, port):
        # definition of your server
    
    @pytest.fixture(autouse=True, scope="session")
    def start_server():
        p = multiprocessing.Process(target=server, args=(host, port))
        p.start()
        yield
        p.terminate()
    

    【讨论】:

      【解决方案2】:

      为了将来参考,这是pytest-xprocess插件的确切应用。您可以编写如下所示的简单夹具来启动服务器实例并使其在测试中可用:

      # content of conftest.py
      
      import pytest
      from xprocess import ProcessStarter
      
      @pytest.fixture
      def myserver(xprocess):
          class Starter(ProcessStarter):
              # startup pattern
              pattern = "PATTERN"
      
              # command to start process
              args = ['command', 'arg1', 'arg2']
      
          # ensure process is running and return its logfile
          logfile = xprocess.ensure("myserver", Starter)
      
          conn = # create a connection or url/port info to the server
          yield conn
      
          # clean up whole process tree afterwards
          xprocess.getinfo("myserver").terminate()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多