Go to content|Go to the main menu|Go to search

edhouse-CookieGdpr-Policy-s
3203657
2
/en/gdpr/
320650B6A

Back to Blog

TutorialsSQA

Table Diff Using Python

Tech_blog

When testing complex systems, I often reach a state where I need to compare values before and after performing a certain operation. At the same time, I want to print out the complete state of the system and verify that the operation didn't affect anything else. My idea was to have all parameter values printed in a clear table and color-code those that have changed.

For the purposes of this article, I needed a sample application that would resemble my use when testing an electron microscope application. I thought of an API for controlling a digital camera - it's different from a microscope, but there are some lenses here too. And because I'm lazy, I let ChatGPT create such an API for me.

Classic Value Output

A simple printout of parameter values looks as follows. However, with a large number of parameters, such an output can be confusing. You can find the complete sample script here: test1.py

from dslr import DSLRCamera # dummy app
camera1 = DSLRCamera("Canon")
rint('Before:')
print(f'camera1.iso: {camera1.iso}')
...
camera1.iso = 700
...
print('After:')
print(f'camera1.iso: {camera1.iso}')

Table Output

To improve clarity, we can output the data in the form of an ASCII table. We'll use the Python module PrettyTable for this. Its use is simple:

from prettytable import PrettyTable

table = PrettyTable()
table.field_names = ["Column A", "Column B"]
table.add_row(["Value A1", "Value B1"])
table.add_row(["Value A2", "Value B2"])

print(table)

Now we can print a table, and the result is immediately more clear: test2.py

Comparing Values

Now all that's left is to compare both tables and highlight the values that have changed. Since the PrettyTable table is essentially a two-dimensional array, we just need to go through the individual cells of the first table and check if their value differs from the value at the corresponding position in the second table.

for x, row in enumerate(data_before):
    for y, cell in enumerate(row):
        if data_before[x][y] != data_after[x][y]:
            data_after[x][y] = ...

To highlight, we'll use the Colorama module, which will add colors to our output:

print(Fore.GREEN + 'this is green text')

The result is a clear table of changes: test3.py

You can find all the scripts used and the tables_diff() function for comparing tables on our Github.

Share article

Author

Jan Zatloukal

Jan ZatloukalTester and developer with a passion for automation and improving the development process. I am currently working on an electron microscope automation project in Python.

Edhouse newsletter

Get the latest updates from the world of Edhouse – news, events, and current software and hardware trends.

By signing up, you agree to our Privacy Policy.

Thank you! You have successfully subscribed to the newsletter.