Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep Unit tests and Integrations tests separate in pytest

According to Wikipedia and various articles it is best practice to divide tests into Unit tests (run first) and Integration tests (run second), where Unit tests are typically very fast and should be run with every build in a CI environment, however Integration tests take longer to run and should be more of a daily run.

Is there a way to divide these in pytest? Most projects don't seem to have multiple test folders, so is there a way to make sure I only run Unit, Integration or both according to the situtation (CI vs daily builds)? When calculating test coverage, I assume I will have to run both.

Am I going about this the right way in attempting to divide the tests into these categories? Is there a good example somewhere of a project that has done this?

like image 624
Tom Malkin Avatar asked Feb 27 '19 05:02

Tom Malkin


People also ask

Can we use pytest for integration testing?

Yes, you can mark tests with the pytest. mark decorator. Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

Can a unit test be an integration test?

As mentioned earlier, unit testing involves testing individual pieces of code while integration testing involves testing modules of code to understand how they perform alone and how they interact with each other. Another difference between the two is the frequency with which each test should be executed.

Can we use pytest and unittest together?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.

Do we need unit tests and integration tests?

Conclusion. Unit testing and integration testing are both important parts of successful software development. Although they serve different yet related purposes, one cannot replace the other. They complement each other nicely.


1 Answers

Yes, you can mark tests with the pytest.mark decorator.

Example:

def unit_test_1():     # assert here  def unit_test_2():     # assert here  @pytest.mark.integtest def integration_test():     # assert here 

Now, from the command line, you can run pytest -m "not integtest" for only the unit tests, pytest -m integtest for only the integration test and plain pytest for all.

(You can also decorate your unit tests with pytest.mark.unit if you want, but I find that slightly tedious/verbose)

See the documentation for more information.

like image 85
gmds Avatar answered Oct 11 '22 22:10

gmds