pythonconnexion

How do I mock headers with connexion?


I am using connexion to read a few headers in my productive code, i.e.:

from connexion import request

def get_my_header() -> str:
    return request.headers.get("my-header")

In the connexion docs I found the TestContext. This sounds quite promising, but I can't find any example on how I would mock headers, so that when testing get_my_header() the headers are set. I have tried many different ways on how to set this up. I found this promising, but it just won't work:

from connexion.testing import TestContext

def test_get_my_header():
  request = MagicMock()
  request.headers = {"my-header": "header-value"}
  with TestContext(context={"request": request}):
    # test code

Any ideas are appreciated!


Solution

  • I finally found it. The headers are set through the scope rather than the context. TestContext even has a static method to build those:

    from connexion.testing import TestContext
    
    def test_get_my_header():
      with TestContext(
        scope=TestContext.build_scope(headers=[(b"my-header", b"header-value")])
      ):
        # test code