Pytest where to store expected data

后端 未结 4 898
有刺的猬
有刺的猬 2021-01-31 02:27

Testing function I need to pass parameters and see the output matches the expected output.

It is easy when function\'s response is just a small array or a one-line st

4条回答
  •  余生分开走
    2021-01-31 03:08

    I had a similar problem once, where I have to test configuration file against an expected file. That's how I fixed it:

    1. Create a folder with the same name of your test module and at the same location. Put all your expected files inside that folder.

      test_foo/
          expected_config_1.ini
          expected_config_2.ini
      test_foo.py
      
    2. Create a fixture responsible for moving the contents of this folder to a temporary file. I did use of tmpdir fixture for this matter.

      from __future__ import unicode_literals
      from distutils import dir_util
      from pytest import fixture
      import os
      
      
      @fixture
      def datadir(tmpdir, request):
          '''
          Fixture responsible for searching a folder with the same name of test
          module and, if available, moving all contents to a temporary directory so
          tests can use them freely.
          '''
          filename = request.module.__file__
          test_dir, _ = os.path.splitext(filename)
      
          if os.path.isdir(test_dir):
              dir_util.copy_tree(test_dir, bytes(tmpdir))
      
          return tmpdir
      

      Important: If you are using Python 3, replace dir_util.copy_tree(test_dir, bytes(tmpdir)) with dir_util.copy_tree(test_dir, str(tmpdir)).

    3. Use your new fixture.

      def test_foo(datadir):
          expected_config_1 = datadir.join('expected_config_1.ini')
          expected_config_2 = datadir.join('expected_config_2.ini')
      

    Remember: datadir is just the same as tmpdir fixture, plus the ability of working with your expected files placed into the a folder with the very name of test module.

提交回复
热议问题