Code Monkey home page Code Monkey logo

pytest-odoo's Introduction

pytest-odoo

pytest plugin to run Odoo tests

This lib allows to run the tests built in Odoo addons which are using Python's unittest, but with the comfort of the pytest CLI. Also allowing to run tests without updating given module.

Odoo's --test-enable machinery and pytest-odoo do not cover exactly the same scope. The Odoo's test runner runs the tests during the upgrades of the addons, that's why they need the "at install" and "post install" markers.

Running tests during upgrades of addons is waaay too slow to work efficiently in a TDD mode, that's where pytest-odoo shines. Consider that all the tests are running post-install with pytest-odoo, as you must run the upgrade of the addon before (but only when needed vs each run).

At the end of the day, its beneficial to run the Odoo tests with --test-enable because, as in very rare conditions, a test can pass with pytest-odoo but not with the "at install" tests run during the upgrade (or the oposite). Pytest-odoo can be considered a development tool, but not the tool that should replace entirely --test-enable in a CI.

See also the official Odoo documentation on writing tests.

Usage

install via:

pip install pytest-odoo

usage:

pytest -s --odoo-database=test --odoo-log-level=debug_sql [--odoo-http]

The custom options are:

  • --odoo-database: name of the database to test.
  • --odoo-log-level: log level as expected by odoo. As time of writing: info, debug_rpc, warn, test, critical, debug_sql, error, debug, debug_rpc_answer. The default is critical to have a clean output.
  • --odoo-config: path of the odoo.cfg file to use.
  • --odoo-http: Allow to launch the Odoo http instance

Alternatively, you can use environment variables, like the Odoo Docker image:

  • HOST: hostname of the database server
  • PORT: port of the database server
  • USER: username to access the database
  • PASSWORD: password to access the database

These only work in addition to --odoo-database.

You can use the ODOO_RC environment variable using an odoo configuration file, containing at least the database option with the name of the database to test:

export ODOO_RC=/path/to/odoo/config.cfg
pytest ...

Known issues

Currently not compatible with pytest >= 8.0.0

pytest-odoo's People

Contributors

anikeenko-viktor avatar carelvd avatar florentx avatar guewen avatar lmignon avatar mwegrzynek avatar rousseldenis avatar samsagaz avatar sbidoul avatar simahawk avatar tmotyl avatar unki2aut avatar xtof-osd avatar yvaucher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytest-odoo's Issues

Problem with pytest version 8

Here is the stack-trace i get when trying to run a test with pytest version 8

