DEV Community

Paul Roub
Paul Roub

Posted on • Originally published at roub.net

Matching form posts in the Pretenders mock HTTP server

I've used the Pretenders "Fake servers for testing" on a number of work and personal projects, with generally good results. But I've wished that it was easier to write tests against different HTML form post contents.

Pretenders can return results based on specific URLs (of course), HTTP headers, query string parameters, body contents, and so on. But if that body is the result of a form? You'd better know:

  1. If it was sent url-encoded or multipart
  2. In what order the fields will be arriving

And be willing to deal with those specifically via RegEx matches.

But I don't want to care about those things. I want to say "here are the form fields and values I'm expecting, respond if you see them."

I'd submit a feature request if the project wasn't borderline abandonware1. But hey, that's why we use open source tools, no?

In my fork at github.com/paulroub/pretenders/tree/match-form-data, I've added an optional data parameter to the when() method. It takes a dictionary, e.g.

http_mock.when('POST /hello', data={'one': 'first', 'two': 'second'}).reply(b'First and Second passed', times=FOREVER)

This will match when a form is posted to /hello, and fields "one" and "two" have the expected values. It does not care in what order those fields were passed, nor which encoding method was used to submit the form.

I've submitted a pull request, but since the project was last touched in 2017 I'm not overly optimistic. In the meantime, you can use the forked version directly, either by saying:

pip install 'git+https://github.com/paulroub/pretenders.git@match-form-data#egg=pretenders'

or by including

git+https://github.com/paulroub/pretenders.git@match-form-data#egg=pretenders

in your requirements.txt file.

The fork currently has a userbase of "me", so comments, suggestions, and bug fixes are even more welcome than usual.


  1. If you're starting a new project, I'd look at alternatives; mockttp is nice, for example. 

Top comments (0)