[Tutor] importing modules to be tested
dn
PythonList at DancesWithMice.info
Wed Jan 10 17:09:51 EST 2024
Alex,
On 11/01/24 10:18, Alex Kleider wrote:
> It's been my impression that tests are usually placed in their own
Yes, there are two popular directory-layouts. Either:
project
-- src
-- script
-- tests
-- test-script
or:
project
-- script
-- tests
-- test-script
> separate directory. The problem then arises how to import the
> modules that are to be tested.
Well spotted!
- and yes, both of the above suffer from such.
> My solution has been to use the following code:
Again, you've 'taken the bull by the horns' and bravely attempted to
solve the problem.
However, this is 're-inventing the wheel' and not 'standing on the
shoulders of giants' (who have trod this path before).
There are three popular automated-testing frameworks:
- doctest
- unittest
- pytest
NB there are others, as well as plug-ins/extensions to the above - the
world is your oyster!
I use pytest, and answered this exact question in (yesterday's)
discussion: "Import Issues".
As you have no-doubt anticipated, the business of managing the
PYTHONPATH is pure 'boilerplate' and would have to be repeated in every
single test-script. Boring!
The other advantage is that pytest's reporting can be abbreviated to a
simple "P" or "F" (pass or fail) for each test, which saves you from
having to add reporting print() calls!
Automation is a huge advantage. Thus, it is possible to build test-runs
into CI/CD pipelines, eg tests being run at every git-commit. When I
first started with pytest I didn't learn that one can select only
certain tests be run/code be tested - the system was so fast to test
'everything' that by the time I'd taken the opportunity to stretch my
neck and loosen my shoulders, the results were in! Using PyCharm, pytest
(or other) can be configured into the IDE, and many features made even
easier to use.
Web.Refs:
https://docs.pytest.org/en/7.4.x/getting-started.html
https://www.jetbrains.com/help/pycharm/pytest.html
Blatant advert:
Friday 1500 (NZDT=UTC+13) VacExcHndlrs: Testing:
https://www.meetup.com/nzpug-auckland/events/298338908/
(also, in a few hours (!) Boston, USA) Python Study Group: using mocks
in your tests: https://www.meetup.com/bostonpython/events/298315254/
- which is several steps beyond where you (seem to be) now, but may be
of-interest, serve to inspire...
--
Regards,
=dn
More information about the Tutor
mailing list