`

pytest --odoo-database ------ odoo/addons/xxx_mrp_machine_cycle/tests
===================================================================================================================================================================== test session starts ======================================================================================================================================================================
platform linux -- Python 3.11.2, pytest-8.2.0, pluggy-1.5.0
rootdir: ------
configfile: pyproject.toml
plugins: anyio-4.3.0, odoo-1.0.0, cov-4.1.0
collected 0 items / 1 error                                                                                                                                                                                                                                                                                                                                    

============================================================================================================================================================================ ERRORS ============================================================================================================================================================================
______________________________________________________________________________________________________________________________________ ERROR collecting odoo/addons/xxx_mrp_machine_cycle/tests/test_mrp_machine_cycle.py ______________________________________________________________________________________________________________________________________
../../.pyenv/versions/3.11.2/lib/python3.11/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1206: in _gcd_import
    ???
<frozen importlib._bootstrap>:1178: in _find_and_load
    ???
<frozen importlib._bootstrap>:1128: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:241: in _call_with_frames_removed
    ???
<frozen importlib._bootstrap>:1206: in _gcd_import
    ???
<frozen importlib._bootstrap>:1178: in _find_and_load
    ???
<frozen importlib._bootstrap>:1128: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:241: in _call_with_frames_removed
    ???
<frozen importlib._bootstrap>:1206: in _gcd_import
    ???
<frozen importlib._bootstrap>:1178: in _find_and_load
    ???
<frozen importlib._bootstrap>:1149: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:690: in _load_unlocked
    ???
<frozen importlib._bootstrap_external>:940: in exec_module
    ???
<frozen importlib._bootstrap>:241: in _call_with_frames_removed
    ???
odoo/addons/xxx_mrp_machine_cycle/__init__.py:1: in <module>
    from . import models
odoo/addons/xxx_mrp_machine_cycle/models/__init__.py:1: in <module>
    from . import mrp_machine_cycle
odoo/addons/xxx_mrp_machine_cycle/models/mrp_machine_cycle.py:10: in <module>
    class MrpMachineCycle(models.Model):
../../.virtualenvs/odoo----/lib/python3.11/site-packages/odoo/models.py:152: in __new__
    assert module.startswith('odoo.addons.'), \
E   AssertionError: Invalid import of xxx_mrp_machine_cycle.models.mrp_machine_cycle.MrpMachineCycle, it should start with 'odoo.addons'.
=================================================================================================================================================================== short test summary info ====================================================================================================================================================================
ERROR odoo/addons/xxx_mrp_machine_cycle/tests/test_mrp_machine_cycle.py - AssertionError: Invalid import of xxx_mrp_machine_cycle.models.mrp_machine_cycle.MrpMachineCycle, it should start with 'odoo.addons'.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
======================================================================================================================================================================= 1 error in 0.33s =======================================================================================================================================================================

`

when downgrading to pytest version 7 -> it works

@sbidoul

How to use with pytest-xdist?

Hi,

I'd like to use it with pytest-xdist, but get Deadlocks because of simultaneus updates.

As I have my fresh DB (with demo data) ready before calling pytest --
I could automatically copy it for each worker (example like here) .

I can get each worker like this and use it for separate DB naming.

But how then pass those separate db-names to pytest-odoo separate processes?

AttributeError with python 3.8.6 - Wrong import way?

When run pytest with odoo12 and python 3.8.6 i get the following error:

@pytest.fixture(scope='session', autouse=True)
def load_registry():
    # Initialize the registry before running tests.
    # If we don't do that, the modules will be loaded *inside* of the first
    # test we run, which would trigger the launch of the postinstall tests
    # (because we force 'test_enable' to True and the at end of the loading of
    # the registry, the postinstall tests are run when test_enable is enabled).
    # And also give wrong timing indications.
    # Finally we enable `testing` flag on current thread
    # since Odoo sets it when loading test suites.
    threading.currentThread().testing = True
  odoo.registry(odoo.tests.common.get_db_name())

E AttributeError: module 'odoo' has no attribute 'tests'

env/lib/python3.8/site-packages/pytest_odoo.py:88: AttributeError

module import broken

Hi!!

I was developping modules against oldish odoo 15 code (two months maybe). I recently dit a git pull on Odoo code, and I also had to reset my venv packages to match Odoo's requirements.txt, and now all my tests crash with this error:

AssertionError: Invalid import of my_module.models.angle.Angle, it should start with 'odoo.addons'.

To make them work again, I have to modify my modules root __init__.py from this:

from . import models

to this:

from odoo.addons.my_module import models

It seems like _importtestmodule() in pytest_odoo.py is not run anymore and I'm not sure why. Any clue?

AttributeError: module 'odoo' has no attribute 'tools'

What I'm doing:

I have an odoo 15 instance that I run from the source code using .venv virtual environment
After activating the enviroment using source /odoo15/.venv/activate
I ran the command pyhton -m pip install pytest-odoo than I ran

python -m pytest -s --odoo-database=15-demo-2 --odoo-log-level=debug_sql

What I expected:

to see tests output

What I got:

