test_style.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. (c) 2017 - Copyright Red Hat Inc
  5. Authors:
  6. Pierre-Yves Chibon <pingou@pingoured.fr>
  7. Tests for flake8 compliance of the code
  8. """
  9. from __future__ import unicode_literals, absolute_import
  10. import os
  11. import subprocess
  12. import sys
  13. import unittest
  14. import six
  15. REPO_PATH = os.path.abspath(
  16. os.path.join(os.path.dirname(__file__), "..", "pagure")
  17. )
  18. TESTS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__)))
  19. class TestStyle(unittest.TestCase):
  20. """This test class contains tests pertaining to code style."""
  21. def test_code_with_flake8(self):
  22. """Enforce PEP-8 compliance on the codebase.
  23. This test runs flake8 on the code, and will fail if it returns a
  24. non-zero exit code.
  25. """
  26. # We ignore E712, which disallows non-identity comparisons with True and False
  27. # We ignore W503, which disallows line break before binary operator
  28. flake8_command = [
  29. sys.executable,
  30. "-m",
  31. "flake8",
  32. "--ignore=E712,W503,E203",
  33. REPO_PATH,
  34. ]
  35. # check if we have an old flake8 or not
  36. import flake8
  37. flake8_v = flake8.__version__.split(".")
  38. for idx, val in enumerate(flake8_v):
  39. try:
  40. val = int(val)
  41. except ValueError:
  42. pass
  43. flake8_v[idx] = val
  44. old_flake = tuple(flake8_v) < (3, 0)
  45. if old_flake:
  46. raise unittest.SkipTest("Flake8 version too old to be useful")
  47. proc = subprocess.Popen(
  48. flake8_command, stdout=subprocess.PIPE, cwd=REPO_PATH
  49. )
  50. print(proc.communicate())
  51. self.assertEqual(proc.returncode, 0)
  52. @unittest.skipIf(
  53. not (six.PY3 and sys.version_info.minor >= 6),
  54. "Black is only available in python 3.6+",
  55. )
  56. def test_code_with_black(self):
  57. """Enforce black compliance on the codebase.
  58. This test runs black on the code, and will fail if it returns a
  59. non-zero exit code.
  60. """
  61. black_command = [
  62. sys.executable,
  63. "-m",
  64. "black",
  65. "-l",
  66. "79",
  67. "--check",
  68. "--diff",
  69. "--exclude",
  70. '"/(\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist)/"',
  71. REPO_PATH,
  72. TESTS_PATH,
  73. ]
  74. proc = subprocess.Popen(
  75. black_command,
  76. stdout=subprocess.PIPE,
  77. stderr=subprocess.PIPE,
  78. cwd=REPO_PATH,
  79. )
  80. stdout, stderr = proc.communicate()
  81. print("stdout: ")
  82. print(stdout.decode("utf-8"))
  83. print("stderr: ")
  84. print(stderr.decode("utf-8"))
  85. self.assertEqual(proc.returncode, 0)
  86. if __name__ == "__main__":
  87. unittest.main(verbosity=2)