Static analysis tools in Testing Fundamentals - Build an Automation Script
import unittest import subprocess import os class TestStaticAnalysis(unittest.TestCase): def test_static_analysis_run(self): # Define the command to run the static analysis tool # Example: pylint scanning a Python file named example.py command = ['pylint', 'example.py', '--output-format=text'] # Run the command and capture output result = subprocess.run(command, capture_output=True, text=True) # Assert the command ran successfully (exit code 0 or 1 for pylint warnings) self.assertIn(result.returncode, [0, 1], f"Static analysis failed with code {result.returncode}") # Assert output contains pylint warning or error messages output = result.stdout self.assertTrue(len(output) > 0, "Static analysis output is empty") self.assertIn('warning', output.lower() + 'error', output.lower(), "No warnings or errors found in output") # Optionally, write output to a report file report_path = 'static_analysis_report.txt' with open(report_path, 'w') as f: f.write(output) # Assert report file is created and not empty self.assertTrue(os.path.exists(report_path), "Report file was not created") self.assertTrue(os.path.getsize(report_path) > 0, "Report file is empty") if __name__ == '__main__': unittest.main()
This test script uses Python's unittest framework to automate running a static analysis tool (like pylint) on a source code file named example.py.
We use the subprocess.run function to execute the tool command and capture its output and exit code.
The test asserts that the tool runs successfully by checking the exit code is either 0 (no issues) or 1 (issues found but no crash).
It then checks that the output contains some warnings or errors by looking for keywords in the output text.
The output is saved to a report file, and the test verifies that this file exists and is not empty.
This approach ensures the static analysis tool runs correctly and produces a meaningful report, automating the manual test steps.
Now add data-driven testing to run static analysis on three different source files