the following error code:

Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/odoo15/.venv/lib/python3.8/site-packages/pytest/__main__.py", line 5, in <module>
    raise SystemExit(pytest.console_main())
  File "/odoo15/.venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main
    code = main()
  File "/odoo15/.venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 164, in main
    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  File "/odoo15/.venv/lib/python3.8/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/odoo15/.venv/lib/python3.8/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/odoo15/.venv/lib/python3.8/site-packages/pluggy/_callers.py", line 60, in _multicall
    return outcome.get_result()
  File "/odoo15/.venv/lib/python3.8/site-packages/pluggy/_result.py", line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File "/odoo15/.venv/lib/python3.8/site-packages/pluggy/_callers.py", line 34, in _multicall
    next(gen)  # first yield
  File "/odoo15/.venv/lib/python3.8/site-packages/pytest_odoo.py", line 58, in pytest_cmdline_main
    odoo.tools.config.parse_config(options)
AttributeError: module 'odoo' has no attribute 'tools'

Filtering test using odoo test tagged - how to avoid running at_install test ?

I'd like to skip test class decorated with the "at_install" odoo test tags while running my test using pytest.

Is there already some way to do so without adding extra line in code source ?

It works properly using Skip decorator @pytest.mark.skip(reason="Do not run at install test using pytest"), I was wondering if there are some plan to provide those tags as pytest marker to be able to filter those tests ?

How to use pytest when Odoo is running from docker container ?

Hello guys,

first i would like to thank you for this awesome tool !
I'm running Odoo from docker container and what i did is the following :

  1. I got inside the container using this command docker exec -ti <my_odoo_container> bash
  2. Then i installed pytest-odoo inside the container pip3 install pytest-odoo
  3. I used this command to run the test pytest -s addons/<my_module>/tests/test_account_move.py --odoo-database=staging_3

But it gives me this error OSError: [Errno 98] Address already in use :
image

Did anyone encounter a similar issue ?

Thanks.

No module named 'odoo'

I don't understand, the script is invoked by pytest, under Python site-packages. How could it ever find Odoo there to import?

Thanks for creating pytest-odoo!

I just wanted to thank you for making this module. It is a god sent! :)

It works very nicely with coverage! We are going to use it with our own addons directories, but we are very motivated to try it in Odoo itself!

Thread testing flag missing

Odoo code base somewhere relies on threading.currentThread().testing = True

They set it here https://github.com/odoo/odoo/blob/11.0/odoo/modules/module.py#L503 and we tried already to simulate it here https://github.com/camptocamp/pytest-odoo/blob/master/pytest_odoo.py#L84

Still, seems to not work as expected.
Use case: partner image default get https://github.com/odoo/odoo/blob/11.0/odoo/addons/base/res/res_partner.py#L282

In this case (our case) we had to create the partner inside the test and not inside test case setup to make it work exactly how it works w/ std odoo tests.

ModuleNotFoundError: No module named 'odoo.addons.tiny_apps'

Hello,

Trying to run a test per module using cmd but getting import errors. any idea?
pytest --odoo-config=/odoo/conf/odoo.cfg --odoo-database=testdb --odoo-log-level=debug --junitxml=junit-report.xml -s /odoo/src/tiny_apps/tiny_apps/purchase_batch_order

odoo@review-develop-3zknud:~$ pytest --odoo-config=/odoo/conf/odoo.cfg --odoo-database=lasgdb --odoo-log-level=debug --junitxml=junit-report.xml -s /odoo/src/tiny_apps/tiny_apps/purchase_batch_order
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: "odoo.http.rpc.request:INFO"
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: "odoo.http.rpc.response:INFO"
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: ":INFO"
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: "odoo:DEBUG"
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: "odoo.sql_db:INFO"
2022-02-28 15:19:29,231 450 DEBUG ? odoo.netsvc: logger level set: "longpolling:WARNING"
2022-02-28 15:19:29,434 450 INFO ? odoo.addons.base.models.ir_actions_report: Will use the Wkhtmltopdf binary at /usr/local/bin/wkhtmltopdf
2022-02-28 15:19:29,438 450 INFO ? odoo.addons.base.models.ir_actions_report: Wkhtmltopdf seems to be broken.
2022-02-28 15:19:29,575 450 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:9069
2022-02-28 15:19:29,576 450 INFO ? odoo.service.server: Stopping gracefully
================================================================================ test session starts =================================================================================
platform linux -- Python 3.7.12, pytest-7.0.1, pluggy-0.13.1
rootdir: /odoo
plugins: cov-3.0.0, odoo-0.7.1
collected 0 items / 1 error

