- The Problem
- Incorrect Method
- Solution #1) Combine Result with Log File
- Solution #2) Two seperate approved files in one test
- Solution #3) Split into Two Tests
We have a function named load_person()
.
We want to verify the logs from this call as well as the person object that is returned.
root INFO
connecting to the database
root INFO
querying a table
root INFO
closing the database
{
"first_name":"Britney",
"last_name": "Spears",
"profession":"Singer"
}
By default, ApprovalTests allows only one verification per test method.
The following will not yield the expected outcome:
def test_load_person_with_logs():
with verify_logging():
verify(load_person())
Here are a couple of solutions (details below):
With this approach, we leverage the logging mechanism to also verify the output.
def test_load_person_logs_and_results():
with verify_logging():
logging.info(f"result = {load_person()}")
This will create a single approved file, combining both the logs and the result:
test_load_person_logs_and_results.approved.txt
root INFO
connecting to the database
root INFO
querying a table
root INFO
closing the database
root INFO
result = {
"first_name":"Britney",
"last_name": "Spears",
"profession":"Singer"
}
This method introduces the .logging
extension to generate two distinct .approved
files.
def test_load_person_logs_and_results_separately():
with verify_logging(options=NamerFactory.with_parameters("logging")):
verify(load_person())
This will create the following files:
test_load_person_logs_and_results_separately.logging.approved.txt
root INFO
connecting to the database
root INFO
querying a table
root INFO
closing the database
and
test_load_person_logs_and_results_separately.approved.txt
{
"first_name":"Britney",
"last_name": "Spears",
"profession":"Singer"
}
This option divides the verification into two distinct tests: one for logs and another for results.
def test_load_person_logs():
with verify_logging():
load_person()
This will create the following file:
test_load_person_logs.approved.txt
root INFO
connecting to the database
root INFO
querying a table
root INFO
closing the database
def test_load_person_results():
verify(load_person())
This will create the following file:
test_load_person_results.approved.txt
{
"first_name":"Britney",
"last_name": "Spears",
"profession":"Singer"
}