title: Spin up a local flask server for testing with pytest
body: <p>I have the following problem.</p>
  
  <p>I'd like to run tests on the local flask server before deploying to production. I use pytest for that. My conftest.py looks like that for the moment:</p>
  
  <pre><code>import pytest
  from toolbox import Toolbox
  import subprocess
  
  
  def pytest_addoption(parser):
      """Add option to pass --testenv=local to pytest cli command"""
      parser.addoption(
          "--testenv", action="store", default="exodemo", help="my option: type1 or type2"
      )
  
  
  @pytest.fixture(scope="module")
  def testenv(request):
      return request.config.getoption("--testenv")
  
  
  @pytest.fixture(scope="module")
  def testurl(testenv):
          if testenv == 'local':
              return 'http://localhost:5000/'
          else:
              return 'https://api.domain.com/'
  </code></pre>
  
  <p>This allows me to test the production api by typing the command <code>pytest</code> and to test a local flask server by typing <code>pytest --testenv=local</code></p>
  
  <p>This code WORKS flawlessly. </p>
  
  <p>My problem is that I have to manually instantiate the local flask server from the terminal each time I want to test locally like this:</p>
  
  <pre><code>source ../pypyenv/bin/activate
  python ../app.py
  </code></pre>
  
  <p>Now I wanted to add a fixture that initiates a terminal in the background at the beginning of the tests and closes the server down after having finished testing. After a lot of research and testing, I still cannot get it to work. This is the line I added to the conftest.py:</p>
  
  <pre><code>@pytest.fixture(scope="module", autouse=True)
  def spinup(testenv):
      if testenv == 'local':
          cmd = ['../pypyenv/bin/python', '../app.py']
          p = subprocess.Popen(cmd, shell=True)
          yield
          p.terminate()
      else:
          pass
  </code></pre>
  
  <p>The errors I get are from the requests package that says that there is no connection/ refused. </p>
  
  <blockquote>
    <p>E           requests.exceptions.ConnectionError:
    HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded
    with url: /login (Caused by
    NewConnectionError(': Failed to establish a new connection:
    [Errno 111] Connection refused',))</p>
    
    <p>/usr/lib/python3/dist-packages/requests/adapters.py:437:
    ConnectionError</p>
  </blockquote>
  
  <p>This means for me that the flask server under app.py is not online. Any suggestions? I am open to more elegant alternatives</p>