======================================================================================= ERRORS =======================================================================================
______________________________________________ ERROR collecting src/tiny_apps/tiny_apps/purchase_batch_order/tests/test_batch_order.py _______________________________________________
.local/lib/python3.7/site-packages/pytest_odoo.py:140: in _importtestmodule
import(modname)
E ModuleNotFoundError: No module named 'odoo.addons.tiny_apps'
------------------------------------------------------------------ generated xml file: /home/odoo/junit-report.xml -------------------------------------------------------------------
============================================================================== short test summary info ===============================================================================
ERROR ../../odoo/src/tiny_apps/tiny_apps/purchase_batch_order/tests/test_batch_order.py - ModuleNotFoundError: No module named 'odoo.addons.tiny_apps'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
================================================================================== 1 error in 0.20s ==================================================================================

Logs polluted by PIL.PngImagePlugin DEBUG log-level

When using pytest with odoo 11.0, the logs are polluted by DEBUG level logs from Pillow library.

2018-02-20 16:00:37,276 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IHDR' 16 13
2018-02-20 16:00:37,276 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'iCCP' 41 1004
2018-02-20 16:00:37,276 1 DEBUG testdb PIL.PngImagePlugin: iCCP profile name b'icc'
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: Compression method 0
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'bKGD' 1057 6
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: b'bKGD' 1057 6 (unknown)
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'pHYs' 1075 9
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'vpAg' 1096 9
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: b'vpAg' 1096 9 (unknown)
2018-02-20 16:00:37,277 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IDAT' 1117 21141
2018-02-20 16:00:37,285 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IHDR' 16 13
2018-02-20 16:00:37,286 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IDAT' 41 16633
2018-02-20 16:00:37,286 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IHDR' 16 13
2018-02-20 16:00:37,286 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IDAT' 41 16633
2018-02-20 16:00:37,286 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IHDR' 16 13
2018-02-20 16:00:37,286 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IDAT' 41 16633
2018-02-20 16:00:37,293 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IHDR' 16 13
2018-02-20 16:00:37,294 1 DEBUG testdb PIL.PngImagePlugin: STREAM b'IDAT' 41 16633

This happens when a user is created in the setUp() method as res.partner.create() is called with no image in vals dict : https://github.com/odoo/odoo/blob/11.0/odoo/addons/base/res/res_partner.py#L530

I have no idea why these logs appear using pytest while they don't using standard odoo --test-enable
machinery.

PS this could easily be reproduced launching pytest on account module as users are created there.

Since Odoo 15.0, Environment.manage() is useless

When running pytest with Odoo 15, a warning is shown aling with a with a traceback:

021-11-04 12:56:10,193 1533666 WARNING ? py.warnings: /usr/lib/python3.8/contextlib.py:113: DeprecationWarning: Since Odoo 15.0, Environment.manage() is useless.

How to identify the individual test_module name?

For Odoo's unittest, it might identify the individual test_module as following:
python odoo-bin -c /path/to/config.conf -d dbname -u test_module --log-level=test

But, for pytest-odoo, how to identify the individual test_module name?
pytest -s --odoo-database=dbname --odoo-log-level=debug_sql

Thanks

Easy access to ORM Environment?

First of all, thanks for a great pytest plugin.
I wonder if there is an easy way to access to ORM Environment like self.env['res.users'] ....
I have searched in pytest_odoo.py file. But I can't find anything related to the access of ORM Environment.
If it does not have an easy way of accessing ORM Environment right, I guess it should be right in the pytest-odoo. It is mindless to develop an another pytest plugin. It is mindless to copy/paste in every module.
If there is no such thing yet, I am eager to help doing it in the pytest-odoo.

