|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# http://nexb.com and https://github.com/nexB/deltacode/ |
| 4 | +# The DeltaCode software is licensed under the Apache License version 2.0. |
| 5 | +# Data generated with DeltaCode require an acknowledgment. |
| 6 | +# DeltaCode is a trademark of nexB Inc. |
| 7 | +# |
| 8 | +# You may not use this software except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0 |
| 10 | +# Unless required by applicable law or agreed to in writing, software distributed |
| 11 | +# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | +# CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | +# specific language governing permissions and limitations under the License. |
| 14 | +# |
| 15 | +# When you publish or redistribute any data created with DeltaCode or any DeltaCode |
| 16 | +# derivative work, you must accompany this data with the following acknowledgment: |
| 17 | +# |
| 18 | +# Generated with DeltaCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES |
| 19 | +# OR CONDITIONS OF ANY KIND, either express or implied. No content created from |
| 20 | +# DeltaCode should be considered or used as legal advice. Consult an Attorney |
| 21 | +# for any legal advice. |
| 22 | +# DeltaCode is a free and open source software analysis tool from nexB Inc. and others. |
| 23 | +# Visit https://github.com/nexB/deltacode/ for support and download. |
| 24 | +# |
| 25 | + |
| 26 | +from __future__ import absolute_import |
| 27 | +from __future__ import print_function |
| 28 | +from __future__ import division |
| 29 | +from __future__ import unicode_literals |
| 30 | + |
| 31 | +from collections import OrderedDict |
| 32 | + |
| 33 | +import io |
| 34 | +import json |
| 35 | + |
| 36 | +from commoncode.system import on_windows |
| 37 | + |
| 38 | + |
| 39 | +def run_scan_click(options, monkeypatch=None, test_mode=True, expected_rc=0, env=None): |
| 40 | + """ |
| 41 | + Run a scan as a Click-controlled subprocess |
| 42 | + If monkeypatch is provided, a tty with a size (80, 43) is mocked. |
| 43 | + Return a click.testing.Result object. |
| 44 | + """ |
| 45 | + import click |
| 46 | + from click.testing import CliRunner |
| 47 | + from deltacode import cli |
| 48 | + |
| 49 | + options = add_windows_extra_timeout(options) |
| 50 | + |
| 51 | + if monkeypatch: |
| 52 | + monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True) |
| 53 | + monkeypatch.setattr(click , 'get_terminal_size', lambda : (80, 43,)) |
| 54 | + runner = CliRunner() |
| 55 | + |
| 56 | + result = runner.invoke(cli.cli, options, catch_exceptions=False, env=env) |
| 57 | + |
| 58 | + output = result.output |
| 59 | + if result.exit_code != expected_rc: |
| 60 | + opts = get_opts(options) |
| 61 | + error = ''' |
| 62 | +Failure to run: deltacode %(opts)s |
| 63 | +output: |
| 64 | +%(output)s |
| 65 | +''' % locals() |
| 66 | + assert result.exit_code == expected_rc, error |
| 67 | + return result |
| 68 | + |
| 69 | + |
| 70 | +def get_opts(options): |
| 71 | + try: |
| 72 | + return ' '.join(options) |
| 73 | + except: |
| 74 | + try: |
| 75 | + return b' '.join(options) |
| 76 | + except: |
| 77 | + return b' '.join(map(repr, options)) |
| 78 | + |
| 79 | + |
| 80 | +WINDOWS_CI_TIMEOUT = '222.2' |
| 81 | + |
| 82 | + |
| 83 | +def add_windows_extra_timeout(options, timeout=WINDOWS_CI_TIMEOUT): |
| 84 | + """ |
| 85 | + Add a timeout to an options list if on Windows. |
| 86 | + """ |
| 87 | + if on_windows and '--timeout' not in options: |
| 88 | + # somehow the Appevyor windows CI is now much slower and timeouts at 120 secs |
| 89 | + options += ['--timeout', timeout] |
| 90 | + return options |
| 91 | + |
| 92 | + |
| 93 | +def check_json_scan(expected_file, result_file, regen=False, remove_file_date=False, ignore_headers=False): |
| 94 | + """ |
| 95 | + Check the scan `result_file` JSON results against the `expected_file` |
| 96 | + expected JSON results. |
| 97 | +
|
| 98 | + If `regen` is True the expected_file WILL BE overwritten with the new scan |
| 99 | + results from `results_file`. This is convenient for updating tests |
| 100 | + expectations. But use with caution. |
| 101 | +
|
| 102 | + if `remove_file_date` is True, the file.date attribute is removed. |
| 103 | + """ |
| 104 | + results = load_json_result(result_file, remove_file_date) |
| 105 | + if regen: |
| 106 | + with open(expected_file, 'wb') as reg: |
| 107 | + json.dump(results, reg, indent=2, separators=(',', ': ')) |
| 108 | + |
| 109 | + expected = load_json_result(expected_file, remove_file_date) |
| 110 | + |
| 111 | + if ignore_headers: |
| 112 | + results.pop('headers', None) |
| 113 | + expected.pop('headers', None) |
| 114 | + |
| 115 | + # NOTE we redump the JSON as a string for a more efficient display of the |
| 116 | + # failures comparison/diff |
| 117 | + # TODO: remove sort, this should no longer be needed |
| 118 | + expected = json.dumps(expected, indent=2, sort_keys=True, separators=(',', ': ')) |
| 119 | + results = json.dumps(results, indent=2, sort_keys=True, separators=(',', ': ')) |
| 120 | + assert expected == results |
| 121 | + |
| 122 | + |
| 123 | +def load_json_result(location, remove_file_date=False): |
| 124 | + """ |
| 125 | + Load the JSON scan results file at `location` location as UTF-8 JSON. |
| 126 | +
|
| 127 | + To help with test resilience against small changes some attributes are |
| 128 | + removed or streamlined such as the "tool_version" and scan "errors". |
| 129 | +
|
| 130 | + To optionally also remove date attributes from "files" and "headers" |
| 131 | + entries, set the `remove_file_date` argument to True. |
| 132 | + """ |
| 133 | + with io.open(location, encoding='utf-8') as res: |
| 134 | + scan_results = res.read() |
| 135 | + return load_json_result_from_string(scan_results, remove_file_date) |
| 136 | + |
| 137 | + |
| 138 | +def load_json_result_from_string(string, remove_file_date=False): |
| 139 | + """ |
| 140 | + Load the JSON scan results `string` as UTF-8 JSON. |
| 141 | + """ |
| 142 | + scan_results = json.loads(string, object_pairs_hook=OrderedDict) |
| 143 | + # clean new headers attributes |
| 144 | + streamline_headers(scan_results) |
| 145 | + |
| 146 | + scan_results['deltas'].sort(key=lambda x: x['factors'], reverse=False) |
| 147 | + scan_results['deltas'].sort(key=lambda x: x['score'], reverse=True) |
| 148 | + return scan_results |
| 149 | + |
| 150 | + |
| 151 | +def streamline_errors(errors): |
| 152 | + """ |
| 153 | + Modify the `errors` list in place to make it easier to test |
| 154 | + """ |
| 155 | + for i, error in enumerate(errors[:]): |
| 156 | + error_lines = error.splitlines(True) |
| 157 | + if len(error_lines) <= 1: |
| 158 | + continue |
| 159 | + # keep only first and last line |
| 160 | + cleaned_error = ''.join([error_lines[0] + error_lines[-1]]) |
| 161 | + errors[i] = cleaned_error |
| 162 | + |
| 163 | + |
| 164 | +def streamline_headers(headers): |
| 165 | + """ |
| 166 | + Modify the `headers` list of mappings in place to make it easier to test. |
| 167 | + """ |
| 168 | + headers.pop('deltacode_version', None) |
| 169 | + headers.pop('deltacode_options', None) |
| 170 | + streamline_errors(headers['deltacode_errors']) |
0 commit comments