2

Is there a way to run a .py at the very beginning besides __init__.py?

My problem is I need to save the current database state before the parsing of the files changes things. Because I have temporary tests variables that change, but if I can store the state before parsing this would be fixed since I can just restore it at the end of the session.

I need to run a .py not just before the actual test session starts but before the other files are parsed.

example:

console> py.test tests/test_example.py
- need it to run here
collecting 0 items
tests/test_example.py
==== test session starts ====
conftest.py runs here

You could say that an __init__.py would be a solution but when there is an __init__.py in the testing directory, pytest runs everything as a module. (instead of running from py._path.pyimport, it runs from __init__.py) This breaks all my tests and imports throughout my whole tests/ directory

So maybe I can crate my own py._path.pyimport, this just doesn't seem to be the safest/correct way. Or is it possible to call an __init__.py and still run from py._path.pyimport after?

SkylerHill-Sky
  • 2,106
  • 2
  • 17
  • 33

1 Answers1

9

You could use pytest's plugin hooks with a conftest.py to do so.

I'm not sure which hook would be best for your case. Probably pytest_configure.

For example, with this in a conftest.py:

def pytest_configure():
    print("Hello World")

you get:

$ py.test
Hello World!
=================== test session starts ====================
platform linux -- Python 3.5.1, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
[..]

collecting 120 items
The Compiler
  • 11,126
  • 4
  • 40
  • 54
  • wouldn't the hooks run after the test session starts? I need it to run during or before initialization – SkylerHill-Sky Jun 09 '16 at 16:34
  • Depends on what initialization you mean, but pytest is heavily based on hooks, e.g. even the test session itself is just a set of (internal) hooks. – The Compiler Jun 09 '16 at 20:09
  • as stated in the question? Initialization meaning at __init__.py at the very beginning of parsing. Way before the test session even starts. hooks can config the test but can only be run once the test session starts, correct? – SkylerHill-Sky Jun 09 '16 at 20:56
  • That's wrong. You can influence things as early as pytest's commandline parsing for example. I'll edit my answer to clarify. – The Compiler Jun 10 '16 at 04:27
  • Oh! sweet thanks. It worked and that was an easy fix – SkylerHill-Sky Jun 15 '16 at 15:42