Run pytest locally while referencing anvil app client modules

What I’m trying to do:
run pytest locally while referencing anvil app client modules

What I’ve tried and what’s not working:

  1. Created a simple anvil app with a single form and a module. The module (named Core) has a portable class that looks like the following.
import anvil.server

@anvil.server.portable_class
class Asset():
  def __init__(self, pn:str, sn:str):
    self.pn = pn
    self.sn = sn
  1. Created a virtual environment locally and installed pytest and anvil-client
  2. I pulled the code locally and added a tests/ directory to the root of the app.
  3. Added an initial test in the tests/ directory that referenced the class in the module
from client_code.Core import Asset

def test_core():
    a = Asset('pn1234', sn='sn888')
    assert a.pn == 'pn1234'
  1. Run pytest and get the following error:
ERROR collecting tests/test_anvil.py 
ImportError while importing test module 'D:\projects\TestAnvil\tests\test_anvil.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Program Files\Python310\lib\importlib\__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests\test_anvil.py:1: in <module>
    from client_code.Core import Asset
E   ModuleNotFoundError: No module named 'client_code'

I have tried various from/import formats, and sprinkled init.py in various places.

I’m sure I’m missing something simple to get this working

Have you tried cd’ing into the client_code directory and just importing from Core?

1 Like

That, in fact, did work. Thanks!
So as of right now, the tests can live next to the objects.

Is it possible to have the tests live somewhere else? I did try making a tests subdirectory of client_code, but that did not work either

1 Like

You could set the testpaths config option

https://docs.pytest.org/en/7.1.x/reference/reference.html#ini-options-ref

2 Likes