You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: guide/getting-started-with-testcontainers-for-python/index.adoc
+29-4Lines changed: 29 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -107,12 +107,37 @@ We will create a PostgreSQL database in a container using Testcontainers and use
107
107
Also, we will delete all the customer records before every test so that our tests will run with a clean database.
108
108
109
109
We are going to use pytest fixtures for implementing the setup and teardown logic.
110
+
A recommended approach to implement the setup and teardown logic is to use https://pytest.org/en/7.4.x/how-to/fixtures.html#yield-fixtures-recommended[yield fixtures].
111
+
112
+
[source,python]
113
+
----
114
+
@pytest.fixture
115
+
def setup():
116
+
# setup code
117
+
yield some_value
118
+
# teardown code
119
+
----
120
+
121
+
However, with this approach, if there is an exception occurred in the setup code, the teardown code will not be executed. So, a better approach is to use https://pytest.org/en/7.4.x/how-to/fixtures.html#adding-finalizers-directly[finalizers] as follows:
122
+
123
+
[source,python]
124
+
----
125
+
@pytest.fixture
126
+
def setup(request):
127
+
# setup code
128
+
129
+
def cleanup():
130
+
# teardown code
131
+
132
+
request.addfinalizer(cleanup)
133
+
return some_value
134
+
----
110
135
111
136
Let's create *tests/test_customers.py* file and implement the fixtures as follows:
0 commit comments