Skip to content

Testing

Tomas Tomecek edited this page Oct 3, 2019 · 6 revisions

Mocking

Flexmock

mocked_object = flexmock(
    active_branch="branch",
    working_dir="example/path",
    remote=lambda: flexmock(urls=["http://example/url"]),
)
  • Easy checking of calls, replacing of the method implementation:
mocked_object = (
    flexmock()
    .should_receive("get_project")
    .with_args(repo="repo", namespace="namespace")
    .replace_with(lambda repo, namespace: flexmock())
    .mock()
)
  • Overwritting existing objects:
MockedRepo = (
    flexmock(git.Repo)
    .should_receive("remote")
    .replace_with(lambda: flexmock(urls=["http://example/url"]))
    .mock()
)
repo = MockedRepo()
  • Mocking of the imports (objects/functions used somewhere in the code) -- same syntax, but you do not need to finalize with .mock():
flexmock(
    git,
    Repo=flexmock(
        active_branch="branch", remote=lambda: flexmock(urls=["git/url"])
    ),
)

Tips & tricks

This section is a collection of the tricks which our team finds out during writing tests for our projects. The ultimate goal of this write-up is to propose the most relevant tips to upstream documentation.

Using should_receive with with_args

Let's say we have a class like this with one simple method.

class Plane:
    def fly(self, from, to):
        pass

And you call it somewhere in your code like this:

plane = Plane()
Plane.fly('OPO', 'BTS')

You might want to use flexmock to check whether this method was called at least once, with specific arguments.

flexmock(Plane).should_receive('fly').with_args(from='OPO', to='BTS').once()

Unfortunately, this would not work, because if you use kwargs in tests you have to use them also in the code which you are testing, so:

plane = Plane()
Plane.fly(from='OPO', to='BTS')

TOX

[tox]
# Operate on these virtual environments
envlist =
    py36
    py37

[testenv]
# Dependencies to install in each environment
deps =
    flexmock
    pytest
    pytest-cov
# Command to run in each environment
commands =
    pytest --color=yes --verbose --showlocals --cov=packit --cov-report=term-missing

Since we use CentOS CI, where's no Python 3.7, we run tox -e py36 to use just Python 3.6 environment.

Clone this wiki locally