testing non odoo project

I'm getting following trace back using python 3.8.6 while running test for simple python tests files using the same env that I use to develop odoo project (some bdd tests), In the mean time I've create a dedicated venv for my bdd tests

I'll probably spend some times to figure out how to make this smooth and avoid to complaint where pytest-odoo plugin is not required by my unit tests.

../../../.pyenv/versions/3.8.6/envs/jeano386/lib/python3.8/site-packages/pytest_odoo.py:116: in _importtestmodule
    pkgroot = pypkgpath.dirpath()
E   AttributeError: 'NoneType' object has no attribute 'dirpath'

What's missing for feature parity with standard Odoo testing machinery?

This is more a question than an issue, but it could become a feature request if feature parity is feasible.

AFAICS pytest-odoo had a gap to bridge years ago: running tests without installing or updating addons:

pytest-odoo/README.rst

Lines 7 to 13 in 9315331

Also allowing to run tests without updating given module.
Odoo's `--test-enable` machinery and pytest-odoo do not cover exactly the same scope. The Odoo's test runner runs the tests during
the upgrades of the addons, that's why they need the "at install" and "post install" markers.
Running tests during upgrades of addons is waaay too slow to work efficiently in a TDD mode, that's where pytest-odoo shines.
Consider that all the tests are running `post-install` with pytest-odoo, as you must run the upgrade of the addon before (but only when needed vs each run).

Those sentences are no longer true. You can achieve the same with pure Odoo:

  • Run it with --test-file ./addon/tests/test_this.py and it won't install or update, only test.
  • Run it with --test-tags .test_name and only the test with that name will run.

So, we could say that the main goal of pytest-odoo is no longer an issue.

However, it still has the benefits of having the whole pytest ecosystem:

  • It can generate coverage reports easily.
  • It produces nicer output. Extremely nicer.
  • It can produce XML reports.
  • Nice IDE integration for test detection, execution and debugging.
  • Probably more plugins that I'm forgetting right now.

I pushed odoo/odoo#151728 some time ago to address these issues directly in Odoo, but it's clearly doomed for oblivion. So I'd be more than happy to entirely replace odoo testing machinery with pytest-odoo. But then...

Pytest-odoo can be considered a development tool, but not the tool that should replace entirely `--test-enable` in a CI.

Sadness.

People out there seem to ignore this warning. I'd like to ignore it too if possible. But I love my CI too much to feed it with unhealthy food.

So... what's missing to be able to remove that warning from the README? What's exactly the difference between pytest-odoo and odoo --test-enable that makes it not suitable for CI workloads?

IIUC these 2 points:

  1. Lack of subtest support in pytest. This was true when pytest-odoo was born, but nowadays pytest-subtests should cover this. Does it work with Odoo? Has anybody tested it?
  2. Unability to install or update addons, testing them under their canonical conditions.

Is it possible to reach feature parity and then reliably use pytest-odoo on CI workloads, entirely replacing (or wrapping) odoo?

Thanks!

@moduon MT-1075

PyCharm support/usage

I came across this module while trying to do development within PyCharm. I can't seem to get this working properly with their testing interface and I was hoping some one here might have some experience with this or a configuration they are willing to share. I find that PyCharm errors out around :

pypkgpath = self.fspath.pypkgpath()
pkgroot = pypkgpath.dirpath()

Claiming that pypkgpath is None. I suspect that the issue lies with the scope under which PyCharm is executing PyTest-Odoo but haven't resolved how to set this properly.

There is a related question on Stack Overflow that also requires an answer but is not getting any love over here

`ModuleNotFoundError: No module named 'odoo'` error on trying to launch

Hey there. Just like #56 and running my odoo-dev-env.

