|
| 1 | +import subprocess |
| 2 | +import sys |
| 3 | +import unittest |
| 4 | +from typing import Dict, List, Tuple |
| 5 | + |
| 6 | + |
| 7 | +class TomliInstallTestCase(unittest.TestCase): |
| 8 | + def test_correct_tomli_version_installed(self): |
| 9 | + python_major, python_minor = self.__get_current_python_version() |
| 10 | + packages = self.__get_installed_pip_packages() |
| 11 | + tomli_version = packages.get('tomli') |
| 12 | + v1_regex = r'1.[0-9]+.[0-9]+' |
| 13 | + v2_regex = r'2.[0-9]+.[0-9]+' |
| 14 | + |
| 15 | + if python_major == 3 and python_minor == 6: |
| 16 | + self.assertRegex(tomli_version, v1_regex) |
| 17 | + elif python_major == 3 and python_minor >= 7: |
| 18 | + self.assertRegex(tomli_version, v2_regex) |
| 19 | + else: |
| 20 | + self.fail("Executed with invalid Python version") |
| 21 | + |
| 22 | + def __get_current_python_version(self) -> Tuple[int, int]: |
| 23 | + python_version = sys.version_info |
| 24 | + |
| 25 | + return python_version.major, python_version.minor |
| 26 | + |
| 27 | + def __get_installed_pip_packages(self) -> Dict[str, str]: |
| 28 | + cmd = "pip list" |
| 29 | + process = subprocess.Popen( |
| 30 | + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE |
| 31 | + ) |
| 32 | + stdout, _ = process.communicate() |
| 33 | + exit_code = process.returncode |
| 34 | + if exit_code != 0: |
| 35 | + raise RuntimeError( |
| 36 | + 'listing pip packages got a non-zero exit code' |
| 37 | + ) |
| 38 | + |
| 39 | + result = {} |
| 40 | + packages = self.__remove_pip_list_table_header(stdout.splitlines()) |
| 41 | + for package in packages: |
| 42 | + decoded_package = package.decode('utf-8') |
| 43 | + name, version = decoded_package.split() |
| 44 | + result[name] = version |
| 45 | + |
| 46 | + return result |
| 47 | + |
| 48 | + def __remove_pip_list_table_header(self, lines: List[bytes]) -> List[bytes]: |
| 49 | + return lines[2:] |
0 commit comments