https://pantsbuild.org/ logo
#general
Title
# general
p

polite-garden-50641

07/07/2020, 10:44 PM
Is there an example to writing a unit test for a rule that might or might not call await operation to get Snapshot and FilesContent during its execution (obviously I want the logic in the test to provide the file content when running those tests) ?
w

witty-crayon-22786

07/07/2020, 10:51 PM
there is a spectrum between “unit test” and “integration test”, and four distinct zones in that spectrum for tests of
@rules
the most unit testy is
run_rule
: https://github.com/pantsbuild/pants/blob/179dbc9a7e496025d32fd4d0e8bc7dbfa2ffacca/src/python/pants/engine/internals/build_files_test.py#L43-L63 … you must mock everything that a rule uses with
run_rule
(edit: switched to John’s example since he’s right that it’s better for this case)
the most integration testy is
PantsRunIntegrationTest
, which subprocesses pants.
your question leans closer to the first side of the spectrum
so depending on how large the rule is, you might want
run_rule
e

enough-analyst-54434

07/07/2020, 10:54 PM
w

witty-crayon-22786

07/07/2020, 10:55 PM
if the rule is a bit larger / has more dependencies, the next step up is to use
TestBase.request_single_product
to run your rule… to do that you need to install all of the other rules that it needs, or mocked replacements*: https://github.com/pantsbuild/pants/blob/e5eed259f5e21a81ef99efc37074b05a7c2f2952/tests/python/pants_test/backend/python/test_pants_requirement.py#L29-L49
yea. so either
run_rule
or
request_single_product
depending on how much other stuff you want to mock out.
(and for completion’s sake: the final zone on the spectrum is “pretty darn integration testy, but doesn’t actually subprocess”, and you do that by installing all of the rules you’d need to run in prod, and then injecting OptionsBootstrapper: like this: https://github.com/pantsbuild/pants/blob/e5eed259f5e21a81ef99efc37074b05a7c2f2952/src/python/pants/core/util_rules/determine_source_files_test.py#L71-L97 … probably not what you want here.)
p

polite-garden-50641

07/07/2020, 11:07 PM
nice. this is exactly what I was looking for. thanks!
👍 2
4 Views