I try the command : pytest -s --odoo-database=odoo-db and get the following error :

pytest -s --odoo-database=odoo-db
Traceback (most recent call last):
  File "/home/mat/documents/odoo-dev-env/venv/bin/pytest", line 8, in <module>
    sys.exit(console_main())
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 206, in console_main
    code = main()
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 159, in main
    config = _prepareconfig(args, plugins)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 346, in _prepareconfig
    config = pluginmanager.hook.pytest_cmdline_parse(
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_hooks.py", line 513, in __call__
    return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_manager.py", line 120, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_callers.py", line 139, in _multicall
    raise exception.with_traceback(exception.__traceback__)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_callers.py", line 122, in _multicall
    teardown.throw(exception)  # type: ignore[union-attr]
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/helpconfig.py", line 106, in pytest_cmdline_parse
    config = yield
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_callers.py", line 103, in _multicall
    res = hook_impl.function(*args)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 1152, in pytest_cmdline_parse
    self.parse(args)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 1501, in parse
    self._preparse(args, addopts=addopts)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/config/__init__.py", line 1388, in _preparse
    self.pluginmanager.load_setuptools_entrypoints("pytest11")
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pluggy/_manager.py", line 421, in load_setuptools_entrypoints
    plugin = ep.load()
  File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 171, in load
    module = import_module(match.group('module'))
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/_pytest/assertion/rewrite.py", line 178, in exec_module
    exec(co, module.__dict__)
  File "/home/mat/documents/odoo-dev-env/venv/lib/python3.10/site-packages/pytest_odoo.py", line 18, in <module>
    import odoo
ModuleNotFoundError: No module named 'odoo'

Thansk in advance !

Configuration of log handlers

Pytest adds a new --odoo-log-level option which is forwarded as odoo's log level.
By default it uses the critical log level to display the less logs possible. But you can change it when you need more details for debugging a test.

Odoo has 2 options for configuring log levels:

  • --log-level: a global single level (critical, error, info, debug, ...)
  • --log-handler: a refined log level per logger name (':INFO,odoo.http.rpc.request:INFO')

The first one is based on this config:

{'critical': ['odoo:CRITICAL', 'werkzeug:CRITICAL'],
 'debug': ['odoo:DEBUG', 'odoo.sql_db:INFO'],
 'debug_rpc': ['odoo:DEBUG', 'odoo.sql_db:INFO', 'odoo.http.rpc.request:DEBUG'],
 'debug_rpc_answer': ['odoo:DEBUG', 'odoo.sql_db:INFO', 'odoo.http.rpc:DEBUG'],
 'debug_sql': ['odoo.sql_db:DEBUG'],
 'error': ['odoo:ERROR', 'werkzeug:ERROR'],
 'info': [],
 'warn': ['odoo:WARNING', 'werkzeug:WARNING']}

And the second one will be applied after the --log-level, so it overrides it.
The default log handler is :INFO.

The result is that when you use a command such as (both are the same):

pytest -s my_addon/tests --odoo-log-level=critical
# means critical log-level
pytest -s my_addon/tests

The log levels will be:

:INFO
odoo:CRITICAL
werkzeug:CRITICAL

As the log levels are recursive, all the loggers below odoo (odoo.addons.sale, ...) and werkzeug will be on the critical log-level. But all other loggers, such as those used by libs (Pillow, ...) will have an INFO logger by default.

What we should probably do is set a default --log-handler to :CRITICAL and add an option to modify it the same way it's done for the log level.

As a workaround, you can use a configuration file (

or os.environ.get('OPENERP_SERVER')):
) and set the log handler configuration into it.

Now, we observed in #15 that even logs in DEBUG of Pillow (and passlib) were shown, and they should have been hidden as the default is INFO.

