How to patch/mock import?

Viewed 851

I'm writing tests for airflow dag and running into issue mocking/patching the dag.

# dag.py
from airflow.models import Variable

ENVIRONMENT = Variable.get("environment")
# test_dag.py
import dag

class TestDAG(TestCase):
    def test_something(self):
        pass

Because I'm just setting variable outside of function or class, it runs Variable.get() during import. This will be give me a SQLAlchemy error cause it's trying to connect to a db and fetch variable.

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: variable
[SQL: SELECT variable.val AS variable_val, variable.id AS variable_id, variable."key" AS variable_key, variable.is_encrypted AS variable_is_encrypted 
FROM variable 
WHERE variable."key" = ?
 LIMIT ? OFFSET ?]
[parameters: ('environment', 1, 0)]

Is there a way to patch/mock airflow.models.Variable before it's imported?

1 Answers

You'll need to defer importing the file until you can set a Variable value into the test database. A startTestRun method would be the perfect place.

Related