| 1 |
import os |
| 2 |
import platform |
| 3 |
import shutil |
| 4 |
import sys |
| 5 |
import tempfile |
| 6 |
from datetime import datetime, timezone |
| 7 |
from unittest import TestCase |
| 8 |
from uuid import uuid4 |
| 9 |
|
| 10 |
import arrow |
| 11 |
|
| 12 |
from qa.shell import RunningCommand, git, gitlint |
| 13 |
from qa.utils import FILE_ENCODING, PLATFORM_IS_WINDOWS, TERMINAL_ENCODING |
| 14 |
|
| 15 |
|
| 16 |
class BaseTestCase(TestCase): |
| 17 |
"""Base class of which all gitlint integration test classes are derived. |
| 18 |
Provides a number of convenience methods.""" |
| 19 |
|
| 20 |
|
| 21 |
maxDiff = None |
| 22 |
tmp_git_repo = None |
| 23 |
|
| 24 |
GITLINT_USE_SH_LIB = os.environ.get("GITLINT_USE_SH_LIB", "[NOT SET]") |
| 25 |
GIT_CONTEXT_ERROR_CODE = 254 |
| 26 |
GITLINT_USAGE_ERROR = 253 |
| 27 |
|
| 28 |
def setUp(self): |
| 29 |
"""Sets up the integration tests by creating a new temporary git repository""" |
| 30 |
self.tmpfiles = [] |
| 31 |
self.tmp_git_repos = [] |
| 32 |
self.tmp_git_repo = self.create_tmp_git_repo() |
| 33 |
|
| 34 |
def tearDown(self): |
| 35 |
|
| 36 |
for tmpfile in self.tmpfiles: |
| 37 |
os.remove(tmpfile) |
| 38 |
for repo in self.tmp_git_repos: |
| 39 |
|
| 40 |
shutil.rmtree(repo, ignore_errors=PLATFORM_IS_WINDOWS) |
| 41 |
|
| 42 |
def assertEqualStdout(self, output, expected): |
| 43 |
self.assertIsInstance(output, RunningCommand) |
| 44 |
output = output.stdout.decode(TERMINAL_ENCODING) |
| 45 |
output = output.replace("\r", "") |
| 46 |
self.assertMultiLineEqual(output, expected) |
| 47 |
|
| 48 |
@staticmethod |
| 49 |
def generate_temp_path(): |
| 50 |
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f") |
| 51 |
return os.path.realpath(f"/tmp/gitlint-test-{timestamp}") |
| 52 |
|
| 53 |
def create_tmp_git_repo(self): |
| 54 |
"""Creates a temporary git repository and returns its directory path""" |
| 55 |
tmp_git_repo = self.generate_temp_path() |
| 56 |
self.tmp_git_repos.append(tmp_git_repo) |
| 57 |
|
| 58 |
git("init", "--initial-branch", "main", tmp_git_repo) |
| 59 |
|
| 60 |
git("config", "user.name", "gitlint-test-user", _cwd=tmp_git_repo) |
| 61 |
git("config", "user.email", "[email protected]", _cwd=tmp_git_repo) |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
git("config", "core.quotePath", "false", _cwd=tmp_git_repo) |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
git("config", "core.precomposeunicode", "true", _cwd=tmp_git_repo) |
| 71 |
|
| 72 |
|
| 73 |
git("config", "commit.cleanup", "verbatim", _cwd=tmp_git_repo) |
| 74 |
|
| 75 |
return tmp_git_repo |
| 76 |
|
| 77 |
@staticmethod |
| 78 |
def create_file(parent_dir, content=None): |
| 79 |
"""Creates a file inside a passed directory. Returns filename.""" |
| 80 |
test_filename = "test-fïle-" + str(uuid4()) |
| 81 |
full_path = os.path.join(parent_dir, test_filename) |
| 82 |
|
| 83 |
if content: |
| 84 |
if isinstance(content, bytes): |
| 85 |
open_kwargs = {"mode": "wb"} |
| 86 |
else: |
| 87 |
open_kwargs = {"mode": "w", "encoding": FILE_ENCODING} |
| 88 |
|
| 89 |
with open(full_path, **open_kwargs) as f: |
| 90 |
f.write(content) |
| 91 |
else: |
| 92 |
open(full_path, "a", encoding=FILE_ENCODING).close() |
| 93 |
|
| 94 |
return test_filename |
| 95 |
|
| 96 |
@staticmethod |
| 97 |
def create_environment(envvars=None): |
| 98 |
"""Creates a copy of the current os.environ and adds/overwrites a given set of variables to it""" |
| 99 |
environment = os.environ.copy() |
| 100 |
if envvars: |
| 101 |
environment.update(envvars) |
| 102 |
return environment |
| 103 |
|
| 104 |
def create_tmp_git_config(self, contents): |
| 105 |
"""Creates an environment with the GIT_CONFIG variable set to a file with the given contents.""" |
| 106 |
tmp_config = self.create_tmpfile(contents) |
| 107 |
return self.create_environment({"GIT_CONFIG": tmp_config}) |
| 108 |
|
| 109 |
def create_simple_commit( |
| 110 |
self, message, *, file_contents=None, out=None, ok_code=None, env=None, git_repo=None, tty_in=False |
| 111 |
): |
| 112 |
"""Creates a simple commit with an empty test file. |
| 113 |
:param message: Commit message for the commit.""" |
| 114 |
|
| 115 |
git_repo = self.tmp_git_repo if git_repo is None else git_repo |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
environment = self.create_environment(env) |
| 122 |
|
| 123 |
|
| 124 |
test_filename = self.create_file(git_repo, file_contents) |
| 125 |
git("add", test_filename, _cwd=git_repo) |
| 126 |
|
| 127 |
if not ok_code: |
| 128 |
ok_code = [0] |
| 129 |
|
| 130 |
git( |
| 131 |
"commit", |
| 132 |
"-m", |
| 133 |
message, |
| 134 |
_cwd=git_repo, |
| 135 |
_err_to_out=True, |
| 136 |
_out=out, |
| 137 |
_tty_in=tty_in, |
| 138 |
_ok_code=ok_code, |
| 139 |
_env=environment, |
| 140 |
) |
| 141 |
return test_filename |
| 142 |
|
| 143 |
def create_tmpfile(self, content): |
| 144 |
"""Utility method to create temp files. These are cleaned at the end of the test""" |
| 145 |
|
| 146 |
tmpfile, tmpfilepath = tempfile.mkstemp() |
| 147 |
self.tmpfiles.append(tmpfilepath) |
| 148 |
|
| 149 |
if isinstance(content, bytes): |
| 150 |
open_kwargs = {"mode": "wb"} |
| 151 |
else: |
| 152 |
open_kwargs = {"mode": "w", "encoding": FILE_ENCODING} |
| 153 |
|
| 154 |
with open(tmpfile, **open_kwargs) as f: |
| 155 |
f.write(content) |
| 156 |
|
| 157 |
return tmpfilepath |
| 158 |
|
| 159 |
@staticmethod |
| 160 |
def get_example_path(filename=""): |
| 161 |
examples_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../examples") |
| 162 |
return os.path.join(examples_dir, filename) |
| 163 |
|
| 164 |
@staticmethod |
| 165 |
def get_sample_path(filename=""): |
| 166 |
samples_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "samples") |
| 167 |
return os.path.join(samples_dir, filename) |
| 168 |
|
| 169 |
def get_last_commit_short_hash(self, git_repo=None): |
| 170 |
git_repo = self.tmp_git_repo if git_repo is None else git_repo |
| 171 |
return git("rev-parse", "--short", "HEAD", _cwd=git_repo, _err_to_out=True).replace("\n", "") |
| 172 |
|
| 173 |
def get_last_commit_hash(self, git_repo=None): |
| 174 |
git_repo = self.tmp_git_repo if git_repo is None else git_repo |
| 175 |
return git("rev-parse", "HEAD", _cwd=git_repo, _err_to_out=True).replace("\n", "") |
| 176 |
|
| 177 |
@staticmethod |
| 178 |
def get_expected(filename="", variable_dict=None): |
| 179 |
"""Utility method to read an 'expected' file and return it as a string. Optionally replace template variables |
| 180 |
specified by variable_dict.""" |
| 181 |
expected_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "expected") |
| 182 |
expected_path = os.path.join(expected_dir, filename) |
| 183 |
|
| 184 |
with open(expected_path, encoding=FILE_ENCODING) as file: |
| 185 |
expected = file.read() |
| 186 |
|
| 187 |
if variable_dict: |
| 188 |
expected = expected.format(**variable_dict) |
| 189 |
return expected |
| 190 |
|
| 191 |
@staticmethod |
| 192 |
def get_system_info_dict(): |
| 193 |
"""Returns a dict with items related to system values logged by `gitlint --debug`""" |
| 194 |
expected_gitlint_version = gitlint("--version").replace("gitlint, version ", "").strip() |
| 195 |
expected_git_version = git("--version").strip() |
| 196 |
return { |
| 197 |
"platform": platform.platform(), |
| 198 |
"python_version": sys.version, |
| 199 |
"git_version": expected_git_version, |
| 200 |
"gitlint_version": expected_gitlint_version, |
| 201 |
"GITLINT_USE_SH_LIB": BaseTestCase.GITLINT_USE_SH_LIB, |
| 202 |
"TERMINAL_ENCODING": TERMINAL_ENCODING, |
| 203 |
"FILE_ENCODING": FILE_ENCODING, |
| 204 |
} |
| 205 |
|
| 206 |
def get_debug_vars_last_commit(self, git_repo=None): |
| 207 |
"""Returns a dict with items related to `gitlint --debug` output for the last commit.""" |
| 208 |
target_repo = git_repo if git_repo else self.tmp_git_repo |
| 209 |
commit_sha = self.get_last_commit_hash(git_repo=target_repo) |
| 210 |
expected_date = git("log", "-1", "--pretty=%ai", _tty_out=False, _cwd=target_repo) |
| 211 |
expected_date = arrow.get(str(expected_date), "YYYY-MM-DD HH:mm:ss Z").format("YYYY-MM-DD HH:mm:ss Z") |
| 212 |
|
| 213 |
expected_kwargs = self.get_system_info_dict() |
| 214 |
expected_kwargs.update({"target": target_repo, "commit_sha": commit_sha, "commit_date": expected_date}) |
| 215 |
return expected_kwargs |