The reason is that each test is in a context manager (pytest.logging.catching_logs) which, during the duration of the test, sets the root loglevel to zero (0 is below DEBUG, display everything). Predefined children log levels will not be changed, but others will all show debug logs. (introduced at pytest-dev/pytest#3013)

The context manager: https://github.com/pytest-dev/pytest/blob/5ad1313b8a18fa3862623d2360cbeb39c202b838/_pytest/logging.py#L84-L106

Hopefully, it has been fixed in pytest 3.4.2 (pytest-dev/pytest@8dcd271)

Help me to fix "AttributeError: module 'odoo' has no attribute 'tests'"

First of all, thanks for this pytest plugin.
i want to know if someome know why i cant use it in my machine :/

Im using Odoo12 and Python3.8

test is

class TestBase:
def test_config(self):
assert 1 == 2

error

___________________________________________________________ ERROR at setup of TestBase.test_config ___________________________________________________________

@pytest.fixture(scope='session', autouse=True)
def load_registry():
    # Initialize the registry before running tests.
    # If we don't do that, the modules will be loaded *inside* of the first
    # test we run, which would trigger the launch of the postinstall tests
    # (because we force 'test_enable' to True and the at end of the loading of
    # the registry, the postinstall tests are run when test_enable is enabled).
    # And also give wrong timing indications.
    # Finally we enable `testing` flag on current thread
    # since Odoo sets it when loading test suites.
    threading.currentThread().testing = True
  odoo.registry(odoo.tests.common.get_db_name())

E AttributeError: module 'odoo' has no attribute 'tests'

/home/user/.virtualenvs/odoo/lib/python3.8/site-packages/pytest_odoo.py:89: AttributeError

as you can see im running the instance inside a virtualenv

Support Status

Hi, I'm investigating this wonderful piece of code.

Analyzing this: odoo-dev/odoo@95a131b

My questions are:

  • How far standard odoo module test are supported?
  • Looking at the marked modules, is there a support gap?
  • Isn't ModuleTest necesary in combination with pre and post tests?
  • Where DataTests used for (now deprecated) yaml files (and are therfore not needed here)?

Can't run inside Eclipse

Hey, I'm really glad I found your plugin! And it works flawlessly in a terminal.

Now I'd like to use it with Eclipse's py.test runner. I tried (too) many things and I always end up with this:

============================= test session starts ==============================
platform linux2 -- Python 2.7.12, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- /usr/bin/python
cachedir: .cache
rootdir: /home/xxx/git/odoo, inifile: 
plugins: odoo-0.2.1
collecting ... collected 0 items / 1 errors

==================================== ERRORS ====================================
________ ERROR collecting addons_test/openacademy/tests/test_session.py ________
File "/usr/lib/python2.7/site-packages/pytest_odoo.py", line 84
in _importtestmodule
    __import__(modname)
E   ImportError: No module named openacademy.tests.test_session
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.22 seconds ============================

I have this hierarchy:

odoo
- addons_test
    - openacademy
      - __init__.py
      - models.py
      - tests
        - __init__.py
        - test_session.py

I can run pytest -v in a terminal and it works fine, but not if I do Ctrl+F9 in test_session.py in eclipse.

Any clue?
Thanks :)

Can't Test Controllers

Hi
First of all, thank you for maintaining this module, it really fills the gap on testing.

I've been using module for a while, maybe more than a year, but still couldn't find a "official" solution for controller testing.
Looks like we're telling Odoo server to exit immediately, then move on to other steps. Since there's no Odoo server to make requests to, I can't test my controllers, I have to spin up another server process and make requests to that server. I made some wrappers and helpers to auto-clean resources created on server process, but it's still far away from perfect, let alone I can't access to logs etc.

I assume you're aware of this, but is there a way to solve this, am I missing something?

Add --odoo-load option

For testing some addons, we need to customize the --load option, should be added in

def pytest_addoption(parser):
parser.addoption("--odoo-database",
action="store",
help="Name of the Odoo database to test")
parser.addoption("--odoo-log-level",
action="store",
default='critical',
help="Log-level used by the Odoo process during tests")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.