Following up on my Q about writing unit tests for ...
# plugins
p
Following up on my Q about writing unit tests for plugins (a little further up in this channel), I wondering if I’m mocking pants classes correctly. I have working unit tests now and not running into any issues. However, the code feels “dirty” as I often need to manually appends properties to pants classes in order to make tests pass. For example when mocking
PythonDistribution
I also need to manually specify its
address
property since the plugin code I’m testing expects the mock to have it:
Copy code
python_distributions = Mock(PythonDistribution)
python_distributions.address = Address
When trying to correctly construct objects from the various pants-native classes (e.g.
PythonDistribution
,
Dependents
,
Address
, etc) I often run into errors and then need much more boilerplate code to create. Thoughts?
Here’s the full unit test to illustrate several such property appending statements going on.
e
So, Pants has this many test files:
Copy code
$ find -name "*_test.py" | wc -l
428
And, as a percentage, it uses mocking in less than 3% of test files:
Copy code
$ find -name "*_test.py" | xargs git grep unittest | grep mock | grep import | cut -d: -f1
build-support/bin/generate_json_schema_test.py
src/python/pants/backend/javascript/subsystems/nodejs_test.py
src/python/pants/backend/python/goals/pytest_runner_integration_test.py
src/python/pants/backend/python/util_rules/pex_from_targets_test.py
src/python/pants/base/deprecated_test.py
src/python/pants/base/exception_sink_test.py
src/python/pants/core/goals/generate_lockfiles_test.py
src/python/pants/engine/internals/platform_rules_test.py
src/python/pants/jvm/resolve/coursier_fetch_filter_test.py
src/python/pants/option/option_types_test.py
src/python/pants/option/options_test.py
src/python/pants/util/dirutil_test.py
In other words, by example, you probably shouldn't need to use mocking at all. Have you looked at how Pants tests itself yet?
p
It’s a great point. I looked for
Mock(
and saw that there were very few mocks. I’m looking through the various tests in the pants repo now, thanks