Sobes.tech
Junior — Middle

What methods can be used to verify the correct functioning of written code?

sobes.tech AI

Answer from AI

To ensure the correct functioning of Python code, you can use the following methods:

  • Unit testing: writing tests for individual functions or classes using modules like unittest, pytest, or doctest.
  • Debugging: running the code in debug mode with a built-in debugger (pdb) or an IDE for step-by-step analysis.
  • Logging: adding logs to track the program's state and identify errors.
  • Manual testing: checking the code's operation with different input data.
  • Static code analysis: using tools like flake8, pylint to identify potential errors and style violations.

Example of a simple unit test using unittest:

import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative(self):
        self.assertEqual(add(-1, -1), -2)

if __name__ == '__main__':
    unittest.main()