Limitations¶
diffcone is designed to select too many tests rather than too few. These are the cases where it selects more than you might expect, or can't see everything.
What a change reaches¶
- Changes that run on import reach every importer.
-
A change to code that runs when a module is imported (a module-level statement, a class body, a decorator) selects every target whose module imports that module, directly or indirectly. In a codebase where most modules import a few central ones, such a change selects most tests.
With a recording, a changed constant or class attribute selects only the tests that read it. Other code that runs on import (a module-level statement, a decorator) is still planned this way.
- Functions under unknown decorators count as import-time code.
-
@decoover a function is a calldeco(f)when the module is imported, and the decorator may call the function then. So a change to the function's body counts as a change to code that runs on import, unless diffcone knows the decorator calls nothing of it:- a decorator such as
property,staticmethod,functools.cache,pytest.fixtureordataclasses.dataclass; - a decorator of your own that only sets attributes and returns the
function, or a
functools.wrapswrapper.
A decorator from an installed package (a compiled
cache_readonly, say) is one diffcone can't read. - a decorator such as
- Class-level changes affect every method.
- A change to a class's body (its bases, decorators or class attributes) affects all of its methods.
- Removed imports affect the whole module.
- Removing or redirecting an import affects the whole importing module. Adding one affects only the code that uses the new name, unless the imported module runs code of its own that the importing module did not run before.
- A change to a file diffcone doesn't read selects everything.
-
Under your source roots, diffcone reads only
.pyfiles, and not those[index] excludelists. A change to any other file there (a data file, a.pyx, aREADME.md, a configuration file) selects every target, since code or tests may read it. So does a change to a file's mode (a script made executable, a file turned into a symlink).diffcone.tomland.diffcone/are the exceptions.With the source root
.(the default), the whole repository is under a root, so editingREADME.mdselects every test. With a recording, most such changes select only the tests that read the file.
Calls and lookups¶
- Calls through objects of unknown type are matched by name.
-
diffcone doesn't infer types.
self.method()andcls.method()are resolved through the class hierarchy. A call likeobj.run()on an object of unknown type is matched against every method namedrun, and against module-levelrunin modules such an object could be. The calling code is selected when any of those changes.A module "such an object could be" is one your code passes around as a value or binds to another name (
m = ops), gets by name (importlib.import_module,sys.modules, a string naming it), or one pytest hands out (test modules, conftests). A name bound only to modules (m = ops, thenm.value()) is followed like the import itself.An instance attribute is followed only when every assignment of it is in
__init__and assigns a parameter, a string, or one of your functions or classes by name. An attribute that holds an object (self.client = Client()) is not typed for calls:self.client.get()is matched against every method namedget. - Dynamic lookups are bounded by imports, if at all.
-
Code that uses
eval,exec,globals(),vars(),getattrwith a computed name, orlocals()at module level (where it is the module's namespace) is treated as affected by any change in the modules its module imports, and in the modules of code that stores objects on one of those modules. Some code changes that bound:- Lookups on a library module.
getattr(logging, name)is bounded unless your code may store something on that module: directly, by handing the module to other code, or by putting an object insys.modulesunder its name. Then any change can affect the lookup. A patch undone when the test ends doesn't count (see Patches in tests below). - Lookup tables. A name taken from a dict, list or set written in
the code (
getattr(handlers, NAMES[key]), the export table of a lazy__getattr__) is bounded by that table only while nothing can change it. Once the table, or the module holding it, is modified, passed to other code, or reached throughglobals(),vars(),sys.modulesorexec, the lookup counts as dynamic. A parameter or local variable that happens to share the table's name isn't bounded by it. - Names in strings.
operator.attrgetter("a.b"),methodcaller("m"), a format template's fields ("{0.name}") and amatchclass pattern (case C(x=1), orcase C(1)through__match_args__) read attributes by name. They are matched likegetattr(x, "a"). A name or template that isn't written out is bounded by what callers pass, or else counts as dynamic. - Names that start with fixed text.
f"plugins.{name}"is bounded to the modules it can name.
- Lookups on a library module.
- Code loaded at run time can be affected by any change.
-
These can reach any of your code, so the code using them is selected for any change:
- a module imported or run by a name nothing bounds
(
importlib.import_module(name),runpy.run_module(name),runpy.run_path(path)); - a module loaded from a file whose path is computed
(
importlib.util.spec_from_file_location); - an object unpickled from data the code doesn't write out. A
pickle.loads(pickle.dumps(x))round trip, and bytes written in the code, are followed.
- a module imported or run by a name nothing bounds
(
- Modules obtained at run time count as any of your modules.
-
A module your code gets by a name it computes counts as any of your modules, so passing it on or writing to it makes every lookup table dynamic. The same goes for a function's
__globals__, a frame'sf_globals, and whatpickle.loads,pkgutil.resolve_nameorpydoc.locategiven a computed name, orgc.get_objects(), hand back.Two exceptions: a name that starts with fixed text, and a new module (
types.ModuleType(name)) that isn't installed insys.modulesunder a name of yours. A copy made withimportlib.util.module_from_speccounts as the module whose file it loads. - Replacing a module in
sys.modulesreaches every importer. - Code that puts an object in
sys.modulesfor good under a computed name may replace any of your modules. Without a recording, every test that imports one of them depends on that code. - Code importing a name you install a module under reads that module.
- When your code puts one of your modules in
sys.modules(sys.modules["compat"] = implin a package__init__, a fake for a library in a fixture:monkeypatch.setitem(sys.modules, "extlib", fakes)), code that imports the name gets that module. Code that imports it, reads an attribute off it or looks a name up on it (compat.run(),getattr(compat, "run"),hasattr(compat, name)) depends on everything in the installed module, and on the code that installed it. Under a computed name, that holds for every library name your code imports. If what is installed is a module loaded from a computed path (importlib.util.module_from_spec), any change can affect that code (a module your code creates,types.ModuleType(name), or finds under the name already, is not one, and neither is a module a fixture puts back from a copy ofsys.modulesit saved, under the name it was saved under). The same goes when your code installs a module it was handed (def install(mod): sys.modules["extplug"] = mod), because diffcone doesn't follow which module the caller passes. An install made by a fixture or a test counts for the tests that run it (see Tests are assumed not to depend on what an earlier test left behind below). A plugin thatpytest_plugins,-porPYTEST_PLUGINSnames this way is the module installed under the name; if diffcone can't tell which module that is (an object your code builds, a module it creates, finds at run time or was handed), every test is always selected. When your code installs under a name it computes, a plugin that no file in your repository provides may be what it installs: every test is always selected when that may be any module (loaded from a computed path, or handed in), and every test depends on the installing code when it is a module the code creates. Both are reported with aplugin_installednote. Installs made only by a test or a function-scoped fixture don't count here, since they run after pytest has loaded its plugins. A plugin file of that name still counts as well, since pytest imports it when the install hasn't run yet.
Objects and modules handed to other code¶
- Passing a module on depends on all of it.
- Code that passes a module to other code (
read(ops, name)) depends on everything in that module and on what its imports bind (api.core.TABLE). That holds whether the module is named by an import or obtained withimportlib.import_module("pkg.sub"). - Passing an object on depends on all of its methods.
- Code that hands an instance of one of your classes to other code
depends on every method of that class, since the receiving code may
call any of them by name. That covers a library (
json.dump(x, w),csv.writer(w),print(file=w),dict(obj),handler.stream = w), a method on an object of unknown type (items.append(w)), and your own functions. Builtins that only use dunder methods (len,str,iter,sorted) don't count. The instance counts as handed on however it gets there: held in a variable first (obj = Impl(); check(obj)), in a list or dict, on an attribute (check(self.obj)), in a module-level variable, returned by a factory, or returned or yielded by a fixture the test receives. So does whatever such an object holds in its attributes. An exception you raise and anisinstance(obj, Proto)check written next to where the instance is made don't count.
Code a test runs from text or in another process¶
- Text run as code.
exec,eval,timeitand pytest'spytester.makepyfilerun text. Text written in the code (a string, a constant, a template filled with literals) is read as code: what it imports and calls counts. Text built at run time or read from a file can import anything, so the test is selected for any change. Text passed in as a helper's argument is read at each call site. A template filled by the test's own argument is read once per value when@pytest.mark.parametrizeon the test function lists literal values for it (and the test has no decorator other than pytest marks); values from a fixture,indirect=True, or a parametrize on the class or inpytestmarkcount as built at run time.- Tests that use
pytester. - A test using
pytesterortestdirruns a pytest session of its own, with your project's registered plugins loaded. It depends on every fixture those plugins define, and on what its inline test code imports. - Python programs a test starts.
-
A test that runs a script or module of your project in a new process depends on that program and on what it imports, when the code names it in a string:
[sys.executable, "scripts/gen.py"],python -m mypkg.tool,python -c "import mypkg". This also works afterenv X=1,uv runortimeout 30, and withasyncio.create_subprocess_exec.- A test file given to a test runner (
python -m pytest tests/test_x.py,pytest.main([...]),python -m unittest tests.cases) runs whole: the test depends on everything in that file and itsconftest.pyfiles. - A
.pyfile no module name maps to (scripts/gen-data.py) is read like-ccode: the test depends on the file and on what it imports. - When the program is built at run time, the test is selected for any
change: a path from a variable or the environment,
-ccode assembled from pieces, a program that imports by a computed name or changessys.path,*args, a directory,unittest discover, or a test runner given no file at all (pytest.main(["-q"])collects your whole suite). A word after an option diffcone doesn't know to take a value (--verbose docs) counts as a path the runner collects. - Console scripts your project installs and files outside your source roots aren't seen.
Execution evidence follows the processes a test starts.
- A test file given to a test runner (
State shared between tests¶
- State changed in place reaches every reader.
-
Code that changes a module-level object, directly or by handing it to a function that changes it (
register(REGISTRY),registry.add(x)), is a dependency of every reader of that object. A change to a function also reaches the readers of whatever the functions it calls change in place. A function changing what it gets in*argsor**kwargs(for o in objs: o.seen = True) changes what its callers pass, and a call passing*ITEMSor**OPTIONSpasses what they hold.Logging counts as a call too. A log call (
log.warning(...),logging.info(...),logging.getLogger(name).error(...)) runs what you handed thelogginglibrary: handlers, filters and formatters added withaddHandler,addFilter,setFormatter,basicConfig(handlers= ...)or by settinghandlers, a filter function, a record factory, any class of yours deriving from aloggingclass, the methods of a logger class you set withlogging.setLoggerClass(a function you store on one of those classes under such a method's name too), and, afterlogging.config.dictConfigorfileConfig, any method of yours with a handler's, filter's or formatter's method name. What they change (a capture handler's list, a counter) is changed by every log call. The record a log call makes holds what was logged, whatever the logger: changingrecord.argsorrecord.msgin place changes your objects, while setting an attribute on the record does not, unless you install a record factory or give the logger class your ownmakeRecord.The same holds for state kept on a class (
Config.mode = m,Config.items.append(x),setattr(Config, "mode", m),cls._instance = cls(),type(self)._cache[k] = v): the code storing it is a dependency of every reader of the class. When the class can't be known (type(obj).mode = morobj.__class__.items.append(x), whereobjis a parameter or comes from a call), the code is a dependency of the readers of each of your classes that has that attribute (its body or one of its methods sets it, or other code gives it that attribute), of each class deriving from a library class, and of their subclasses, or of every class for a special attribute (__doc__), for an attribute none of your classes has, and for a name only known at run time (setattr(type(obj), name, v)). A mock's class is its own, sotype(mock).name = PropertyMock(...)changes none of your classes. And it holds when the code reaches the object by another name:- a local name for it:
cache = _CACHE, thencache[k] = v(also(cache := _CACHE),for cache in (_A, _B),with nullcontext(_CACHE) as cache); - a part of it:
entry = _CACHE[k]orentry = _CACHE.setdefault(k, []), thenentry.append(v); - a bound method:
put = _CACHE.__setitem__, thenput(k, v); - what one of your functions returns:
registry()[k] = v, whereregistryreturns_CACHE, and anything a function returns when a decorator may keep its result: any decorator but one known to hand back the function or call it afresh (property,staticmethod,functools.wraps,contextmanager, pytest's marks) or one of yours that returns the function itself (sofunctools.cache,lru_cache,cached_propertyand a memoizing decorator of yours all count): every call may hand back the same object; - what a lambda, a closure or a
functools.partialbound to a name returns (get_cache = lambda: _CACHE, thenget_cache()[k] = v); globals()["_CACHE"][k] = v.
A class is followed by another name as well: an alias (
Alias = Config,c = Config), a dict, tuple or loop over classes (config_by_name["test"].DEBUG = True), a parameter's default (def f(klass=Config)),getattr(module, "Config"), the module got by name (import_module,sys.modules,vars(module)[...],module.__dict__[...]),type.__setattr__(Config, ...), an item ofSub.__mro__orSub.__bases__(also oftype(obj)), and what a call handed the class gives back (HANDLERS.get(k, Default)). Calling such a name (Alias(),functools.partial(Config)(),getattr(module, "Config")()) makes an instance of the class. A mock made with the class as its spec (create_autospec(Config),Mock(spec=Config)) is not the class; what it wraps or returns (wraps=Config,return_value=Config) is. A method a library gives your class, called on the class itself, may keep state on it:Base.register(Foo)on a class deriving fromabc.ABC(or with theabc.ABCMetametaclass) andCase.addClassCleanup(f)on aTestCaseare dependencies of every reader of the class, as istype("Name", (Base,), {}), which runsBase.__init_subclass__.A class-level container is shared by every instance: a change made through an instance of your class is a dependency of every reader of the class too (
Store._cache,cls._cache), as long as the class or one of your base classes binds something mutable in its body (a class nested in it included:OUTER.Meta.registry.append(x),self.Meta .registry), some code stores onto the class or gives it an attribute outside its body (its module's top-levelConfig.registry = {}, another module,setattr, a decorator or metaclass of yours), or it has a decorator, a metaclass or a library base that may give it state (other thandataclasses.dataclass,functools.total_ordering,typing.finalandabc.ABCMeta;staticmethod(x),classmethod(x)andproperty(x)in its body hold nothing only whenxis a function). The rule for class-level containers holds for an instance a module-level name holds (STORE = Store(),STORE = make_store(), or set by a function underglobal:STORE._cache[k] = v,STORE.cache()[k] = v), and for one a function makes (s = Store(),new = cls.__new__(cls),make_store():s._cache[k] = v,new._items.append(x), ors._itemshanded to a function that changes it). Otherwise a class whose body holds only constants, methods and properties is not affected, nor is an attribute of a new instance that no class body binds and that its methods set to a new object (s.mine.append(x), where only__init__setsself.mine = []). An attribute a method sets to an object that may be shared (a module-level name, a class attribute, a parameter's mutable default:self.items = _ITEMS,self.items = self._shared,def __init__(self, items=[])) is that object: changing it through any instance is a dependency of the object's readers. So is setting an attribute on an instance whose__init__setsself.__dict__to a shared dict (the Borg).A copy is not the object:
cache = dict(_CACHE)or_CACHE.copy(), thencache[k] = v, changes nothing shared. Some copies may be the object, or hold it, and count as it:copy.deepcopy(x)and a pickle round trip (a__deepcopy__or__reduce__may hand back the original, and a class inside is not copied), except a deep copy of a dict, list or set literal or of a module-level name bound to one;x.copy()when a class of yours definescopyor__copy__, andcopy.copy(x)when one defines__copy__,__reduce__or__reduce_ex__; andsum,abs,round,powanddivmod, which may return what they were given. Either way, what the copy holds (a class, an instance, an inner list) is still the original's. Setting an attribute on a new instance (Config().mode = m,new = cls.__new__(cls); new.mode = m) changes that instance only, unless a class in its hierarchy (a base or a subclass) defines its own__new__or derives from a class of an installed package, or the class is decorated or has a metaclass (forcls.__new__(cls), one other thanfunctools.total_ordering,typing.finalorabc.ABCMeta): such an instance may be one kept elsewhere (a singleton), and setting its attribute counts as a change of the class's state. A method changing an attribute its instance owns (self.items.append(x), where__init__setsself.items = []) on an instance no module variable or class holds is not followed as shared state.A module-level constant nothing can change in place has no writers: a name your module binds once, to a string, a number, a tuple of such values,
re.compile(...),textwrap.dedent(...)or a path, and that no code binds again (global,module.NAME = ...,setattr). PassingSQLto a function, or using whatPATTERN.match(s)returns, does not make its readers depend on that code. The same holds for a class attribute your class body binds once to such a value (DAYS = "days",_MONTHS = 12) and that no code binds again: handingTimeDelta.DAYSto a function, orm = min(m, self._MONTHS), writes nothing of the class, and neither does calling a method on an item of a class-level table of strings and numbers that no code changes (self.timeframes[k].format(n)). A class with a decorator (other thanfunctools.total_orderingortyping.final), a metaclass (other thanabc.ABCMeta) or a library base keeps every writer of its attributes.An object you hand to a constructor of your class (
Tokenizer(source, rules=RULES)) is part of the new instance. Changing the instance in place (tok.rules["x"] = 1, calling one of its methods,__init__changing what it stored) changes the object, so it is a dependency of every reader ofRULES. Setting an attribute on the instance (tok.position = 0; not a special attribute such as__dict__), or adding a number or string to one that only ever holds such values (tok.position += 1), in that code or in a function it hands the instance to, is not, as long as no class involved defines__new__,__setattr__or__delattr__(or, for the adding, which reads the attribute first,__getattr__or__getattribute__), binds that name in its body to anything but a constant (a property, another descriptor, a list), or has a decorator (other thanfunctools.total_orderingortyping.final), a metaclass (other thanabc.ABCMeta) or a library base.What one of your functions returns of what it was handed is that object: changing the result in place changes what the caller handed (
r = wrap(p), thenr["items"].append(x), wherewrapreturnsp, part of it,pon one of several returns, or what another function returns of it;b.tag().add(x)wheretagreturnsself), and so does handing the result to a function that changes it. A new object it builds and returns (return {"items": list(p["items"])}) is not what the caller handed: adding to it changes nothing handed.Not followed:
- an object stored away and changed later under another name
(
self.store = store, thenself.store[k] = v), unless the instance holding it was made by calling your class with it, in the function that changes it or hands it on or in a function of yours that returns it (an instance kept in a module variable,TOK = Tokenizer(RULES), is not followed back toRULES); - an object a library function returns that your code then changes
(
typing.cast(T, p)isp); - logging a library does into your handlers from inside its own
calls (
requests.get(...)logging throughurllib3's logger); - your handlers read back through the
logginglibrary (logging.getLogger("x").handlers[0].records,logger.parent): such code is not a reader of what the handler changes; name the handler (CAPTURE.records) instead; - a function stored on one of your classes under another name and
called as a method by your own code (
Cache.get = _fast_get, thenself.get(k)); one stored on alogginglogger, handler, filter or formatter class under a name the library calls back (SLog.handle = _recording_handle) is followed, whether the library or your code calls it (self.handle(record),LOG.handle(record)); - a method called on an item of a module-level dict or list
(
_CACHE["a"].put(4)): only the dict's own methods count as writes; - a library function that changes an argument you pass it, a module of yours included (a library writing into a module you hand it).
- a local name for it:
- Patches in tests.
-
A store on a module, yours or a library's, makes the code storing a dependency of every reader in your code: of a module variable, of that attribute of a library module (
json.x = v, thenjson.xorgetattr(json, "x"); any attribute forvars(json).update(...)), of the environment foros.environ. What a library or a child process reads of it is not followed, and neither is a store onto a module found by name at run time under a name only known then (setattr(sys.modules[name], key, v)) read as a plain attribute (json.x): only code reading a module as a whole or by a computed name (getattr(json, key)) depends on it. A patch undone when the test ends doesn't count:- a method of pytest's
monkeypatchor pytest-mock'smocker, called in the test or in a function-scoped fixture that requests it, unless that module defines its own fixture of the same name; - a
with mock.patch(...)orwith MonkeyPatch.context()block in a function that doesn'tyield; - a
@mock.patch(...)decorator; - a value saved and put back in a test or a function-scoped fixture:
orig = m.X, thenm.X = v, restored in afinally:block or, in a fixture, right after theyield.
Any other patch counts as a store that may outlast the test:
patch(...).start(), a patcher kept for later, aMonkeyPatch()of your own,monkeypatchhanded to a helper function, awith mock.patch(...)around ayieldin a fixture, or amonkeypatchfixture the same module overrides.An override of
monkeypatchormockerin a parentconftest.pyis not seen: diffcone still assumes what a test patches through it is undone when the test ends. - a method of pytest's
- Tests are assumed not to depend on what an earlier test left behind.
-
When code that runs inside one test changes module state (
server._state = make(),os.environ["MODE"] = mode(), or a module put insys.modules), diffcone counts that change for that test only (and for each test using the fixture that makes it), not for other tests that read the same state, with or without a recording; set an environment variable withmonkeypatch.setenv, which undoes it when the test ends. Such code is:- the test itself, and unittest's
setUpandtearDown; - a function-scoped fixture;
- a helper in a test module or
conftest.pythat only such code calls.
A module whose top-level code changes process state (
os.environ,sys.path) runs that code for the whole session, so none of its code counts as such, a test module's tests included.A test or
setUpthat other code calls (a test module's top-level code, a session fixture) is not such code, and neither is a doctest's function. Code that runs once for many tests is a dependency of every test that reads what it changes: a test module's top-level code, a fixture with a wider scope (or a scope it computes), a hook, and any code of your project, a cache it fills included.If a test relies on state an earlier test set up, declare that dependency in
diffcone.toml(an[[edges]]entry from the reader to the code setting it up), or run the whole suite. - the test itself, and unittest's
- Caches with a recording.
-
With a recording, a test that reads a cache an earlier test filled counts as running the code that filled it. Every write counts that the code able to run a change makes, itself or through a function it calls (
_put(key, compute(key))), into a module variable, a class, an object (self._cache[k] = v,self.__dict__[k] = v,setattr(self, k, v),self._table()[k] = v), a closure or a function attribute, whatever it stores: a computed value, a constant, a registration, or a value it stores only on some branch, since what it stores may depend on the change in ways the code doesn't show. So does a result kept by a memoising decorator. An attribute set on an object (self.value = v) or on a class by name (Settings.value = v) is read by the object's or class's own methods and by any code reading.valueoff it (CONF.value,self.settings.value). Code reading the stored state outside the tests counts too: a module that kept a reference to it when imported, or a hook that runs between tests, which selects every test. The one exception is what__init__(or a dataclass's__post_init__) sets on the object it is building: no other test can hold that object yet, unless calling the class can give back an object made earlier (a metaclass, a class decorator or a__new__that keeps one). Callingobj.__init__(),Base.__init__(obj)orsuper().__init__()again on an object in use counts as writing into it.A test that read a file that changed (opened it, or listed its directory when it was added or removed) counts as having filled a cache with it: what the code it ran stores is followed the same way, so a later test served what an earlier one loaded from the file is selected.
A decorator counts as memoising when diffcone knows it (
functools,cachetools, Django's and Werkzeug'scached_property, and others) or its name says so (cached_property,cached,memoize,memoized,cachedmethod), applied with@or by a call (get = cachetools.cached(cache={})(_get)).Not followed:
- a cache kept by an installed package's decorator under another name;
- a cache filled through code diffcone can't follow from the code that
ran the change: a method of an object whose class the code doesn't
tell (
store.put(k, v)withstorepassed in; a module-level instance, a new instance or a local holding one,_STORE.put(k, v),Engine().run(k), are followed, and so are their property setters), a method of an attribute set in several ways (self._cache.set(k, compute(k))), a bound method kept in a variable (put = _STORE.put), an object called like a function (__call__), or a list or table of functions (for cb in _HOOKS: cb(v),_SINKS["a"](k, v)); - a write in a class's
__exit__at the end of awithblock, or in a generator created elsewhere that the code running the change resumes; - a value a test computes and hands to code of your project that keeps
it (
store(compute(2))in the test itself): it counts for that test only, as described above; - source lines Python's
linecacheread for a test (to format a traceback or a warning, or forinspect.getsource) that your code then keeps (self.errors.append(traceback.format_exc())): the test that read them is selected when the file changes, but a later test reading what was kept is not.
If later tests depend on such a cache, declare the dependency in
diffcone.toml(an[[edges]]entry from the code reading the cache to the code filling it), name those tests in an[[always_run]]entry, or plan that change without the recording. - What a recording can't see.
-
The recorder sees what Python code of your project and its tests runs, opens and lists. A plan made from a recording misses what happens out of its sight:
- a file opened by compiled code rather than by Python (a certificate
or key file that
sslhands to OpenSSL, say): a change to it doesn't reach the tests that load it; - a cache on disk (a pickle, an SQLite file, a cache directory) one
test writes and a later one reads: the later test reads the file,
not the code that wrote it; give each test its own directory
(
tmp_path) or clear the cache between tests; - a cache an earlier test filled through
functools.lru_cacheorfunctools.cache: the recorder clears these before each test, so each test records the code that fills them, but a suite that relies on one test seeing another's cached result runs differently while recording; - a program your tests start that is named like a read-only system
query (
git,uname,ps,locale,fc-list) but is a script of yours onPATHoutside the repository (one inside it makes the test always selected): it is taken for the system program and not followed; - tests outside pytest's rootdir: with the rootdir in a subdirectory
(a
pytest.iniinsub/) and tests both under it and elsewhere (pytest sub/tests tests), records can be matched to the wrong tests; add--rootdir=.to the command you record with, or keep every test under the rootdir.
For tests that depend on any of these, use an
[[always_run]]entry, or plan without the recording, which follows the code instead (a change to a file diffcone doesn't read selects every test). - a file opened by compiled code rather than by Python (a certificate
or key file that
- Code that changes the process while pytest collects reaches every test.
- A
conftest.py, a test module or a module they import may set an environment variable, extendsys.pathor configure a library (warnings.filterwarnings,logging.basicConfig) when it's imported. A collection hook may do the same. That can change what any later test sees, so such code is a dependency of every test. Static discovery lists what is recognised. - With a recording, code run while pytest collects a file reaches that file's tests.
- Building parameter ids, an
ids=function andpytest_generate_testsdecide the tests of the file pytest is collecting, so a change there selects that file's tests and whoever reads what the code stored. Code that pytest hands its objects to can also leave something for hooks that act on every test. That is recognised when the code, or what ran it, reads.config,.session,.stashor.pluginmanager, or is a hook other thanpytest_generate_tests, and then every test is selected. Something left on another pytest object (metafunc.function, a node's attributes) for a later hook to act on is not.
Reading files¶
- A file that doesn't parse selects everything.
- Any
.pyfile under your source roots that isn't valid Python 3, or can't be decoded in its declared encoding (UTF-8 unless the file says otherwise), is an analysis error, even a test data file nothing imports. So is one that nests an expression hundreds of levels deep, as generated code may (a sum of a thousand terms). Choose source roots that leave such files out, or list them under[index] excludein diffcone.toml. - An excluded file is a dependency diffcone can't see into.
- diffcone doesn't read a
.pyfile[index] excludekeeps out, so it doesn't know what the file imports or calls. Code that imports or runs one (an import,import_module,runpy, a subprocess, loading it by path) is selected on any change under your source roots, and a change to the excluded file itself selects every test (with a recording, see diffcone.toml). Tests and benchmarks in an excluded file, and the fixtures and hooks of an excludedconftest.pyor plugin, are not discovered. - Uncommitted analysis is only as stable as your working tree.
- A plan of
WORKTREEorINDEXdescribes the files at the moment you planned. The report always marks such plans as uncommitted. - Git-ignored files are seen only by
WORKTREEplans, and only Python ones. -
A plan of a commit or of
INDEXreads what git recorded. A.pyfile git ignores (a generated_version.py, alocal_settings.py) and any edit to it are invisible to it.runrefuses to run such a plan while one is on disk under your source roots, unless it only assigns constants and neither commit has it (a generated_version.py); otherwise plan with--head WORKTREE.A
WORKTREEplan reads ignored.pyfiles in a directory that also holds files git tracks or doesn't ignore. A directory with only ignored files is skipped, as are ignored directories (a virtualenv, a build tree) and ignored files that aren't Python.
Discovery¶
- Discovery reads the source, so it can't see what plugins do.
-
A pytest plugin that collects tests by its own rules, or a test base class outside your source roots, can mean diffcone's target list is incomplete. diffcone reports it and the plan exits with code
3(static discovery). A plugin that collects files just by being installed is invisible to a plan from the code. Wheneverrunstarts pytest, it runs every collected test the plan doesn't know, and a recording captures what pytest really collected.A fixture decorator is recognised under another name only when the module using it binds that name (
from pytest import fixture as fx,fx = pytest.fixture). One imported from another of your modules is not: an autouse fixture under it is not a dependency of the tests it applies to, so a change to it may select none of them. A decorator from an installed package that writes docstrings isn't read either: the doctests it adds are not targets. - Parametrized tests are selected as a whole.
- diffcone selects or skips all of a test's parameter cases together.