How to fix TypeError: () got an unexpected keyword argument

Pavol Kutaj
1 min readJun 23, 2023

--

The aim of this page📝 is to analyze the following instance of Python TypeError:

TypeError: mock_requests_delete() got an unexpected keyword argument 'headers'

I got that as my pytest unit test was failing while mocking the requests.delete function call with mock_requests_delete()s

  • My unit test is as follows
""" CODE """
def request_deletion(env, schema_data):
url = schema_data.url_dev if env == "DEV" else schema_data.url_prod
headers = schema_data.headers_dev if env == "DEV" else schema_data.headers_prod
res = requests.delete(url,
headers,
data=json.dumps(
schema_data.schema).encode("utf-8"),
verify=schema_data.cert_file)
res.raise_for_status()okr
return res

""" TEST """
class MockResponse:
def __init__(self, status_code, content):
self.status_code = status_code
self.content = content.encode()

def __repr__(self) -> str:
return f"<Response [{self.status_code}]>"

def test_request_deletion_returns_res_object_with_mock_http_response(monkeypatch):
def mock_requests_delete(_, __, ___, ____):
return MockResponse(204, "No Content")

with push_and_pop_path(MODULE_PATH):
schema = schema_patcher.Schema()
monkeypatch.setattr(
schema_patcher_http_requestor.requests, "delete", mock_requests_delete)
res = schema_patcher_http_requestor.request_deletion("DEV", schema)
assert res.status_code == 204
assert res.content.decode() == "No Content"
  • The failure occurs when there are keywords arguments in the call that do not exist in the signature
  • In other words
""" CALL """
requests.delete(url,
headers,
data=json.dumps(schema_data.schema).encode("utf-8"),
verify=schema_data.cert_file)
""" SIGNATURE """
def mock_requests_delete(_, __, ___, ____): #...
#^^^ #^^^^
#!=data
#!=verify
  • A strict way to fix this would be to add keyword parametes and assign them a None default value
def mock_requests_delete(_, __, headers=None, verify=None):
return MockResponse(204, "No Content")
  • A quick fix is to use *args and **kwargs in the mock to be able to accept any parameter
def mock_requests_delete(*args, **kwargs):
return MockResponse(204, "No Content")

--

--

No responses yet