instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
repobee__repobee-235
diff --git a/repobee/apimeta.py b/repobee/apimeta.py index b1b2f7d..5b92c54 100644 --- a/repobee/apimeta.py +++ b/repobee/apimeta.py @@ -35,6 +35,25 @@ MAX_NAME_LENGTH = 100 class APIObject: """Base wrapper class for platform API objects.""" + def __getattribute__(self, name: str): + """If the sought attr is 'implementation', and that attribute is None, + an AttributeError should be raise. This is because there should never + be a case where the caller tries to access a None implementation: if + it's None the caller should now without checking, as only API objects + returned by platform API (i.e. a class deriving from :py:class:`API`) + can have a reasonable value for the implementation attribute. + + In all other cases, proceed as usual in getting the attribute. This + includes the case when ``name == "implementation"``, and the APIObject + does not have that attribute. + """ + attr = object.__getattribute__(self, name) + if attr is None and name == "implementation": + raise AttributeError( + "invalid access to 'implementation': not initialized" + ) + return attr + def _check_name_length(name): """Check that a Team/Repository name does not exceed the maximum GitHub
repobee/repobee
293665ce1ec44fc274806ae7d002bd06bd932c2d
diff --git a/tests/test_apimeta.py b/tests/test_apimeta.py index acb4b9d..a6bb707 100644 --- a/tests/test_apimeta.py +++ b/tests/test_apimeta.py @@ -2,6 +2,8 @@ import pytest from repobee import apimeta from repobee import exception +import collections + def api_methods(): methods = apimeta.methods(apimeta.APISpec.__dict__) @@ -14,47 +16,84 @@ def api_method_ids(): return list(methods.keys()) [email protected]("method", api_methods(), ids=api_method_ids()) -def test_raises_when_unimplemented_method_called(method): - """Test that get_teams method raises NotImplementedError when called if - left undefined. - """ +class TestAPI: + @pytest.mark.parametrize("method", api_methods(), ids=api_method_ids()) + def test_raises_when_unimplemented_method_called(self, method): + """Test that get_teams method raises NotImplementedError when called if + left undefined. + """ + + class API(apimeta.API): + pass - class API(apimeta.API): - pass + name, impl = method + params = apimeta.parameter_names(impl) - name, impl = method - params = apimeta.parameter_names(impl) + with pytest.raises(NotImplementedError): + m = getattr(API, name) + arguments = (None,) * len(params) + m(*arguments) - with pytest.raises(NotImplementedError): - m = getattr(API, name) - arguments = (None,) * len(params) - m(*arguments) + def test_raises_when_method_incorrectly_declared(self): + """``get_teams`` takes only a self argument, so defining it with a + different argument should raise. + """ + with pytest.raises(exception.APIImplementationError): -def test_raises_when_method_incorrectly_declared(): - """``get_teams`` takes only a self argument, so defining it with a - different argument should raise. - """ + class API(apimeta.API): + def get_teams(a): + pass - with pytest.raises(exception.APIImplementationError): + def test_accepts_correctly_defined_method(self): + """API should accept a correctly defined method, and not alter it in any + way. + """ + expected = 42 class API(apimeta.API): - def get_teams(a): + def __init__(self, base_url, token, org_name, user): pass + def get_teams(self): + return expected -def test_accepts_correctly_defined_method(): - """API should accept a correctly defined method, and not alter it in any - way. - """ - expected = 42 + assert API(None, None, None, None).get_teams() == expected - class API(apimeta.API): - def __init__(self, base_url, token, org_name, user): - pass - def get_teams(self): - return expected +class TestAPIObject: + def test_raises_when_accessing_none_implementation(self): + """Any APIObject should raise when the implementation attribute is + accessed, if it is None. + """ + + class APIObj( + apimeta.APIObject, + collections.namedtuple("APIObj", "implementation"), + ): + def __new__(cls): + return super().__new__(cls, implementation=None) + + obj = APIObj() + + with pytest.raises(AttributeError) as exc_info: + obj.implementation + + assert "invalid access to 'implementation': not initialized" in str( + exc_info + ) + + def test_does_not_raise_when_accessing_initialized_implementation(self): + """If implementation is not None, there should be no error on access""" + implementation = 42 + + class APIObj( + apimeta.APIObject, + collections.namedtuple("APIObj", "implementation"), + ): + def __new__(cls): + return super().__new__(cls, implementation=implementation) + + obj = APIObj() - assert API(None, None, None, None).get_teams() == expected + assert obj.implementation == implementation
APIObject should raise when accessing the internal implementation, if it is None As APIObjects are often passed around without the `implementation` attribute being initialized, it would be good if an exception was raised if it is accessed when not initialized. If an APIObject is built from an API platform-specific object, it should _always_ have an initialized `implementation` attribute. If it is not built from an API platform-specific object, then there should never be a reason to access the `implementation` attribute.
0.0
293665ce1ec44fc274806ae7d002bd06bd932c2d
[ "tests/test_apimeta.py::TestAPIObject::test_raises_when_accessing_none_implementation" ]
[ "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[ensure_teams_and_members]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[get_teams]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[create_repos]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[get_repo_urls]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[get_issues]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[open_issue]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[close_issue]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[add_repos_to_review_teams]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[get_review_progress]", "tests/test_apimeta.py::TestAPI::test_raises_when_unimplemented_method_called[delete_teams]", "tests/test_apimeta.py::TestAPI::test_raises_when_method_incorrectly_declared", "tests/test_apimeta.py::TestAPI::test_accepts_correctly_defined_method", "tests/test_apimeta.py::TestAPIObject::test_does_not_raise_when_accessing_initialized_implementation" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-06-03 20:09:33+00:00
mit
5,235
repobee__repobee-328
diff --git a/requirements.txt b/requirements.txt index 05c3420..f1c41ee 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,4 @@ daiquiri pluggy>=0.8.0 pygithub python-gitlab==1.8.0 -repobee-plug==0.8.0 +repobee-plug==0.9.0 diff --git a/setup.py b/setup.py index 7e8c9fd..39587b7 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ required = [ "daiquiri", "pygithub", "colored", - "repobee-plug==0.8.0", + "repobee-plug==0.9.0", "python-gitlab==1.8.0", ] diff --git a/src/_repobee/cli.py b/src/_repobee/cli.py index 43d6979..e43b0b5 100644 --- a/src/_repobee/cli.py +++ b/src/_repobee/cli.py @@ -30,6 +30,7 @@ from _repobee import util from _repobee import exception from _repobee import config from _repobee import constants +from _repobee import formatters try: os.makedirs(str(constants.LOG_DIR), exist_ok=True) @@ -282,6 +283,7 @@ def dispatch_command( ext_commands: A list of active extension commands. """ ext_command_names = [cmd.name for cmd in ext_commands or []] + hook_results = {} if ext_command_names and args.subparser in ext_command_names: ext_cmd = ext_commands[ext_command_names.index(args.subparser)] with _sys_exit_on_expected_error(): @@ -311,7 +313,9 @@ def dispatch_command( command.migrate_repos(args.master_repo_urls, api) elif args.subparser == CLONE_PARSER: with _sys_exit_on_expected_error(): - command.clone_repos(args.master_repo_names, args.students, api) + hook_results = command.clone_repos( + args.master_repo_names, args.students, api + ) elif args.subparser == VERIFY_PARSER: with _sys_exit_on_expected_error(): plug.manager.hook.get_api_class().verify_settings( @@ -364,6 +368,25 @@ def dispatch_command( "This is a bug, please open an issue.".format(args.subparser) ) + if hook_results: + _handle_hook_results( + hook_results=hook_results, filepath=args.hook_results_file + ) + + +def _handle_hook_results(hook_results, filepath): + LOGGER.info(formatters.format_hook_results_output(hook_results)) + if filepath: + LOGGER.warning( + "Storing hook results to file is a beta feature, the file format " + "is not final" + ) + output_file = pathlib.Path(filepath) + util.atomic_write( + plug.result_mapping_to_json(hook_results), output_file + ) + LOGGER.info("Hook results stored to {}".format(filepath)) + def _add_peer_review_parsers(base_parsers, subparsers): assign_parser = subparsers.add_parser( @@ -762,6 +785,13 @@ def _add_subparsers(parser, show_all_opts, ext_commands): parents=[base_parser, base_student_parser, repo_name_parser], formatter_class=_OrderedFormatter, ) + clone.add_argument( + "--hook-results-file", + help="Path to a file to store results from plugin hooks in. The " + "results are stored as JSON, regardless of file extension.", + type=str, + default=None, + ) plug.manager.hook.clone_parser_hook(clone_parser=clone) diff --git a/src/_repobee/command.py b/src/_repobee/command.py index 7b9e50e..ae5b14c 100644 --- a/src/_repobee/command.py +++ b/src/_repobee/command.py @@ -18,7 +18,7 @@ import shutil import os import sys import tempfile -from typing import Iterable, List, Optional, Tuple, Generator +from typing import Iterable, List, Optional, Tuple, Generator, Mapping from colored import bg, fg, style import daiquiri @@ -343,7 +343,7 @@ def close_issue( def clone_repos( master_repo_names: Iterable[str], teams: Iterable[plug.Team], api: plug.API -) -> None: +) -> Mapping[str, List[plug.HookResult]]: """Clone all student repos related to the provided master repos and student teams. @@ -352,6 +352,8 @@ def clone_repos( teams: An iterable of student teams. api: An implementation of :py:class:`repobee_plug.API` used to interface with the platform (e.g. GitHub or GitLab) instance. + Returns: + A mapping from repo name to a list of hook results. """ repo_urls = api.get_repo_urls(master_repo_names, teams=teams) # the reason we first compute the urls and then extract repo names is that @@ -374,8 +376,8 @@ def clone_repos( for plugin in plug.manager.get_plugins(): if "act_on_cloned_repo" in dir(plugin): repo_names = util.generate_repo_names(teams, master_repo_names) - _execute_post_clone_hooks(repo_names, api) - break + return _execute_post_clone_hooks(repo_names, api) + return {} def _clone_repos_no_check(repo_urls, dst_dirpath, api): @@ -400,7 +402,9 @@ def _clone_repos_no_check(repo_urls, dst_dirpath, api): return [repo.name for repo in cloned_repos] -def _execute_post_clone_hooks(repo_names: List[str], api: plug.API): +def _execute_post_clone_hooks( + repo_names: List[str], api: plug.API +) -> Mapping[str, List[plug.HookResult]]: LOGGER.info("Executing post clone hooks on repos") local_repos = [name for name in os.listdir() if name in repo_names] @@ -411,9 +415,8 @@ def _execute_post_clone_hooks(repo_names: List[str], api: plug.API): path=os.path.abspath(repo_name), api=api ) results[repo_name] = res - LOGGER.info(formatters.format_hook_results_output(results)) - LOGGER.info("Post clone hooks done") + return results def migrate_repos(master_repo_urls: Iterable[str], api: plug.API) -> None: diff --git a/src/_repobee/util.py b/src/_repobee/util.py index 9adaa95..e4678f9 100644 --- a/src/_repobee/util.py +++ b/src/_repobee/util.py @@ -9,6 +9,8 @@ import os import sys import pathlib +import shutil +import tempfile from typing import Iterable, Generator, Union, Set from repobee_plug import apimeta @@ -135,3 +137,21 @@ def find_files_by_extension( for file in files: if _ends_with_ext(file, extensions): yield pathlib.Path(cwd) / file + + +def atomic_write(content: str, dst: pathlib.Path) -> None: + """Write the given contents to the destination "atomically". Achieved by + writin in a temporary directory and then moving the file to the + destination. + + Args: + content: The content to write to the new file. + dst: Path to the file. + """ + with tempfile.TemporaryDirectory() as tmpdir: + with tempfile.NamedTemporaryFile( + delete=False, dir=tmpdir, mode="w" + ) as file: + file.write(content) + + shutil.move(file.name, str(dst))
repobee/repobee
84aae39ab1ba012cf942c7b247489276718ddbeb
diff --git a/tests/unit_tests/test_cli.py b/tests/unit_tests/test_cli.py index e25b6db..f20f739 100644 --- a/tests/unit_tests/test_cli.py +++ b/tests/unit_tests/test_cli.py @@ -1,7 +1,7 @@ import os import pathlib import argparse -from unittest.mock import MagicMock +import collections from unittest import mock import pytest @@ -56,12 +56,13 @@ VALID_PARSED_ARGS = dict( author=None, token=TOKEN, num_reviews=1, + hook_results_file=None, ) @pytest.fixture(autouse=True) def api_instance_mock(mocker): - instance_mock = MagicMock(spec=_repobee.ext.github.GitHubAPI) + instance_mock = mock.MagicMock(spec=_repobee.ext.github.GitHubAPI) instance_mock.get_repo_urls.side_effect = lambda repo_names, org_name: [ generate_repo_url(rn, org_name) for rn in repo_names ] @@ -162,9 +163,82 @@ def command_all_raise_mock(command_mock, api_class_mock, request): return command_mock [email protected] +def hook_result_mapping(): + """A hook result mapping for use as a mocked return value to commands that + return hook results (e.g. command.clone_repos). + """ + hook_results = collections.defaultdict(list) + for repo_name, hook_name, status, msg, data in [ + ( + "slarse-task-1", + "junit4", + plug.Status.SUCCESS, + "All tests passed", + {"extra": "data", "arbitrary": {"nesting": "here"}}, + ), + ( + "slarse-task-1", + "javac", + plug.Status.ERROR, + "Some stuff failed", + None, + ), + ( + "glassey-task-2", + "pylint", + plug.Status.WARNING, + "-10/10 code quality", + None, + ), + ]: + hook_results[repo_name].append( + plug.HookResult(hook=hook_name, status=status, msg=msg, data=data) + ) + return dict(hook_results) + + class TestDispatchCommand: """Test the handling of parsed arguments.""" + def test_writes_hook_results_correctly( + self, tmpdir, hook_result_mapping, api_instance_mock + ): + expected_filepath = pathlib.Path(".").resolve() / "results.json" + expected_json = plug.result_mapping_to_json(hook_result_mapping) + args_dict = dict(VALID_PARSED_ARGS) + args_dict["hook_results_file"] = str(expected_filepath) + with mock.patch( + "_repobee.util.atomic_write", autospec=True + ) as write, mock.patch( + "_repobee.command.clone_repos", + autospec=True, + return_value=hook_result_mapping, + ): + args = argparse.Namespace(subparser=cli.CLONE_PARSER, **args_dict) + cli.dispatch_command(args, api_instance_mock) + + write.assert_called_once_with(expected_json, expected_filepath) + + def test_does_not_write_hook_results_if_there_are_none( + self, tmpdir, api_instance_mock + ): + """Test that no file is created if there are no hook results, even if + --hook-results-file is specified. + """ + expected_filepath = pathlib.Path(".").resolve() / "results.json" + args_dict = dict(VALID_PARSED_ARGS) + args_dict["hook_results_file"] = str(expected_filepath) + with mock.patch( + "_repobee.util.atomic_write", autospec=True + ) as write, mock.patch( + "_repobee.command.clone_repos", autospec=True, return_value={} + ): + args = argparse.Namespace(subparser=cli.CLONE_PARSER, **args_dict) + cli.dispatch_command(args, api_instance_mock) + + assert not write.called + def test_raises_on_invalid_subparser_value(self, api_instance_mock): parser = "DOES_NOT_EXIST" args = argparse.Namespace(subparser=parser, **VALID_PARSED_ARGS) @@ -555,7 +629,7 @@ class TestExtensionCommands: """Return a mock callback function for use with an extension command. """ - yield MagicMock( + yield mock.MagicMock( spec=_repobee.ext.configwizard.create_extension_command )
Add arg `--hook-results-file` to store hook results to JSON This is related to #153 The idea is that some plugins report results, and if `--hook-results-file` is specified, these results should be written as JSON to the specified file. Initially, it will be enough to add it to the `clone` parser, but in the end it should probably be an optional base argument.
0.0
84aae39ab1ba012cf942c7b247489276718ddbeb
[ "tests/unit_tests/test_cli.py::TestDispatchCommand::test_does_not_write_hook_results_if_there_are_none" ]
[ "tests/unit_tests/test_cli.py::TestDispatchCommand::test_raises_on_invalid_subparser_value", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[setup]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[update]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[clone]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[migrate]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[open-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[close-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[list-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[verify-settings]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[assign-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[end-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[show-config]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[check-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_setup_student_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_update_student_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_open_issue_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_close_issue_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_migrate_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_clone_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_master_org_name", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[setup]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[update]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[clone]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[migrate]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[open-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[close-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[list-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[verify-settings]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[assign-reviews]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[end-reviews]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[show-config]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[check-reviews]", "tests/unit_tests/test_cli.py::test_create_parser_for_docs", "tests/unit_tests/test_cli.py::TestBaseParsing::test_show_all_opts_true_shows_configured_args", "tests/unit_tests/test_cli.py::TestBaseParsing::test_show_all_opts_false_hides_configured_args", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_org", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_bad_credentials", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_base_url", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[http://some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[ftp://some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_parse_ext_command_that_does_not_require_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_parse_ext_command_that_requires_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_dispatch_ext_command_that_does_not_require_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_dispatch_ext_command_that_requires_api", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[setup-extra_args0]", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[update-extra_args1]", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[open-issues-extra_args2]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--bu]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[-u]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--sf]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[-o]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--mo]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--bu]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-u]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--sf]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-o]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--mo]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[setup]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[update]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[setup]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[update]", "tests/unit_tests/test_cli.py::TestMigrateParser::test_happy_path", "tests/unit_tests/test_cli.py::TestVerifyParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCloneParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[setup-extra_args0]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[update-extra_args1]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[open-issues-extra_args2]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[close-issues-extra_args3]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[verify-settings-extra_args4]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[migrate-extra_args5]", "tests/unit_tests/test_cli.py::TestShowConfigParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[assign-peer-reviews-assign-reviews-sys_args0]", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[purge-peer-review-teams-end-reviews-sys_args1]", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[check-peer-review-progress-check-reviews-sys_args2]" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-14 15:13:56+00:00
mit
5,236
repobee__repobee-330
diff --git a/requirements.txt b/requirements.txt index f1c41ee..684860e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,4 +4,4 @@ daiquiri pluggy>=0.8.0 pygithub python-gitlab==1.8.0 -repobee-plug==0.9.0 +repobee-plug==0.10.0-alpha.1 diff --git a/setup.py b/setup.py index 39587b7..c0760ba 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ required = [ "daiquiri", "pygithub", "colored", - "repobee-plug==0.9.0", + "repobee-plug==0.10.0-alpha.1", "python-gitlab==1.8.0", ] diff --git a/src/_repobee/cli.py b/src/_repobee/cli.py index e43b0b5..96d3499 100644 --- a/src/_repobee/cli.py +++ b/src/_repobee/cli.py @@ -111,6 +111,15 @@ PARSER_NAMES = ( CHECK_REVIEW_PROGRESS_PARSER, ) +HOOK_RESULTS_PARSER = argparse.ArgumentParser(add_help=False) +HOOK_RESULTS_PARSER.add_argument( + "--hook-results-file", + help="Path to a file to store results from plugin hooks in. The " + "results are stored as JSON, regardless of file extension.", + type=str, + default=None, +) + # add any diprecated parsers to this dict on the following form: # @@ -316,6 +325,7 @@ def dispatch_command( hook_results = command.clone_repos( args.master_repo_names, args.students, api ) + LOGGER.info(formatters.format_hook_results_output(hook_results)) elif args.subparser == VERIFY_PARSER: with _sys_exit_on_expected_error(): plug.manager.hook.get_api_class().verify_settings( @@ -327,7 +337,7 @@ def dispatch_command( ) elif args.subparser == LIST_ISSUES_PARSER: with _sys_exit_on_expected_error(): - command.list_issues( + hook_results = command.list_issues( args.master_repo_names, args.students, api, @@ -368,24 +378,20 @@ def dispatch_command( "This is a bug, please open an issue.".format(args.subparser) ) - if hook_results: + if hook_results and args.hook_results_file: _handle_hook_results( hook_results=hook_results, filepath=args.hook_results_file ) def _handle_hook_results(hook_results, filepath): - LOGGER.info(formatters.format_hook_results_output(hook_results)) - if filepath: - LOGGER.warning( - "Storing hook results to file is a beta feature, the file format " - "is not final" - ) - output_file = pathlib.Path(filepath) - util.atomic_write( - plug.result_mapping_to_json(hook_results), output_file - ) - LOGGER.info("Hook results stored to {}".format(filepath)) + LOGGER.warning( + "Storing hook results to file is an alpha feature, the file format " + "is not final" + ) + output_file = pathlib.Path(filepath) + util.atomic_write(plug.result_mapping_to_json(hook_results), output_file) + LOGGER.info("Hook results stored to {}".format(filepath)) def _add_peer_review_parsers(base_parsers, subparsers): @@ -532,7 +538,7 @@ def _add_issue_parsers(base_parsers, subparsers): LIST_ISSUES_PARSER, description="List issues in student repos.", help="List issues in student repos.", - parents=base_parsers, + parents=[*base_parsers, HOOK_RESULTS_PARSER], formatter_class=_OrderedFormatter, ) list_parser.add_argument( @@ -782,16 +788,14 @@ def _add_subparsers(parser, show_all_opts, ext_commands): CLONE_PARSER, help="Clone student repos.", description="Clone student repos asynchronously in bulk.", - parents=[base_parser, base_student_parser, repo_name_parser], + parents=[ + base_parser, + base_student_parser, + repo_name_parser, + HOOK_RESULTS_PARSER, + ], formatter_class=_OrderedFormatter, ) - clone.add_argument( - "--hook-results-file", - help="Path to a file to store results from plugin hooks in. The " - "results are stored as JSON, regardless of file extension.", - type=str, - default=None, - ) plug.manager.hook.clone_parser_hook(clone_parser=clone) diff --git a/src/_repobee/command.py b/src/_repobee/command.py index ae5b14c..f6a9b87 100644 --- a/src/_repobee/command.py +++ b/src/_repobee/command.py @@ -199,11 +199,11 @@ def list_issues( master_repo_names: Iterable[str], teams: Iterable[plug.Team], api: plug.API, - state: str = "open", + state: plug.IssueState = plug.IssueState.OPEN, title_regex: str = "", show_body: bool = False, author: Optional[str] = None, -) -> None: +) -> List[plug.HookResult]: """List all issues in the specified repos. Args: @@ -211,7 +211,7 @@ def list_issues( teams: An iterable of student teams. api: An implementation of :py:class:`repobee_plug.API` used to interface with the platform (e.g. GitHub or GitLab) instance. - state: state of the repo (open or closed). Defaults to 'open'. + state: state of the repo (open or closed). Defaults to open. title_regex: If specified, only issues with titles matching the regex are displayed. Defaults to the empty string (which matches everything). @@ -221,16 +221,67 @@ def list_issues( """ repo_names = util.generate_repo_names(teams, master_repo_names) max_repo_name_length = max(map(len, repo_names)) + issues_per_repo = _get_issue_generator( + repo_names=repo_names, + state=state, + title_regex=title_regex, + author=author, + api=api, + ) - issues_per_repo = api.get_issues(repo_names, state, title_regex) + # _log_repo_issues exhausts the issues_per_repo iterator and + # returns a list with the same information. It's important to + # have issues_per_repo as an iterator as it greatly speeds + # up visual feedback to the user when fetching many issues + pers_issues_per_repo = _log_repo_issues( + issues_per_repo, show_body, max_repo_name_length + 6 + ) - if author: - issues_per_repo = ( - (repo_name, (issue for issue in issues if issue.author == author)) - for repo_name, issues in issues_per_repo + # for writing to JSON + hook_result_mapping = { + repo_name: [ + plug.HookResult( + hook="list-issues", + status=plug.Status.SUCCESS, + msg="Fetched {} issues from {}".format(len(issues), repo_name), + data={issue.number: issue.to_dict() for issue in issues}, + ) + ] + for repo_name, issues in pers_issues_per_repo + } + # meta hook result + hook_result_mapping["list-issues"] = [ + plug.HookResult( + hook="meta", + status=plug.Status.SUCCESS, + msg="Meta info about the list-issues hook results", + data={"state": state.value}, ) + ] + return hook_result_mapping - _log_repo_issues(issues_per_repo, show_body, max_repo_name_length + 6) + +def _get_issue_generator( + repo_names: List[str], + state: plug.IssueState, + title_regex: str, + author: Optional[str], + api: plug.API, +) -> Generator[ + Tuple[str, Generator[Iterable[plug.Issue], None, None]], None, None +]: + issues_per_repo = ( + ( + repo_name, + [ + issue + for issue in issues + if not author or issue.author == author + ], + ) + for repo_name, issues in api.get_issues(repo_names, state, title_regex) + ) + return issues_per_repo def _log_repo_issues( @@ -247,8 +298,10 @@ def _log_repo_issues( start of the line. """ even = True + persistent_issues_per_repo = [] for repo_name, issues in issues_per_repo: issues = list(issues) + persistent_issues_per_repo.append((repo_name, issues)) if not issues: LOGGER.warning("{}: No matching issues".format(repo_name)) @@ -275,6 +328,8 @@ def _log_repo_issues( out += os.linesep * 2 + _limit_line_length(issue.body) LOGGER.info(out) + return persistent_issues_per_repo + def _limit_line_length(s: str, max_line_length: int = 100) -> str: """Return the input string with lines no longer than max_line_length.
repobee/repobee
d4323c801702bd37b000f62426c373b593a5ac8c
diff --git a/tests/unit_tests/test_cli.py b/tests/unit_tests/test_cli.py index f20f739..0d7493f 100644 --- a/tests/unit_tests/test_cli.py +++ b/tests/unit_tests/test_cli.py @@ -201,8 +201,20 @@ def hook_result_mapping(): class TestDispatchCommand: """Test the handling of parsed arguments.""" + @pytest.mark.parametrize( + "parser, command_func", + [ + (cli.CLONE_PARSER, "_repobee.command.clone_repos"), + (cli.LIST_ISSUES_PARSER, "_repobee.command.list_issues"), + ], + ) def test_writes_hook_results_correctly( - self, tmpdir, hook_result_mapping, api_instance_mock + self, + tmpdir, + hook_result_mapping, + api_instance_mock, + parser, + command_func, ): expected_filepath = pathlib.Path(".").resolve() / "results.json" expected_json = plug.result_mapping_to_json(hook_result_mapping) @@ -211,11 +223,9 @@ class TestDispatchCommand: with mock.patch( "_repobee.util.atomic_write", autospec=True ) as write, mock.patch( - "_repobee.command.clone_repos", - autospec=True, - return_value=hook_result_mapping, + command_func, autospec=True, return_value=hook_result_mapping ): - args = argparse.Namespace(subparser=cli.CLONE_PARSER, **args_dict) + args = argparse.Namespace(subparser=parser, **args_dict) cli.dispatch_command(args, api_instance_mock) write.assert_called_once_with(expected_json, expected_filepath)
Make it possible to store list-isses results to JSON Using the `--store-hook-results` argument from #324
0.0
d4323c801702bd37b000f62426c373b593a5ac8c
[ "tests/unit_tests/test_cli.py::TestDispatchCommand::test_writes_hook_results_correctly[list-issues-_repobee.command.list_issues]" ]
[ "tests/unit_tests/test_cli.py::TestDispatchCommand::test_does_not_write_hook_results_if_there_are_none", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_raises_on_invalid_subparser_value", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[setup]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[update]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[clone]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[migrate]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[open-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[close-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[list-issues]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[verify-settings]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[assign-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[end-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[show-config]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[check-reviews]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[end-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock0]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock1]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock2]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock3]", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_setup_student_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_update_student_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_open_issue_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_close_issue_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_migrate_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_clone_repos_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_correct_args", "tests/unit_tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_master_org_name", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[setup]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[update]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[clone]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[migrate]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[open-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[close-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[list-issues]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[verify-settings]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[assign-reviews]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[end-reviews]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[show-config]", "tests/unit_tests/test_cli.py::test_help_calls_add_arguments[check-reviews]", "tests/unit_tests/test_cli.py::test_create_parser_for_docs", "tests/unit_tests/test_cli.py::TestBaseParsing::test_show_all_opts_true_shows_configured_args", "tests/unit_tests/test_cli.py::TestBaseParsing::test_show_all_opts_false_hides_configured_args", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_org", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_bad_credentials", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_base_url", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[setup]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[update]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[http://some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[ftp://some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[some_enterprise_host/api/v3]", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_parse_ext_command_that_does_not_require_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_parse_ext_command_that_requires_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_dispatch_ext_command_that_does_not_require_api", "tests/unit_tests/test_cli.py::TestExtensionCommands::test_dispatch_ext_command_that_requires_api", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_listing_students[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parser_student_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[setup|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[update|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[close-issues|['--mn',", "tests/unit_tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[open-issues|['--mn',", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[setup-extra_args0]", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[update-extra_args1]", "tests/unit_tests/test_cli.py::TestConfig::test_full_config[open-issues-extra_args2]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--bu]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[-u]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--sf]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[-o]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_is_required[--mo]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--bu]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-u]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--sf]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-o]", "tests/unit_tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[--mo]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[setup]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[update]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[setup]", "tests/unit_tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[update]", "tests/unit_tests/test_cli.py::TestMigrateParser::test_happy_path", "tests/unit_tests/test_cli.py::TestVerifyParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCloneParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[setup-extra_args0]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[update-extra_args1]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[open-issues-extra_args2]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[close-issues-extra_args3]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[verify-settings-extra_args4]", "tests/unit_tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[migrate-extra_args5]", "tests/unit_tests/test_cli.py::TestShowConfigParser::test_happy_path", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[assign-peer-reviews-assign-reviews-sys_args0]", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[purge-peer-review-teams-end-reviews-sys_args1]", "tests/unit_tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[check-peer-review-progress-check-reviews-sys_args2]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-16 07:50:08+00:00
mit
5,237
repobee__repobee-371
diff --git a/src/_repobee/ext/github.py b/src/_repobee/ext/github.py index 3bb248f..657a413 100644 --- a/src/_repobee/ext/github.py +++ b/src/_repobee/ext/github.py @@ -129,6 +129,17 @@ class GitHubAPI(plug.API): """ if not user: raise TypeError("argument 'user' must not be empty") + if not ( + base_url == "https://api.github.com" + or base_url.endswith("/api/v3") + ): + raise plug.PlugError( + "invalid base url, should either be https://api.github.com or " + "end with '/api/v3'. See the docs: " + "https://repobee.readthedocs.io/en/stable/" + "getting_started.html#configure-repobee-for-the-target" + "-organization-show-config-and-verify-settings" + ) self._github = github.Github(login_or_token=token, base_url=base_url) self._org_name = org_name self._base_url = base_url
repobee/repobee
f5adada7aa91cfa67735957d606b34d7d14a4118
diff --git a/tests/unit_tests/plugin_tests/test_github.py b/tests/unit_tests/plugin_tests/test_github.py index 959aafc..84ead19 100644 --- a/tests/unit_tests/plugin_tests/test_github.py +++ b/tests/unit_tests/plugin_tests/test_github.py @@ -317,6 +317,32 @@ def api(happy_github, organization, no_teams): return _repobee.ext.github.GitHubAPI(BASE_URL, TOKEN, ORG_NAME, USER) +class TestInit: + def test_raises_on_empty_user_arg(self): + with pytest.raises(TypeError) as exc_info: + _repobee.ext.github.GitHubAPI(BASE_URL, TOKEN, ORG_NAME, "") + + assert "argument 'user' must not be empty" in str(exc_info.value) + + @pytest.mark.parametrize("url", ["https://github.com", constants.HOST_URL]) + def test_raises_when_url_is_bad(self, url): + with pytest.raises(plug.PlugError) as exc_info: + _repobee.ext.github.GitHubAPI(url, TOKEN, ORG_NAME, USER) + + assert ( + "invalid base url, should either be https://api.github.com or " + "end with '/api/v3'" in str(exc_info.value) + ) + + @pytest.mark.parametrize( + "url", ["https://api.github.com", constants.BASE_URL] + ) + def test_accepts_valid_urls(self, url): + api = _repobee.ext.github.GitHubAPI(url, TOKEN, ORG_NAME, USER) + + assert isinstance(api, plug.API) + + class TestEnsureTeamsAndMembers: @staticmethod def assert_teams_equal(actual_teams, expected_teams):
Add a check for GitHub base url Check that the url is either `https://api.github.com`, or that it ends with `/api/v3`. There have been way too many user errors on incorrect urls, and the error messages can be cryptic.
0.0
f5adada7aa91cfa67735957d606b34d7d14a4118
[ "tests/unit_tests/plugin_tests/test_github.py::TestInit::test_raises_when_url_is_bad[https://github.com]", "tests/unit_tests/plugin_tests/test_github.py::TestInit::test_raises_when_url_is_bad[https://some_enterprise_host]" ]
[ "tests/unit_tests/plugin_tests/test_github.py::TestInit::test_raises_on_empty_user_arg", "tests/unit_tests/plugin_tests/test_github.py::TestInit::test_accepts_valid_urls[https://api.github.com]", "tests/unit_tests/plugin_tests/test_github.py::TestInit::test_accepts_valid_urls[https://some_enterprise_host/api/v3]", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_no_previous_teams", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_all_teams_exist_but_without_members", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc0]", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc1]", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc2]", "tests/unit_tests/plugin_tests/test_github.py::TestEnsureTeamsAndMembers::test_running_twice_has_no_ill_effects", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_creates_correct_repos", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_skips_existing_repos", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception0]", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception1]", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception2]", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_returns_all_urls", "tests/unit_tests/plugin_tests/test_github.py::TestCreateRepos::test_create_repos_without_team_id", "tests/unit_tests/plugin_tests/test_github.py::TestGetRepoUrls::test_with_token_and_user", "tests/unit_tests/plugin_tests/test_github.py::TestGetRepoUrls::test_with_students", "tests/unit_tests/plugin_tests/test_github.py::TestOpenIssue::test_on_existing_repos", "tests/unit_tests/plugin_tests/test_github.py::TestOpenIssue::test_on_some_non_existing_repos", "tests/unit_tests/plugin_tests/test_github.py::TestOpenIssue::test_no_crash_when_no_repos_are_found", "tests/unit_tests/plugin_tests/test_github.py::TestCloseIssue::test_closes_correct_issues", "tests/unit_tests/plugin_tests/test_github.py::TestCloseIssue::test_no_crash_if_no_repos_found", "tests/unit_tests/plugin_tests/test_github.py::TestCloseIssue::test_no_crash_if_no_issues_found", "tests/unit_tests/plugin_tests/test_github.py::TestGetIssues::test_get_all_open_issues", "tests/unit_tests/plugin_tests/test_github.py::TestGetIssues::test_get_all_closed_issues", "tests/unit_tests/plugin_tests/test_github.py::TestGetIssues::test_get_issues_when_one_repo_doesnt_exist", "tests/unit_tests/plugin_tests/test_github.py::TestGetIssues::test_get_open_issues_by_regex", "tests/unit_tests/plugin_tests/test_github.py::TestAddReposToReviewTeams::test_with_default_issue", "tests/unit_tests/plugin_tests/test_github.py::TestAddReposToTeams::test_happy_path", "tests/unit_tests/plugin_tests/test_github.py::TestDeleteTeams::test_delete_non_existing_teams_does_not_crash", "tests/unit_tests/plugin_tests/test_github.py::TestDeleteTeams::test_delete_existing_teams", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_happy_path", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_empty_token_raises_bad_credentials", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_user]", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_organization]", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_bad_token_scope_raises", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_not_owner_raises", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_raises_unexpected_exception_on_unexpected_status", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_none_user_raises", "tests/unit_tests/plugin_tests/test_github.py::TestVerifySettings::test_mismatching_user_login_raises", "tests/unit_tests/plugin_tests/test_github.py::TestGetPeerReviewProgress::test_nothing_returns", "tests/unit_tests/plugin_tests/test_github.py::TestGetPeerReviewProgress::test_with_review_teams_but_no_repos" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-09-13 06:36:10+00:00
mit
5,238
repobee__repobee-449
diff --git a/src/_repobee/main.py b/src/_repobee/main.py index 1c9afde..fe9a164 100644 --- a/src/_repobee/main.py +++ b/src/_repobee/main.py @@ -50,9 +50,10 @@ def main(sys_args: List[str]): LOGGER.info("Non-default plugins disabled") plugin.initialize_plugins([constants.DEFAULT_PLUGIN]) else: - plugin_names = plugin.resolve_plugin_names( - parsed_preparser_args.plug, config_file - ) + plugin_names = ( + parsed_preparser_args.plug + or config.get_plugin_names(config_file) + ) or [] # IMPORTANT: the default plugin MUST be loaded last to ensure that # any user-defined plugins override the firstresult hooks plugin.initialize_plugins( @@ -93,6 +94,8 @@ def main(sys_args: List[str]): else: LOGGER.error("{.__class__.__name__}: {}".format(exc, str(exc))) sys.exit(1) + finally: + plugin.unregister_all_plugins() if __name__ == "__main__": diff --git a/src/_repobee/plugin.py b/src/_repobee/plugin.py index 20f8624..ee2d5de 100644 --- a/src/_repobee/plugin.py +++ b/src/_repobee/plugin.py @@ -16,12 +16,11 @@ import types import pathlib import importlib from types import ModuleType -from typing import List, Optional, Iterable, Mapping +from typing import List, Optional, Iterable, Mapping, Union import daiquiri import _repobee -from _repobee import config from _repobee import exception import repobee_plug as plug @@ -90,32 +89,129 @@ def _try_load_module(qualname: str) -> Optional[ModuleType]: return None -def register_plugins(modules: List[ModuleType]) -> None: +def register_plugins(modules: List[ModuleType],) -> List[object]: """Register the namespaces of the provided modules, and any plug.Plugin instances in them. Registers modules in reverse order as they are run in LIFO order. Args: modules: A list of modules. + Returns: + A list of registered modules and and plugin class instances. """ assert all([isinstance(mod, ModuleType) for mod in modules]) + + registered = [] for module in reversed(modules): # reverse because plugins are run LIFO plug.manager.register(module) + registered.append(module) + for value in module.__dict__.values(): if ( isinstance(value, type) and issubclass(value, plug.Plugin) and value != plug.Plugin ): - plug.manager.register(value()) + obj = value() + plug.manager.register(obj) + registered.append(obj) + + return registered + + +def unregister_all_plugins() -> None: + """Unregister all currently registered plugins.""" + for p in plug.manager.get_plugins(): + plug.manager.unregister(p) + + +def try_register_plugin( + plugin_module: ModuleType, *plugin_classes: List[type], +) -> None: + """Attempt to register a plugin module and then immediately unregister it. + + .. important:: + This is a convenience method for sanity checking plugins, and should + only be called in test suites. It's not for production use. + + This convenience method can be used to sanity check plugins by registering + them with RepoBee. If they have incorrectly defined hooks, this will be + discovered only when registering. + + As an example, assume that we have a plugin module with a single (useless) + plugin class in it, like this: + + .. code-block:: python + :caption: useless.py + + import repobee_plug as plug + + class Useless(plug.Plugin): + \"\"\"This plugin does nothing!\"\"\" + + We want to make sure that both the ``useless`` module and the ``Useless`` + plugin class are registered correctly, and for that we can write some + simple code like this. + + .. code-block:: python + :caption: Example test case to check registering + import repobee + # assuming that useless is defined in the external plugin + # repobee_useless + from repobee_useless import useless -def initialize_plugins(plugin_names: List[str] = None): + def test_register_useless_plugin(): + repobee.try_register_plugin(useless, useless.Useless) + + Args: + plugin_module: A plugin module. + plugin_classes: If the plugin contains any plugin classes (i.e. classes + that extend :py:class:`repobee_plug.Plugin`), then these must be + provided here. Otherwise, this option should not be provided. + Raises: + :py:class:`repobee_plug.PlugError` if the module cannot be registered, + or if the contained plugin classes does not match + plugin_classes. + """ + expected_plugin_classes = set(plugin_classes or []) + newly_registered = register_plugins([plugin_module]) + + registered_modules = [ + reg for reg in newly_registered if isinstance(reg, ModuleType) + ] + registered_classes = { + cl.__class__ for cl in newly_registered if cl not in registered_modules + } + + errors = [] + if len(registered_modules) != 1 or registered_modules[0] != plugin_module: + errors.append( + f"Expected only module {plugin_module}, got {registered_modules}" + ) + elif expected_plugin_classes != registered_classes: + errors.append( + f"Expected plugin classes {expected_plugin_classes}, " + f"got {registered_classes}" + ) + + for reg in newly_registered: + plug.manager.unregister(reg) + + if errors: + raise plug.PlugError(errors) + + +def initialize_plugins( + plugin_names: List[str] = None, +) -> List[Union[ModuleType, type]]: """Load and register plugins. Args: plugin_names: An optional list of plugin names that overrides the configuration file's plugins. + Returns: + A list of registered modules and classes. """ registered_plugins = plug.manager.get_plugins() plug_modules = [ @@ -123,23 +219,9 @@ def initialize_plugins(plugin_names: List[str] = None): for p in load_plugin_modules(plugin_names=plugin_names) if p not in registered_plugins ] - register_plugins(plug_modules) + registered = register_plugins(plug_modules) _handle_deprecation() - - -def resolve_plugin_names( - plugin_names: Optional[List[str]], config_file: pathlib.Path, -) -> List[str]: - """Return a list of plugin names to load into RepoBee given a list of - externally specified plugin names, and a path to a configuration file. - - Args: - plugin_names: A list of names of plugins. - config_file: A configuration file. - Returns: - A list of plugin names that should be loaded. - """ - return [*(plugin_names or config.get_plugin_names(config_file) or [])] + return registered def resolve_plugin_version(plugin_module: types.ModuleType,) -> Optional[str]: diff --git a/src/repobee.py b/src/repobee.py index 690885b..f474ba0 100644 --- a/src/repobee.py +++ b/src/repobee.py @@ -1,5 +1,13 @@ import sys -from _repobee import main + +from _repobee.main import main +from _repobee.plugin import unregister_all_plugins, try_register_plugin + +__all__ = [ + main.__name__, + try_register_plugin.__name__, + unregister_all_plugins.__name__, +] if __name__ == "__main__": - main.main(sys.argv) + main(sys.argv)
repobee/repobee
ad936229e3ba3dd8505279f4bbb33408c39e5cf5
diff --git a/tests/unit_tests/repobee/conftest.py b/tests/unit_tests/repobee/conftest.py index ac28544..52c8a11 100644 --- a/tests/unit_tests/repobee/conftest.py +++ b/tests/unit_tests/repobee/conftest.py @@ -7,10 +7,9 @@ import os from unittest.mock import MagicMock import pytest -from repobee_plug import manager - import _repobee.constants import _repobee.config +import _repobee.plugin import constants @@ -64,9 +63,7 @@ def unused_path(): @pytest.fixture(autouse=True) def unregister_plugins(): """All plugins should be unregistered after each function.""" - registered = manager.get_plugins() - for plugin in registered: - manager.unregister(plugin) + _repobee.plugin.unregister_all_plugins() @pytest.fixture(autouse=True) diff --git a/tests/unit_tests/repobee/test_command.py b/tests/unit_tests/repobee/test_command.py index 7a405e9..f5185e8 100644 --- a/tests/unit_tests/repobee/test_command.py +++ b/tests/unit_tests/repobee/test_command.py @@ -535,9 +535,7 @@ class TestCloneRepos: monkeypatch.setattr("_repobee.ext.pylint.act", act_hook_func) _repobee.ext.pylint.act(None, None) - plugin_names = plugin.resolve_plugin_names( - plugin_names=constants.PLUGINS, config_file=unused_path - ) + plugin_names = constants.PLUGINS modules = plugin.load_plugin_modules(plugin_names) plugin.register_plugins(modules) diff --git a/tests/unit_tests/repobee/test_plugin.py b/tests/unit_tests/repobee/test_plugin.py index cbd74cc..2e207f0 100644 --- a/tests/unit_tests/repobee/test_plugin.py +++ b/tests/unit_tests/repobee/test_plugin.py @@ -34,21 +34,6 @@ def unregister_plugins(): plug.manager.unregister(p) -class TestResolvePluginNames: - """Tests for resolve_plugin_names.""" - - def test_plugin_names_override_config_file(self, config_mock, mocker): - """Test that the plugin_names argument override the configuration - file.""" - plugin_names = ["awesome", "the_slarse_plugin", "ric_easter_egg"] - - actual_plugin_names = plugin.resolve_plugin_names( - config_file=str(config_mock), plugin_names=plugin_names - ) - - assert actual_plugin_names == plugin_names - - class TestLoadPluginModules: """Tests for load_plugin_modules.""" @@ -136,6 +121,33 @@ class TestRegisterPlugins: plugin_manager_mock.register.assert_has_calls(expected_calls) +class TestTryRegisterPlugin: + """Tests for try_register_plugin.""" + + def test_modules_unregistered_after_success(self): + plugin.try_register_plugin(pylint) + assert not plug.manager.get_plugins() + + def test_modules_and_classes_unregistered_after_success(self): + plugin.try_register_plugin(javac, javac.JavacCloneHook) + assert not plug.manager.get_plugins() + + def test_does_not_unregister_unrelated_plugins(self): + plug.manager.register(pylint) + plugin.try_register_plugin(javac, javac.JavacCloneHook) + assert pylint in plug.manager.get_plugins() + + def test_modules_unregistered_after_fail(self): + with pytest.raises(plug.PlugError): + plugin.try_register_plugin(pylint, javac.JavacCloneHook) + assert not plug.manager.get_plugins() + + def test_fails_if_classes_not_specified(self): + with pytest.raises(plug.PlugError) as exc_info: + plugin.try_register_plugin(javac) + assert javac.JavacCloneHook.__name__ in str(exc_info.value) + + class TestTasks: """Tests for testing RepoBee tasks."""
RepoBee must expose more functionality to allow for reasonable end-to-end tests of plugins It should reasonably be possible to run RepoBee with a plugin in plugin tests. At the very least, this requires the following: * The main function being publically exposed, or some wrapped version of it. * The register_plugin function being publically exposed * An easy way to unload plugins. This also means that it's important for the main function to _not_ have side effects. In other words, it must unload plugins after being run. Or, perhaps, we should expose another derivative of the main function that runs the "real" main function, and then unloads plugins.
0.0
ad936229e3ba3dd8505279f4bbb33408c39e5cf5
[ "tests/unit_tests/repobee/test_command.py::TestSetupStudentRepos::test_raises_on_clone_failure", "tests/unit_tests/repobee/test_command.py::TestSetupStudentRepos::test_raises_on_duplicate_master_urls", "tests/unit_tests/repobee/test_command.py::TestSetupStudentRepos::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestUpdateStudentRepos::test_raises_on_duplicate_master_urls", "tests/unit_tests/repobee/test_command.py::TestUpdateStudentRepos::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[issue0]", "tests/unit_tests/repobee/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[None]", "tests/unit_tests/repobee/test_command.py::TestUpdateStudentRepos::test_issues_arent_opened_on_exceptions_if_unspeficied", "tests/unit_tests/repobee/test_command.py::TestOpenIssue::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestCloseIssue::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestCloneRepos::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestCloneRepos::test_executes_act_hooks", "tests/unit_tests/repobee/test_command.py::TestCloneRepos::test_executes_clone_tasks", "tests/unit_tests/repobee/test_command.py::TestMigrateRepo::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestListIssues::test_happy_path[slarse-True--IssueState.CLOSED]", "tests/unit_tests/repobee/test_command.py::TestListIssues::test_happy_path[slarse-True-^.*$-IssueState.CLOSED]", "tests/unit_tests/repobee/test_command.py::TestListIssues::test_happy_path[slarse-False--IssueState.CLOSED]", "tests/unit_tests/repobee/test_command.py::TestListIssues::test_happy_path[slarse-False-^.*$-IssueState.CLOSED]", "tests/unit_tests/repobee/test_command.py::test_purge_review_teams", "tests/unit_tests/repobee/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-3]", "tests/unit_tests/repobee/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-4]", "tests/unit_tests/repobee/test_command.py::TestAssignPeerReviewers::test_zero_reviews_raises", "tests/unit_tests/repobee/test_command.py::TestAssignPeerReviewers::test_happy_path", "tests/unit_tests/repobee/test_command.py::TestSetupTask::test_executes_setup_hooks[setup_student_repos]", "tests/unit_tests/repobee/test_command.py::TestSetupTask::test_executes_setup_hooks[update_student_repos]", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_unregistered_after_success", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_and_classes_unregistered_after_success", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_does_not_unregister_unrelated_plugins", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_unregistered_after_fail", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_fails_if_classes_not_specified" ]
[ "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_load_all_bundled_plugins", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_load_no_plugins", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_raises_when_loading_invalid_module", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_module", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_module_with_plugin_class", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_modules_and_classes", "tests/unit_tests/repobee/test_plugin.py::TestTasks::test_tasks_run_on_repo_copies_by_default", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_deprecation_warning_is_emitted_for_deprecated_hook" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-26 12:28:01+00:00
mit
5,239
repobee__repobee-456
diff --git a/src/_repobee/config.py b/src/_repobee/config.py index 1a1b194..59aabe2 100644 --- a/src/_repobee/config.py +++ b/src/_repobee/config.py @@ -11,7 +11,7 @@ Contains the code required for pre-configuring user interfaces. import os import pathlib import configparser -from typing import Union, List, Mapping, Optional +from typing import Union, List, Mapping import daiquiri import repobee_plug as plug @@ -137,21 +137,8 @@ def get_all_tasks() -> List[plug.Task]: return plug.manager.hook.setup_task() + plug.manager.hook.clone_task() -def _fetch_token() -> Optional[str]: - token = os.getenv(constants.TOKEN_ENV) - token_from_old = os.getenv(constants.TOKEN_ENV_OLD) - if token_from_old: - LOGGER.warning( - "The {} environment variable has been deprecated, " - "use {} instead".format( - constants.TOKEN_ENV_OLD, constants.TOKEN_ENV - ) - ) - return token or token_from_old - - def _read_defaults(config_file: pathlib.Path) -> dict: - token = _fetch_token() + token = os.getenv(constants.TOKEN_ENV) if not config_file.is_file(): return {} if not token else dict(token=token) defaults = dict(_read_config(config_file)[constants.DEFAULTS_SECTION_HDR]) diff --git a/src/_repobee/constants.py b/src/_repobee/constants.py index 5a55a27..a174027 100644 --- a/src/_repobee/constants.py +++ b/src/_repobee/constants.py @@ -39,4 +39,3 @@ ORDERED_CONFIGURABLE_ARGS = ( CONFIGURABLE_ARGS = set(ORDERED_CONFIGURABLE_ARGS) TOKEN_ENV = "REPOBEE_TOKEN" -TOKEN_ENV_OLD = "REPOBEE_OAUTH" diff --git a/src/_repobee/main.py b/src/_repobee/main.py index 8b994a6..b51af81 100644 --- a/src/_repobee/main.py +++ b/src/_repobee/main.py @@ -57,7 +57,7 @@ def main(sys_args: List[str]): parsed_preparser_args.plug or config.get_plugin_names(config_file) ) or [] - plugin.initialize_plugins(plugin_names) + plugin.initialize_plugins(plugin_names, allow_filepath=True) config.execute_config_hooks(config_file) ext_commands = plug.manager.hook.create_extension_command() diff --git a/src/_repobee/plugin.py b/src/_repobee/plugin.py index 2fff203..cc3f7ca 100644 --- a/src/_repobee/plugin.py +++ b/src/_repobee/plugin.py @@ -14,6 +14,9 @@ import tempfile import pkgutil import pathlib import importlib +import hashlib +import os +import sys from types import ModuleType from typing import List, Optional, Iterable, Mapping, Union @@ -39,7 +42,9 @@ def _external_plugin_qualname(plugin_name): def load_plugin_modules( - plugin_names: Iterable[str], allow_qualified: bool = False + plugin_names: Iterable[str], + allow_qualified: bool = False, + allow_filepath: bool = False, ) -> List[ModuleType]: """Load the given plugins. Plugins are loaded such that they are executed in the same order that they are specified in the plugin_names list. @@ -56,18 +61,16 @@ def load_plugin_modules( # import nr 2 from repobee_javac import javac - If ``allow_qualified`` is True, an additional import using the provided - plugin names as-is is also attempted. - - .. code-block:: python - # import nr 3 (only if allow_qualified) import javac + # import nr 4 (only if allow_filepath) + # Dynamically import using the name as a filepath + Args: plugin_names: A list of plugin names. - allow_qualified: If True, attempts to import modules using the plugin - names as qualified paths. + allow_qualified: Allow the plugin to be specified by a qualified name. + allow_filepath: Allows the plugin to be specified as a filepath. Returns: a list of loaded modules. """ @@ -79,6 +82,7 @@ def load_plugin_modules( _try_load_module(_plugin_qualname(name)) or _try_load_module(_external_plugin_qualname(name)) or (allow_qualified and _try_load_module(name)) + or (allow_filepath and _try_load_module_from_filepath(name)) ) if not plug_mod: msg = "failed to load plugin module " + name @@ -87,6 +91,30 @@ def load_plugin_modules( return loaded_modules +def _try_load_module_from_filepath(path: str) -> Optional[ModuleType]: + """Try to load a module from the specified filepath. + + Adapted from code by Sebastian Rittau (https://stackoverflow.com/a/67692). + + Args: + path: A path to a Python module. + Returns: + The module if loaded successfully, or None if there was no module at + the path. + """ + package_name = f"_{hashlib.sha1(path.encode(sys.getdefaultencoding()))}" + module_name = pathlib.Path(path).stem + qualname = f"{package_name}.{module_name}" + spec = importlib.util.spec_from_file_location(qualname, path) + if not spec: + return None + + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + return mod + + def _try_load_module(qualname: str) -> Optional[ModuleType]: """Try to load a module. @@ -208,7 +236,9 @@ def try_register_plugin( def initialize_plugins( - plugin_names: List[str] = None, allow_qualified: bool = False, + plugin_names: List[str] = None, + allow_qualified: bool = False, + allow_filepath: bool = False, ) -> List[Union[ModuleType, type]]: """Load and register plugins. @@ -216,18 +246,23 @@ def initialize_plugins( plugin_names: An optional list of plugin names that overrides the configuration file's plugins. allow_qualified: Allows the plugin names to be qualified. + allow_filepath: Allows the plugin to be specified as a filepath. Returns: A list of registered modules and classes. Raises: :py:class:`_repobee.exception.PluginLoadError` """ + if not allow_filepath: + _check_no_filepaths(plugin_names) if not allow_qualified: _check_no_qualified_names(plugin_names) registered_plugins = plug.manager.get_plugins() plug_modules = [ p - for p in load_plugin_modules(plugin_names, allow_qualified) + for p in load_plugin_modules( + plugin_names, allow_qualified, allow_filepath + ) if p not in registered_plugins ] registered = register_plugins(plug_modules) @@ -235,8 +270,20 @@ def initialize_plugins( return registered +def _is_filepath(name: str) -> bool: + return os.pathsep in name or os.path.exists(name) + + +def _check_no_filepaths(names: List[str]): + filepaths = [name for name in names if _is_filepath(name)] + if filepaths: + raise exception.PluginLoadError(f"Filepaths not allowed: {filepaths}") + + def _check_no_qualified_names(names: List[str]): - qualified_names = [name for name in names if "." in name] + qualified_names = [ + name for name in names if "." in name and not _is_filepath(name) + ] if qualified_names: raise exception.PluginLoadError( f"Qualified names not allowed: {qualified_names}" @@ -244,9 +291,18 @@ def _check_no_qualified_names(names: List[str]): def resolve_plugin_version(plugin_module: ModuleType) -> Optional[str]: - """Return the version of the top-level package containing the plugin, or - None if it is not defined. + """Return the version of this plugin. Tries to resolve the version by + first checking if the plugin module itself has a ``__version__`` + attribute, and then the top level package. + + Args: + plugin_module: A plugin module. + Returns: + The version if found, otherwise None. """ + if hasattr(plugin_module, "__version__"): + return plugin_module.__version__ + pkg_name = plugin_module.__package__.split(".")[0] pkg_module = _try_load_module(pkg_name) return (
repobee/repobee
74d7e576978e03e43e3ae0c3639f299a61e8e507
diff --git a/tests/unit_tests/repobee/conftest.py b/tests/unit_tests/repobee/conftest.py index 8d004ed..5b8d481 100644 --- a/tests/unit_tests/repobee/conftest.py +++ b/tests/unit_tests/repobee/conftest.py @@ -21,7 +21,6 @@ import _repobee # noqa: E402 EXPECTED_ENV_VARIABLES = [ _repobee.constants.TOKEN_ENV, - _repobee.constants.TOKEN_ENV_OLD, "REPOBEE_NO_VERIFY_SSL", ] diff --git a/tests/unit_tests/repobee/test_config.py b/tests/unit_tests/repobee/test_config.py index 7466b82..7e88fa5 100644 --- a/tests/unit_tests/repobee/test_config.py +++ b/tests/unit_tests/repobee/test_config.py @@ -55,23 +55,6 @@ class TestGetConfiguredDefaults: defaults = config.get_configured_defaults(str(config_mock)) assert defaults["token"] == constants.TOKEN - @pytest.mark.skipif( - "_repobee.__version__ >= '3.0.0'", - msg="Old token should have been removed", - ) - def test_deprecated_token_env(self, config_mock, mock_getenv): - token = "superdupertoken" - - def _env(name): - if name == _repobee.constants.TOKEN_ENV_OLD: - return token - return None - - mock_getenv.side_effect = _env - - defaults = config.get_configured_defaults(str(config_mock)) - assert defaults["token"] == token - def test_get_configured_defaults_raises_on_invalid_keys( self, empty_config_mock, students_file ): diff --git a/tests/unit_tests/repobee/test_main.py b/tests/unit_tests/repobee/test_main.py index 5056633..fcbabc0 100644 --- a/tests/unit_tests/repobee/test_main.py +++ b/tests/unit_tests/repobee/test_main.py @@ -57,7 +57,7 @@ def api_instance_mock(mocker): @pytest.fixture def init_plugins_mock(mocker): - def init_plugins(plugs=None, allow_qualified=False): + def init_plugins(plugs=None, allow_qualified=False, allow_filepath=False): list(map(module, plugs or [])) return mocker.patch( @@ -159,7 +159,7 @@ def test_plugins_args( init_plugins_mock.assert_has_calls( [ - call(["javac", "pylint"]), + call(["javac", "pylint"], allow_filepath=True), call(DEFAULT_PLUGIN_NAMES, allow_qualified=True), ], any_order=True, @@ -223,7 +223,7 @@ def test_configured_plugins_are_loaded( init_plugins_mock.assert_has_calls( [ - call(["javac", "pylint"]), + call(["javac", "pylint"], allow_filepath=True), call(DEFAULT_PLUGIN_NAMES, allow_qualified=True), ], any_order=True, @@ -245,7 +245,7 @@ def test_plugin_with_subparser_name( init_plugins_mock.assert_has_calls( [ - call(["javac", "clone"]), + call(["javac", "clone"], allow_filepath=True), call(DEFAULT_PLUGIN_NAMES, allow_qualified=True), ], any_order=True, @@ -287,7 +287,10 @@ def test_invalid_plug_options(dispatch_command_mock, init_plugins_mock): main.main(sys_args) init_plugins_mock.assert_has_calls( - [call(["javac"]), call(DEFAULT_PLUGIN_NAMES, allow_qualified=True)], + [ + call(["javac"], allow_filepath=True), + call(DEFAULT_PLUGIN_NAMES, allow_qualified=True), + ], any_order=True, ) assert not dispatch_command_mock.called diff --git a/tests/unit_tests/repobee/test_plugin.py b/tests/unit_tests/repobee/test_plugin.py index 3a2f2ba..9656ae2 100644 --- a/tests/unit_tests/repobee/test_plugin.py +++ b/tests/unit_tests/repobee/test_plugin.py @@ -6,6 +6,7 @@ installed any other plugins, tests in here may fail unexpectedly without anything actually being wrong. """ +import shutil import pathlib import tempfile import types @@ -246,3 +247,39 @@ class TestInitializePlugins: plugin.initialize_plugins([qualname]) assert "Qualified names not allowed" in str(exc_info.value) + + def test_raises_on_filepath_by_default(self, tmpdir): + plugin_file = pathlib.Path(str(tmpdir)) / "pylint.py" + shutil.copy(_repobee.ext.javac.__file__, str(plugin_file)) + + with pytest.raises(exception.PluginLoadError) as exc_info: + plugin.initialize_plugins([str(plugin_file)]) + + assert "Filepaths not allowed" in str(exc_info.value) + + def test_initialize_from_filepath_filepath(self, tmpdir): + """Test initializing a plugin that's specified by a filepath.""" + plugin_file = pathlib.Path(str(tmpdir)) / "pylint.py" + shutil.copy(_repobee.ext.pylint.__file__, str(plugin_file)) + + initialized_plugins = plugin.initialize_plugins( + [str(plugin_file)], allow_filepath=True + ) + + assert len(initialized_plugins) == 1 + assert initialized_plugins[0].__file__ == str(plugin_file) + + def test_raises_when_filepath_is_not_python_module(self, tmpdir): + not_a_python_module = pathlib.Path(str(tmpdir)) / "some_file.txt" + not_a_python_module.write_text( + "This is definitely\nnot a Python module" + ) + + with pytest.raises(exception.PluginLoadError) as exc_info: + plugin.initialize_plugins( + [str(not_a_python_module)], allow_filepath=True + ) + + assert f"failed to load plugin module {not_a_python_module}" in str( + exc_info.value + )
Make it possible to write a local single-file plugin In theory, there's nothing stopping us from supporting local single-file plugins, as it's super easy to load a module given its filepath. These files also wouldn't need to follow any form of convention (other than defining hook implementations). Just as an example, imagine I have written the `javac.py` plugin and it's located at `/home/slarse/javac.py`. Then, I run RepoBee like so: ``` $ repobee --plug /home/slarse/javac.py clone ... ``` Making this work is extremely easy: when loading plugins, just check if the plugin specified is a local file. It will massively lower the bar for creating plugins.
0.0
74d7e576978e03e43e3ae0c3639f299a61e8e507
[ "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_no_config_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_empty_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_token_in_env_variable_overrides_configuration_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_raises_on_invalid_keys", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_raises_on_missing_header", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_well_formed_config", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_invalid_defaults_key_raises", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_valid_but_malformed_default_args_raises", "tests/unit_tests/repobee/test_main.py::test_plugins_args", "tests/unit_tests/repobee/test_main.py::test_configured_plugins_are_loaded", "tests/unit_tests/repobee/test_main.py::test_plugin_with_subparser_name", "tests/unit_tests/repobee/test_main.py::test_invalid_plug_options", "tests/unit_tests/repobee/test_main.py::test_show_config_custom_config", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_raises_on_filepath_by_default", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_initialize_from_filepath_filepath", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_raises_when_filepath_is_not_python_module" ]
[ "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_reads_full_config", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_full_config", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac,pylint-expected_plugins0]", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac,", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac-expected_plugins2]", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[-expected_plugins3]", "tests/unit_tests/repobee/test_config.py::TestExecuteConfigHooks::test_with_no_config_file", "tests/unit_tests/repobee/test_config.py::TestExecuteConfigHooks::test_with_config_file", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_well_formed_plugin_options", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_no_config_file_raises", "tests/unit_tests/repobee/test_main.py::test_happy_path", "tests/unit_tests/repobee/test_main.py::test_exit_status_1_on_exception_in_parsing", "tests/unit_tests/repobee/test_main.py::test_exit_status_1_on_exception_in_handling_parsed_args", "tests/unit_tests/repobee/test_main.py::test_no_plugins_arg", "tests/unit_tests/repobee/test_main.py::test_no_plugins_with_configured_plugins", "tests/unit_tests/repobee/test_main.py::test_plug_arg_incompatible_with_no_plugins", "tests/unit_tests/repobee/test_main.py::test_does_not_raise_on_exception_in_dispatch", "tests/unit_tests/repobee/test_main.py::test_logs_traceback_on_exception_in_dispatch_if_traceback", "tests/unit_tests/repobee/test_main.py::test_show_all_opts_correctly_separated", "tests/unit_tests/repobee/test_main.py::test_non_zero_exit_status_on_exception", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_load_default_plugins", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_load_bundled_plugins", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_load_no_plugins", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_raises_when_loading_invalid_module", "tests/unit_tests/repobee/test_plugin.py::TestLoadPluginModules::test_raises_when_loading_default_plugins_without_allow_qualified", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_module", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_module_with_plugin_class", "tests/unit_tests/repobee/test_plugin.py::TestRegisterPlugins::test_register_modules_and_classes", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_unregistered_after_success", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_and_classes_unregistered_after_success", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_does_not_unregister_unrelated_plugins", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_modules_unregistered_after_fail", "tests/unit_tests/repobee/test_plugin.py::TestTryRegisterPlugin::test_fails_if_classes_not_specified", "tests/unit_tests/repobee/test_plugin.py::TestTasks::test_tasks_run_on_repo_copies_by_default", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_deprecation_warning_is_emitted_for_deprecated_hook", "tests/unit_tests/repobee/test_plugin.py::TestInitializePlugins::test_raises_on_qualified_names_by_default" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-07 14:50:38+00:00
mit
5,240
repobee__repobee-457
diff --git a/src/_repobee/config.py b/src/_repobee/config.py index 1a1b194..59aabe2 100644 --- a/src/_repobee/config.py +++ b/src/_repobee/config.py @@ -11,7 +11,7 @@ Contains the code required for pre-configuring user interfaces. import os import pathlib import configparser -from typing import Union, List, Mapping, Optional +from typing import Union, List, Mapping import daiquiri import repobee_plug as plug @@ -137,21 +137,8 @@ def get_all_tasks() -> List[plug.Task]: return plug.manager.hook.setup_task() + plug.manager.hook.clone_task() -def _fetch_token() -> Optional[str]: - token = os.getenv(constants.TOKEN_ENV) - token_from_old = os.getenv(constants.TOKEN_ENV_OLD) - if token_from_old: - LOGGER.warning( - "The {} environment variable has been deprecated, " - "use {} instead".format( - constants.TOKEN_ENV_OLD, constants.TOKEN_ENV - ) - ) - return token or token_from_old - - def _read_defaults(config_file: pathlib.Path) -> dict: - token = _fetch_token() + token = os.getenv(constants.TOKEN_ENV) if not config_file.is_file(): return {} if not token else dict(token=token) defaults = dict(_read_config(config_file)[constants.DEFAULTS_SECTION_HDR]) diff --git a/src/_repobee/constants.py b/src/_repobee/constants.py index 5a55a27..a174027 100644 --- a/src/_repobee/constants.py +++ b/src/_repobee/constants.py @@ -39,4 +39,3 @@ ORDERED_CONFIGURABLE_ARGS = ( CONFIGURABLE_ARGS = set(ORDERED_CONFIGURABLE_ARGS) TOKEN_ENV = "REPOBEE_TOKEN" -TOKEN_ENV_OLD = "REPOBEE_OAUTH"
repobee/repobee
74d7e576978e03e43e3ae0c3639f299a61e8e507
diff --git a/tests/unit_tests/repobee/conftest.py b/tests/unit_tests/repobee/conftest.py index 8d004ed..5b8d481 100644 --- a/tests/unit_tests/repobee/conftest.py +++ b/tests/unit_tests/repobee/conftest.py @@ -21,7 +21,6 @@ import _repobee # noqa: E402 EXPECTED_ENV_VARIABLES = [ _repobee.constants.TOKEN_ENV, - _repobee.constants.TOKEN_ENV_OLD, "REPOBEE_NO_VERIFY_SSL", ] diff --git a/tests/unit_tests/repobee/test_config.py b/tests/unit_tests/repobee/test_config.py index 7466b82..7e88fa5 100644 --- a/tests/unit_tests/repobee/test_config.py +++ b/tests/unit_tests/repobee/test_config.py @@ -55,23 +55,6 @@ class TestGetConfiguredDefaults: defaults = config.get_configured_defaults(str(config_mock)) assert defaults["token"] == constants.TOKEN - @pytest.mark.skipif( - "_repobee.__version__ >= '3.0.0'", - msg="Old token should have been removed", - ) - def test_deprecated_token_env(self, config_mock, mock_getenv): - token = "superdupertoken" - - def _env(name): - if name == _repobee.constants.TOKEN_ENV_OLD: - return token - return None - - mock_getenv.side_effect = _env - - defaults = config.get_configured_defaults(str(config_mock)) - assert defaults["token"] == token - def test_get_configured_defaults_raises_on_invalid_keys( self, empty_config_mock, students_file ):
Remove REPOBEE_OAUTH environment variable It has been deprecated for a long time now, since it was replaced with `REPOBEE_TOKEN`
0.0
74d7e576978e03e43e3ae0c3639f299a61e8e507
[ "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_no_config_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_empty_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_token_in_env_variable_overrides_configuration_file", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_raises_on_invalid_keys", "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_raises_on_missing_header", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_well_formed_config", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_invalid_defaults_key_raises", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_valid_but_malformed_default_args_raises" ]
[ "tests/unit_tests/repobee/test_config.py::TestGetConfiguredDefaults::test_get_configured_defaults_reads_full_config", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_full_config", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac,pylint-expected_plugins0]", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac,", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[javac-expected_plugins2]", "tests/unit_tests/repobee/test_config.py::TestGetPluginNames::test_with_only_plugins[-expected_plugins3]", "tests/unit_tests/repobee/test_config.py::TestExecuteConfigHooks::test_with_no_config_file", "tests/unit_tests/repobee/test_config.py::TestExecuteConfigHooks::test_with_config_file", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_well_formed_plugin_options", "tests/unit_tests/repobee/test_config.py::TestCheckConfigIntegrity::test_with_no_config_file_raises" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-07-07 15:04:01+00:00
mit
5,241
repobee__repobee-509
diff --git a/src/repobee_plug/_pluginmeta.py b/src/repobee_plug/_pluginmeta.py index 01981c8..ae12f8f 100644 --- a/src/repobee_plug/_pluginmeta.py +++ b/src/repobee_plug/_pluginmeta.py @@ -2,7 +2,7 @@ import argparse import daiquiri import functools -from typing import List, Tuple, Callable, Mapping, Any +from typing import List, Tuple, Callable, Mapping, Any, Union from repobee_plug import _exceptions from repobee_plug import _corehooks @@ -90,14 +90,17 @@ class _PluginMeta(type): } -def _extract_cli_options(attrdict) -> List[Tuple[str, cli.Option]]: +def _extract_cli_options( + attrdict, +) -> List[Tuple[str, Union[cli.Option, cli.Positional]]]: """Return any members that are CLI options as a list of tuples on the form - (member_name, option). + (member_name, option). Other types of CLI arguments, such as positionals, + are converted to :py:class:`~cli.Option`s. """ return [ (key, value) for key, value in attrdict.items() - if isinstance(value, cli.Option) + if isinstance(value, (cli.Option, cli.Positional)) ] @@ -127,7 +130,9 @@ def _attach_options(config, show_all_opts, parser, plugin: "Plugin"): opts = _extract_cli_options(plugin.__class__.__dict__) for (name, opt) in opts: configured_value = config_section.get(name) - if configured_value and not opt.configurable: + if configured_value and not ( + hasattr(opt, "configurable") and opt.configurable + ): raise _exceptions.PlugError( f"Plugin '{plugin.plugin_name}' does not allow " f"'{name}' to be configured" @@ -168,7 +173,7 @@ def _generate_command_func(attrdict: Mapping[str, Any]) -> Callable: def _add_option( name: str, - opt: cli.Option, + opt: Union[cli.Positional, cli.Option], configured_value: str, show_all_opts: bool, parser: argparse.ArgumentParser, @@ -177,26 +182,32 @@ def _add_option( args = [] kwargs = opt.argparse_kwargs or {} - if opt.short_name: - args.append(opt.short_name) + if opt.converter: + kwargs["type"] = opt.converter - if opt.long_name: - args.append(opt.long_name) - else: - args.append(f"--{name.replace('_', '-')}") - - kwargs["type"] = opt.converter - # configured value takes precedence over default - kwargs["default"] = configured_value or opt.default - kwargs["dest"] = name - # required opts become not required if configured - kwargs["required"] = not configured_value and opt.required kwargs["help"] = ( argparse.SUPPRESS if (configured_value and not show_all_opts) else opt.help or "" ) + if isinstance(opt, cli.Option): + if opt.short_name: + args.append(opt.short_name) + + if opt.long_name: + args.append(opt.long_name) + else: + args.append(f"--{name.replace('_', '-')}") + + kwargs["dest"] = name + # configured value takes precedence over default + kwargs["default"] = configured_value or opt.default + # required opts become not required if configured + kwargs["required"] = not configured_value and opt.required + elif isinstance(opt, cli.Positional): + args.append(name) + parser.add_argument(*args, **kwargs) diff --git a/src/repobee_plug/cli.py b/src/repobee_plug/cli.py index 2359850..6192fa7 100644 --- a/src/repobee_plug/cli.py +++ b/src/repobee_plug/cli.py @@ -19,6 +19,11 @@ Option = collections.namedtuple( ) Option.__new__.__defaults__ = (None,) * len(Option._fields) +Positional = collections.namedtuple( + "Positional", ["help", "converter", "argparse_kwargs"] +) +Positional.__new__.__defaults__ = (None,) * len(Positional._fields) + class CommandExtension: """Mixin class for use with the Plugin class. Marks the extending class as
repobee/repobee
cbfc528f133d099530a7ad51975843226c4336b8
diff --git a/tests/unit_tests/repobee_plug/test_pluginmeta.py b/tests/unit_tests/repobee_plug/test_pluginmeta.py index 6f5afea..475b693 100644 --- a/tests/unit_tests/repobee_plug/test_pluginmeta.py +++ b/tests/unit_tests/repobee_plug/test_pluginmeta.py @@ -267,6 +267,25 @@ class TestDeclarativeExtensionCommand: assert short_opt_args.name == name assert long_opt_args.name == name + def test_positional_arguments(self): + class Greeting(plug.Plugin, plug.cli.Command): + name = plug.cli.Positional() + age = plug.cli.Positional(converter=int) + + def command_callback(self, args, api): + pass + + ext_cmd = Greeting("g").create_extension_command() + parser = argparse.ArgumentParser() + ext_cmd.parser(config={}, show_all_opts=False, parser=parser) + + name = "Alice" + age = 33 + parsed_args = parser.parse_args(f"{name} {age}".split()) + + assert parsed_args.name == name + assert parsed_args.age == age + class TestDeclarativeCommandExtension: """Test creating command extensions to existing commands."""
Add positional arguments to declarative extension commands We need to add positional arguments to the declarative extension commands. It could look like this: ```python # command.py import repobee_plug as plug class Greeting(plug.Plugin, plug.cli.Command): name = plug.cli.Positional() def command_callback(self, args, api): print(args.name) ``` And can be called like so: ``` $ repobee -p command.py greeting Simon Simon ```
0.0
cbfc528f133d099530a7ad51975843226c4336b8
[ "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_positional_arguments" ]
[ "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestPluginInheritance::test_raises_on_non_hook_public_method", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestPluginInheritance::test_happy_path", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestPluginInheritance::test_with_private_methods", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_defaults", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_with_metadata", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_generated_parser", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_configuration", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_raises_when_non_configurable_value_is_configured", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_override_opt_names", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_add_required_option_to_config_show", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_raises_when_command_and_command_extension_are_subclassed_together" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-22 13:10:59+00:00
mit
5,242
repobee__repobee-516
diff --git a/src/_repobee/cli/mainparser.py b/src/_repobee/cli/mainparser.py index 7e2c255..16d7f61 100644 --- a/src/_repobee/cli/mainparser.py +++ b/src/_repobee/cli/mainparser.py @@ -635,7 +635,7 @@ def _add_extension_parsers( parents.append(repo_name_parser) def _add_ext_parser( - parents: List[argparse.ArgumentParser], + name=None, parents: List[argparse.ArgumentParser] = None ) -> argparse.ArgumentParser: """Add a new parser either to the extension command's category (if specified), or to the top level subparsers (if category is not @@ -644,24 +644,48 @@ def _add_extension_parsers( return ( parsers_mapping.get(cmd.category) or subparsers ).add_parser( - cmd.name, + name or cmd.name, help=cmd.help, description=cmd.description, parents=parents, formatter_class=_OrderedFormatter, ) - if cmd.name in plug.cli.CoreCommand: + category = ( + cmd.name.category + if isinstance(cmd.name, plug.cli.Action) + else cmd.category + ) + if category and category not in parsers_mapping: + # new category + category_cmd = subparsers.add_parser( + category.name, + help=category.help, + description=category.description, + ) + category_parsers = category_cmd.add_subparsers(dest=ACTION) + category_parsers.required = True + parsers_mapping[category] = category_parsers + + if cmd.name in parsers_mapping: ext_parser = parsers_mapping[cmd.name] cmd.parser( config=parsed_config, show_all_opts=show_all_opts, parser=ext_parser, ) + elif isinstance(cmd.name, plug.cli.Action): + action = cmd.name + ext_parser = _add_ext_parser(parents=parents, name=action.name) + cmd.parser( + config=parsed_config, + show_all_opts=show_all_opts, + parser=ext_parser, + ) elif callable(cmd.parser): action = cmd.category.get(cmd.name) if cmd.category else None ext_parser = parsers_mapping.get(action) or _add_ext_parser( - parents + parents=parents ) cmd.parser( config=parsed_config, @@ -670,7 +694,7 @@ def _add_extension_parsers( ) else: parents.append(cmd.parser) - ext_parser = _add_ext_parser(parents) + ext_parser = _add_ext_parser(parents=parents) try: _add_traceback_arg(ext_parser) diff --git a/src/_repobee/main.py b/src/_repobee/main.py index d423e27..431acda 100644 --- a/src/_repobee/main.py +++ b/src/_repobee/main.py @@ -102,7 +102,7 @@ def run( parsed_args, api, ext_commands = _parse_args( cmd, config_file, show_all_opts ) - _repobee.cli.dispatch.dispatch_command( + return _repobee.cli.dispatch.dispatch_command( parsed_args, api, config_file, ext_commands ) finally: diff --git a/src/repobee_plug/_pluginmeta.py b/src/repobee_plug/_pluginmeta.py index a74cf78..c686161 100644 --- a/src/repobee_plug/_pluginmeta.py +++ b/src/repobee_plug/_pluginmeta.py @@ -160,7 +160,7 @@ def _generate_command_func(attrdict: Mapping[str, Any]) -> Callable: return _containers.ExtensionCommand( parser=functools.partial(_attach_options, plugin=self), - name=settings.action_name + name=settings.action or self.__class__.__name__.lower().replace("_", "-"), help=settings.help, description=settings.description, diff --git a/src/repobee_plug/cli.py b/src/repobee_plug/cli.py index eb3e7d2..4c2180c 100644 --- a/src/repobee_plug/cli.py +++ b/src/repobee_plug/cli.py @@ -3,7 +3,17 @@ import abc import collections import enum import itertools -from typing import List, Tuple, Optional, Set, Mapping, Iterable, Any, Callable +from typing import ( + List, + Tuple, + Optional, + Set, + Mapping, + Iterable, + Any, + Callable, + Union, +) from repobee_plug import _containers @@ -49,7 +59,7 @@ _Option.__new__.__defaults__ = (None,) * len(_Option._fields) _CommandSettings = collections.namedtuple( "_CommandSettings", [ - "action_name", + "action", "category", "help", "description", @@ -66,7 +76,7 @@ _CommandExtensionSettings = collections.namedtuple( def command_settings( - action_name: Optional[str] = None, + action: Optional[Union[str, "Action"]] = None, category: Optional["CoreCommand"] = None, help: str = "", description: str = "", @@ -100,10 +110,13 @@ def command_settings( Hello, world! Args: - action_name: The name of the action that the command will be - available under. Defaults to the name of the plugin class. + action: The name of this command, or a :py:class:`Action` object that + defines both category and action for the command. Defaults to the + name of the plugin class. category: The category to place this command in. If not specified, - then the command will be top-level (i.e. uncategorized). + then the command will be top-level (i.e. uncategorized). If + ``action`` is an :py:class:`Action` (as opposed to a ``str``), + then this argument is not allowed. help: A help section for the command. This appears when listing the help section of the command's category. description: A help section for the command. This appears when @@ -114,9 +127,19 @@ def command_settings( config_section_name: The name of the configuration section the command should look for configurable options in. Defaults to the name of the plugin the command is defined in. + Returns: + A settings object used internally by RepoBee. """ + if isinstance(action, Action): + if category: + raise TypeError( + "argument 'category' not allowed when argument 'action' is an " + "Action object" + ) + category = action.category + return _CommandSettings( - action_name=action_name, + action=action, category=category, help=help, description=description, @@ -126,6 +149,26 @@ def command_settings( ) +def category( + name: str, action_names: List[str], help: str = "", description: str = "" +) -> "Category": + """Create a category for CLI actions. + + Args: + name: Name of the category. + action_names: The actions of this category. + Returns: + A CLI category. + """ + action_names = set(action_names) + return Category( + name=name, + action_names=action_names, + help=help, + description=description, + ) + + def command_extension_settings( actions: List["Action"], config_section_name: Optional[str] = None ) -> _CommandExtensionSettings: @@ -375,29 +418,37 @@ class Category(ImmutableMixin, abc.ABC): For example, the command ``repobee issues list`` has category ``issues`` and action ``list``. Actions are unique only within their category. - - Attributes: - name: Name of this category. - actions: A tuple of names of actions applicable to this category. """ + help: str = "" + description: str = "" name: str actions: Tuple["Action"] action_names: Set[str] _action_table: Mapping[str, "Action"] - def __init__(self): + def __init__( + self, + name: Optional[str] = None, + action_names: Optional[Set[str]] = None, + help: Optional[str] = None, + description: Optional[str] = None, + ): # determine the name of this category based on the runtime type of the # inheriting class - name = self.__class__.__name__.lower().strip("_") + name = name or self.__class__.__name__.lower().strip("_") # determine the action names based on type annotations in the # inheriting class - action_names = { + action_names = (action_names or set()) | { name for name, tpe in self.__annotations__.items() - if issubclass(tpe, Action) + if isinstance(tpe, type) and issubclass(tpe, Action) } + object.__setattr__(self, "help", help or self.help) + object.__setattr__( + self, "description", description or self.description + ) object.__setattr__(self, "name", name) object.__setattr__(self, "action_names", set(action_names)) # This is just to reserve the name 'actions' @@ -410,7 +461,7 @@ class Category(ImmutableMixin, abc.ABC): actions = [] for action_name in action_names: action = Action(action_name.replace("_", "-"), self) - object.__setattr__(self, action_name, action) + object.__setattr__(self, action_name.replace("-", "_"), action) actions.append(action) object.__setattr__(self, "actions", tuple(actions))
repobee/repobee
88c22d8b2b2e5cd98294aa504c74d025ea6879ae
diff --git a/tests/unit_tests/repobee_plug/test_pluginmeta.py b/tests/unit_tests/repobee_plug/test_pluginmeta.py index b997f00..e2e987a 100644 --- a/tests/unit_tests/repobee_plug/test_pluginmeta.py +++ b/tests/unit_tests/repobee_plug/test_pluginmeta.py @@ -159,7 +159,7 @@ class TestDeclarativeExtensionCommand: class ExtCommand(plug.Plugin, plug.cli.Command): __settings__ = plug.cli.command_settings( category=expected_category, - action_name=expected_name, + action=expected_name, help=expected_help, description=expected_description, base_parsers=expected_base_parsers, @@ -353,6 +353,102 @@ class TestDeclarativeExtensionCommand: assert parsed_args.old == old + def test_create_new_category(self): + """Test that command can be added to a new category.""" + + class Greetings(plug.cli.Category): + hello: plug.cli.Action + + class Hello(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings(action=Greetings().hello) + name = plug.cli.positional() + age = plug.cli.positional(converter=int) + + def command(self, args, api): + return plug.Result( + name=self.plugin_name, + msg="Nice!", + status=plug.Status.SUCCESS, + data={"name": args.name, "age": args.age}, + ) + + name = "Bob" + age = 24 + results_mapping = repobee.run( + f"greetings hello {name} {age}".split(), plugins=[Hello] + ) + _, results = list(results_mapping.items())[0] + result, *_ = results + + assert result.data["name"] == name + assert result.data["age"] == age + + def test_add_two_actions_to_new_category(self): + """Test that it's possible to add multiple actions to a custom + category. + """ + + class Greetings(plug.cli.Category): + hello: plug.cli.Action + bye: plug.cli.Action + + category = Greetings() + + class Hello(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings(action=category.hello) + name = plug.cli.positional() + + def command(self, args, api): + return plug.Result( + name=self.plugin_name, + msg=f"Hello {args.name}", + status=plug.Status.SUCCESS, + ) + + class Bye(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings(action=category.bye) + name = plug.cli.positional() + + def command(self, args, api): + return plug.Result( + name=self.plugin_name, + msg=f"Bye {args.name}", + status=plug.Status.SUCCESS, + ) + + name = "Alice" + hello_results = repobee.run( + f"greetings hello {name}".split(), plugins=[Hello, Bye] + ) + bye_results = repobee.run( + f"greetings bye {name}".split(), plugins=[Hello, Bye] + ) + + assert hello_results[category.hello][0].msg == f"Hello {name}" + assert bye_results[category.bye][0].msg == f"Bye {name}" + + def test_raises_when_both_action_and_category_given(self): + """It is not allowed to give an Action object to the action argument, + and at the same time give a Category, as the Action object defines + both. + """ + category = plug.cli.category("cat", action_names=["greetings"]) + + with pytest.raises(TypeError) as exc_info: + + class Greetings(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings( + action=category.greetings, category=category + ) + + def command(self, args, api): + pass + + assert ( + "argument 'category' not allowed when argument " + "'action' is an Action object" + ) in str(exc_info.value) + class TestDeclarativeCommandExtension: """Test creating command extensions to existing commands."""
Allow extension commands to add new categories An extension command should be able to add a new category. It should also be possible for several extension commands to attach to the same category. We'll need this for example for `repobee plugin install` and `repobee plugin uninstall`.
0.0
88c22d8b2b2e5cd98294aa504c74d025ea6879ae
[ "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_with_settings", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_raises_when_both_action_and_category_given" ]
[ "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestPluginInheritance::test_raises_on_non_hook_public_method", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_defaults", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_generated_parser", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_configuration", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_raises_when_non_configurable_value_is_configured", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_override_opt_names", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_positional_arguments", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_mutex_group_arguments_are_mutually_exclusive", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_positionals_not_allowed_in_mutex_group", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeExtensionCommand::test_mutex_group_allows_one_argument", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_add_required_option_to_config_show", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_raises_when_command_and_command_extension_are_subclassed_together", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_requires_settings", "tests/unit_tests/repobee_plug/test_pluginmeta.py::TestDeclarativeCommandExtension::test_requires_non_empty_actions_list" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-25 09:33:47+00:00
mit
5,243
repobee__repobee-csvgrades-23
diff --git a/repobee_csvgrades/_marker.py b/repobee_csvgrades/_marker.py index 4c70e7e..6ed87a4 100644 --- a/repobee_csvgrades/_marker.py +++ b/repobee_csvgrades/_marker.py @@ -10,6 +10,7 @@ import itertools import re import heapq import contextlib +import dataclasses from typing import List import daiquiri @@ -17,9 +18,18 @@ import daiquiri import repobee_plug as plug from repobee_csvgrades import _exception +from repobee_csvgrades import _containers LOGGER = daiquiri.getLogger(__file__) [email protected](frozen=True, order=True) +class _SpeccedIssue: + """Wrapper for an issue and associated grade spec, which is ordered by the + gradespec. + """ + + spec: _containers.GradeSpec = dataclasses.field(compare=True) + issue: plug.platform.Issue = dataclasses.field(compare=False) def get_authorized_issues(issues, teachers, grade_spec, repo_name): matched_issues = [ @@ -61,13 +71,13 @@ def mark_grade( issue_heap = [] for spec in grade_specs: for issue in get_authorized_issues(issues, teachers, spec, repo_name): - heapq.heappush(issue_heap, (spec, issue)) + heapq.heappush(issue_heap, _SpeccedIssue(spec, issue)) graded_students = [] author = None symbol = None if issue_heap: - spec, issue = issue_heap[0] + spec, issue = issue_heap[0].spec, issue_heap[0].issue for student in team.members: with log_error(_exception.GradingError): old = grades.set(student, master_repo_name, spec) diff --git a/requirements.txt b/requirements.txt index a0618ec..3c3c9c4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,1 +1,2 @@ -repobee>=3.0.0 +repobee>=3.5.0 +dataclasses>='0.7';python_version<'3.7' diff --git a/setup.py b/setup.py index a833643..c9db413 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ with open("repobee_csvgrades/__version.py", mode="r", encoding="utf-8") as f: assert re.match(r"^\d+(\.\d+){2}(-(alpha|beta|rc)(\.\d+)?)?$", __version__) test_requirements = ["pytest", "pytest-cov", "pytest-mock", "tox"] -required = ["repobee>=3.0.0"] +required = ["repobee>=3.5.0", "dataclasses>='0.7';python_version<'3.7'"] setup( name="repobee-csvgrades",
repobee/repobee-csvgrades
71270f80f42a801b6405e6778da9401af102ed4f
diff --git a/tests/test_csvgrades.py b/tests/test_csvgrades.py index a5e8eb6..a659a7d 100644 --- a/tests/test_csvgrades.py +++ b/tests/test_csvgrades.py @@ -36,11 +36,11 @@ FAIL_GRADESPEC_FORMAT = "2:F:[Ff]ail" KOMP_GRADESPEC_FORMAT = "3:K:[Kk]omplettering" -def create_pass_hookresult(author): +def create_pass_hookresult(author, number=3): pass_issue = plug.Issue( title="Pass", body="This is a pass", - number=3, + number=number, created_at=datetime(1992, 9, 19), author=author, ) @@ -79,6 +79,17 @@ def create_komp_and_pass_hookresult(author): ) +def create_duplicated_pass_hookresult(author): + first_pass = create_pass_hookresult(author, number=3) + second_pass = create_pass_hookresult(author, number=4) + return plug.Result( + name="list-issues", + status=plug.Status.SUCCESS, + msg=None, + data={**first_pass.data, **second_pass.data}, + ) + + @pytest.fixture def mocked_hook_results(mocker): """Hook results with passes for glassey-glennol in week-1 and week-2, and @@ -91,7 +102,7 @@ def mocked_hook_results(mocker): for team, repo_name, result in [ (slarse, "week-1", create_komp_hookresult(SLARSE_TA)), (slarse, "week-2", create_komp_hookresult(SLARSE_TA)), - (slarse, "week-4", create_pass_hookresult(SLARSE_TA)), + (slarse, "week-4", create_duplicated_pass_hookresult(SLARSE_TA)), (slarse, "week-6", create_komp_and_pass_hookresult(SLARSE_TA)), ( glassey_glennol,
Crash multiple issues matching the same grade spec This causes a crash when pushing to the heap, as the issues themselves are then used for comparison, and `<` isn't implemented for them.
0.0
71270f80f42a801b6405e6778da9401af102ed4f
[ "tests/test_csvgrades.py::TestCallback::test_correctly_marks_passes", "tests/test_csvgrades.py::TestCallback::test_writes_edit_msg", "tests/test_csvgrades.py::TestCallback::test_multiple_specs", "tests/test_csvgrades.py::TestCallback::test_repos_without_hook_results_are_skipped" ]
[ "tests/test_csvgrades.py::TestCallback::test_writes_nothing_if_graders_are_not_teachers", "tests/test_csvgrades.py::TestCallback::test_does_not_overwrite_lower_priority_grades", "tests/test_csvgrades.py::TestCallback::test_students_missing_from_grades_file_causes_crash", "tests/test_csvgrades.py::TestCallback::test_raises_if_state_is_not_all", "tests/test_csvgrades.py::test_register" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-16 19:07:25+00:00
mit
5,244
repobee__repobee-feedback-24
diff --git a/repobee_feedback/feedback.py b/repobee_feedback/feedback.py index 6014698..f4ceb59 100644 --- a/repobee_feedback/feedback.py +++ b/repobee_feedback/feedback.py @@ -11,6 +11,7 @@ import pathlib import re import sys import argparse +from textwrap import indent from typing import Iterable, Tuple, List, Mapping import repobee_plug as plug @@ -18,6 +19,8 @@ import repobee_plug as plug PLUGIN_NAME = "feedback" BEGIN_ISSUE_PATTERN = r"#ISSUE#(.*?)#(.*)" +INDENTATION_STR = " " +TRUNC_SIGN = "[...]" def callback(args: argparse.Namespace, api: plug.PlatformAPI) -> None: @@ -108,20 +111,20 @@ class Feedback(plug.Plugin, plug.cli.Command): callback(self.args, api) +def _indent_issue_body(body: str, trunc_len: int): + indented_body = indent(body[:trunc_len], INDENTATION_STR) + body_end = TRUNC_SIGN if len(body) > trunc_len else "" + return indented_body + body_end + + def _ask_for_open(issue: plug.Issue, repo_name: str, trunc_len: int) -> bool: - plug.echo( - 'Processing issue "{}" for {}: {}{}'.format( - issue.title, - repo_name, - issue.body[:trunc_len], - "[...]" if len(issue.body) > trunc_len else "", - ) + indented_body = _indent_issue_body(issue.body, trunc_len) + issue_description = ( + f'\nProcessing issue "{issue.title}" for {repo_name}:\n{indented_body}' ) + plug.echo(issue_description) return ( - input( - 'Open issue "{}" in repo {}? (y/n) '.format(issue.title, repo_name) - ) - == "y" + input(f'Open issue "{issue.title}" in repo {repo_name}? (y/n) ') == "y" )
repobee/repobee-feedback
8c3924c8bce4e6e570b1b68f9da53df2fd0bbf53
diff --git a/tests/test_feedback.py b/tests/test_feedback.py index 790e602..67667d4 100644 --- a/tests/test_feedback.py +++ b/tests/test_feedback.py @@ -223,3 +223,26 @@ class TestCallback: feedback.callback(args=args, api=api_mock) api_mock.create_issue.assert_has_calls(expected_calls, any_order=True) + + +class TestIndentIssueBody: + """Tests for the method that addds indentation to the issue body""" + + def test_issue_indented_and_truncated( + self, + ): + """Test that a long issue body get truncated to a certain length""" + body = "Hello world\nfrom python\n" + indented_body = feedback._indent_issue_body( + body, trunc_len=len(body) // 2 + ) + assert indented_body.startswith(f"{feedback.INDENTATION_STR}Hello") + assert indented_body.endswith(feedback.TRUNC_SIGN) + + def test_issue_indented_and_not_truncated( + self, + ): + """Test that a short issue body does not get truncated""" + body = "This is an issue\n" + indented_body = feedback._indent_issue_body(body, 2 * len(body)) + assert indented_body == f"{feedback.INDENTATION_STR}{body}"
Reformat issue confirmation output on using Multi Issue File Right now when opening issues repobee asks for confirmation on these and the way the text is formatted doesn't really do it for my eyes. ``` wagmode$ repobee issues feedback --mi issues.md -a task-15 Processing issue "Pass" for student1-task-15: Now this is c++! dolor sit amet Open issue "Pass" in repo student1-task-15? (y/n) y Processing issue "Fail" for student2-task-15: Open issue "Fail" in repo student2-task-15? (y/n) y Processing issue "Pass" for student3-task-15: more lorem ipsum, more dolor sit amet Open issue "Pass" in repo student3-task-15? (y/n) ```` I think this feels a bit cluttered, especially when each issue is given one by one it is sometimes difficult to directly see what is the new/old issue. Instead I would want something like this: ``` wagmode$ repobee issues feedback --mi issues.md -a task-15 Processing issue "Pass" for student1-task-15: >Now this is c++! > >lorem ispum dolor sit amet Open issue "Pass" in repo student1-task-15? (y/n) y Processing issue "Fail" for student2-task-15: Open issue "Fail" in repo student2-task-15? (y/n) y Processing issue "Pass" for student3-task-15: >More Lorem isum > >More dolor sit amet Open issue "Pass" in repo student3-task-15? (y/n) ``` So the changes i can think of right now is: * Separate each issue with empty line * Indent issue text and/or place in some kind of block This becomes even more usefull for larger issues. Alternatively, we can also make it so that when a new issue is shown in the terminal we make it so that while in "approval mode" only the current issue is shown. @slarse what do you think?
0.0
8c3924c8bce4e6e570b1b68f9da53df2fd0bbf53
[ "tests/test_feedback.py::TestIndentIssueBody::test_issue_indented_and_truncated", "tests/test_feedback.py::TestIndentIssueBody::test_issue_indented_and_not_truncated" ]
[ "tests/test_feedback.py::test_register", "tests/test_feedback.py::TestCallback::test_opens_issues_from_issues_dir", "tests/test_feedback.py::TestCallback::test_aborts_if_issue_is_missing", "tests/test_feedback.py::TestCallback::test_ignores_missing_issue_if_allow_missing", "tests/test_feedback.py::TestCallback::test_opens_nothing_if_open_prompt_returns_false", "tests/test_feedback.py::TestCallback::test_opens_issues_from_multi_issues_file", "tests/test_feedback.py::TestCallback::test_skips_unexpected_issues_in_multi_issues_file" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-12-18 00:17:14+00:00
mit
5,245
repobee__repobee-feedback-26
diff --git a/repobee_feedback/_generate_multi_issues_file.py b/repobee_feedback/_generate_multi_issues_file.py new file mode 100644 index 0000000..4f007cb --- /dev/null +++ b/repobee_feedback/_generate_multi_issues_file.py @@ -0,0 +1,62 @@ +"""A helper command to automatically generate a file called issue.md +wich contains templates of issues for multiple students assignments. + +.. module:: _generate_multi_issues_file + :synopsis: A helper command to automatically generate a file + called issue.md wich contains templates of issues for multiple + students assignments. + +.. moduleauthor:: Marcelo Freitas +""" +import pathlib +import sys +from typing import List + +import repobee_plug as plug +from repobee_plug.cli.categorization import Action + +MULTI_ISSUES_FILENAME = "issue.md" + +GENERATE_MULTI_ISSUES_FILE_ACTION = Action( + name="generate-multi-issues-file", + category=plug.cli.CoreCommand.issues, +) + + +class GenerateMultiIssuesFile(plug.Plugin, plug.cli.Command): + __settings__ = plug.cli.command_settings( + help=( + "auto generate multi-issues file" + " for the `issues feedback` command" + ), + description="Will generate a multi-issues file template " + "where each pair of student assignment passed " + "will become an issue that starts with the line " + "#ISSUE#<STUDENT_REPO_NAME>#<ISSUE_TITLE>, followed by its " + "body. Title and body should be filled appropriately later.", + action=GENERATE_MULTI_ISSUES_FILE_ACTION, + base_parsers=[plug.BaseParser.ASSIGNMENTS, plug.BaseParser.STUDENTS], + ) + + def command(self): + content = _generate_multi_issues_file_content( + self.args.students, self.args.assignments + ) + + pathlib.Path(MULTI_ISSUES_FILENAME).write_text( + content, encoding=sys.getdefaultencoding() + ) + + plug.echo(f"Created multi-issues file '{MULTI_ISSUES_FILENAME}'") + + +def _generate_multi_issues_file_content( + students: List[str], assignments: List[str] +) -> str: + + issue_headers = [ + f"#ISSUE#{repo_name}#<ISSUE-TITLE>\n<ISSUE-BODY>" + for repo_name in plug.generate_repo_names(students, assignments) + ] + + return "\n\n".join(issue_headers) diff --git a/repobee_feedback/feedback.py b/repobee_feedback/feedback.py index f4ceb59..cc6d488 100644 --- a/repobee_feedback/feedback.py +++ b/repobee_feedback/feedback.py @@ -15,6 +15,9 @@ from textwrap import indent from typing import Iterable, Tuple, List, Mapping import repobee_plug as plug +from repobee_feedback._generate_multi_issues_file import ( # noqa: F401 + GenerateMultiIssuesFile, +) PLUGIN_NAME = "feedback"
repobee/repobee-feedback
304e38cfcaaa1dba37dbe7bf52e37dca2387572f
diff --git a/tests/test_generate_multi_issues_file.py b/tests/test_generate_multi_issues_file.py new file mode 100644 index 0000000..29b2c36 --- /dev/null +++ b/tests/test_generate_multi_issues_file.py @@ -0,0 +1,45 @@ +import sys + +import repobee +from repobee_feedback._generate_multi_issues_file import ( + MULTI_ISSUES_FILENAME, + GENERATE_MULTI_ISSUES_FILE_ACTION, + GenerateMultiIssuesFile, +) + + +class TestGenerateMultiIssuesFile: + """Tests generation of a multi-issues file""" + + def test_creates_non_empty_output_file(self, tmp_path): + students = "alice bob".split() + assignments = "task-1 task-2".split() + command = [ + *GENERATE_MULTI_ISSUES_FILE_ACTION.as_name_tuple(), + "--students", + *students, + "--assignments", + *assignments, + ] + + expected_content = ( + "#ISSUE#alice-task-1#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#bob-task-1#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#alice-task-2#<ISSUE-TITLE>\n" + "<ISSUE-BODY>\n\n" + "#ISSUE#bob-task-2#<ISSUE-TITLE>\n" + "<ISSUE-BODY>" + ) + + repobee.run( + command, + plugins=[GenerateMultiIssuesFile], + workdir=tmp_path, + ) + + outfile = tmp_path / MULTI_ISSUES_FILENAME + content = outfile.read_text(encoding=sys.getdefaultencoding()) + assert outfile.is_file() + assert content == expected_content
Auto generate multi-issue file I'm getting real tired of adding #ISSUE#name-task-X#Pass/fail to a file 15 times so I considered writing a plugin to do that for me but realized I can just add it to the feedback plugin if that's okay with you @slarse I'm thinking something like: `repobee issues feedback create-mi-file`
0.0
304e38cfcaaa1dba37dbe7bf52e37dca2387572f
[ "tests/test_generate_multi_issues_file.py::TestGenerateMultiIssuesFile::test_creates_non_empty_output_file" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-12-21 18:27:15+00:00
mit
5,246
reportportal__client-Python-137
diff --git a/reportportal_client/helpers.py b/reportportal_client/helpers.py index a4cecf3..7a52a39 100644 --- a/reportportal_client/helpers.py +++ b/reportportal_client/helpers.py @@ -13,10 +13,12 @@ limitations under the License. """ import logging import uuid +from pkg_resources import DistributionNotFound, get_distribution from platform import machine, processor, system import six -from pkg_resources import DistributionNotFound, get_distribution + +from .static.defines import ATTRIBUTE_LENGTH_LIMIT logger = logging.getLogger(__name__) @@ -106,3 +108,27 @@ def get_package_version(package_name): except DistributionNotFound: package_version = 'not found' return package_version + + +def verify_value_length(attributes): + """Verify length of the attribute value. + + The length of the attribute value should have size from '1' to '128'. + Otherwise HTTP response will return an error. + Example of the input list: + [{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}] + :param attributes: List of attributes(tags) + :return: List of attributes with corrected value length + """ + if attributes is not None: + for pair in attributes: + if not isinstance(pair, dict): + continue + attr_value = pair.get('value') + if attr_value is None: + continue + try: + pair['value'] = attr_value[:ATTRIBUTE_LENGTH_LIMIT] + except TypeError: + continue + return attributes diff --git a/reportportal_client/helpers.pyi b/reportportal_client/helpers.pyi index fbf35ad..763ec63 100644 --- a/reportportal_client/helpers.pyi +++ b/reportportal_client/helpers.pyi @@ -1,20 +1,19 @@ from logging import Logger -from typing import Dict, List, Text +from typing import Dict, List, Text, Union logger: Logger +def generate_uuid() -> Text: ... -def generate_uuid() -> str: ... - - -def convert_string(value: str) -> str: ... - +def convert_string(value: Text) -> Text: ... def dict_to_payload(value: Dict) -> List[Dict]: ... - -def gen_attributes(rp_attributes: List) -> List[Dict]: ... +def gen_attributes(rp_attributes: List[Dict]) -> List[Dict]: ... def get_launch_sys_attrs() -> Dict[Text]: ... def get_package_version(package_name: Text) -> Text: ... + +def verify_value_length( + attributes: Union[List[Dict], None]) -> Union[List[Dict], None]: ... diff --git a/reportportal_client/service.py b/reportportal_client/service.py index 7ae36f5..3b62caf 100644 --- a/reportportal_client/service.py +++ b/reportportal_client/service.py @@ -26,6 +26,7 @@ from six.moves.collections_abc import Mapping from requests.adapters import HTTPAdapter from .errors import ResponseError, EntryCreatedError, OperationCompletionError +from .helpers import verify_value_length POST_LOGBATCH_RETRY_COUNT = 10 logger = logging.getLogger(__name__) @@ -225,7 +226,7 @@ class ReportPortalService(object): data = { "name": name, "description": description, - "attributes": attributes, + "attributes": verify_value_length(attributes), "startTime": start_time, "mode": mode, "rerun": rerun, @@ -251,7 +252,7 @@ class ReportPortalService(object): data = { "endTime": end_time, "status": status, - "attributes": attributes + "attributes": verify_value_length(attributes) } url = uri_join(self.base_url_v2, "launch", self.launch_id, "finish") r = self.session.put(url=url, json=data, verify=self.verify_ssl) @@ -346,7 +347,7 @@ class ReportPortalService(object): data = { "name": name, "description": description, - "attributes": attributes, + "attributes": verify_value_length(attributes), "startTime": start_time, "launchUuid": self.launch_id, "type": item_type, @@ -374,7 +375,7 @@ class ReportPortalService(object): """ data = { "description": description, - "attributes": attributes, + "attributes": verify_value_length(attributes), } item_id = self.get_item_id_by_uuid(item_uuid) url = uri_join(self.base_url_v1, "item", item_id, "update") @@ -413,7 +414,7 @@ class ReportPortalService(object): "status": status, "issue": issue, "launchUuid": self.launch_id, - "attributes": attributes + "attributes": verify_value_length(attributes) } url = uri_join(self.base_url_v2, "item", item_id) r = self.session.put(url=url, json=data, verify=self.verify_ssl) diff --git a/reportportal_client/static/defines.py b/reportportal_client/static/defines.py index dafbbb5..1616fd5 100644 --- a/reportportal_client/static/defines.py +++ b/reportportal_client/static/defines.py @@ -78,6 +78,7 @@ class Priority(enum.IntEnum): PRIORITY_LOW = 0x3 +ATTRIBUTE_LENGTH_LIMIT = 128 DEFAULT_PRIORITY = Priority.PRIORITY_MEDIUM NOT_FOUND = _PresenceSentinel() NOT_SET = _PresenceSentinel() diff --git a/requirements.txt b/requirements.txt index aef8b3d..e2a43e9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ requests>=2.23.0 six>=1.15.0 pytest delayed-assert +enum34
reportportal/client-Python
7a0183567dcfc8f819dba716258a14fae35fd9de
diff --git a/tests/test_helpers.py b/tests/test_helpers.py index a5568b2..bb6d703 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -5,7 +5,8 @@ from six.moves import mock from reportportal_client.helpers import ( gen_attributes, get_launch_sys_attrs, - get_package_version + get_package_version, + verify_value_length ) @@ -49,3 +50,12 @@ def test_get_launch_sys_attrs_docker(): def test_get_package_version(): """Test for the get_package_version() function-helper.""" assert get_package_version('noname') == 'not found' + + +def test_verify_value_length(): + """Test for validate verify_value_length() function.""" + inputl = [{'key': 'tn', 'value': 'v' * 130}, [1, 2], + {'value': 'tv2'}, {'value': 300}] + expected = [{'key': 'tn', 'value': 'v' * 128}, [1, 2], + {'value': 'tv2'}, {'value': 300}] + assert verify_value_length(inputl) == expected
Long pytest makers make report portal status:interrupted When i use this on a test: @pytest.mark.required_options('MACHINE_TYPE=100/101/102/103/104/105/106/107/108/110/111/112, USE_FAM_HLM_SENSOR=1, USE_FAM_OPTION=1, USE_HOLE_LENGTH_MEASURE=1) report portalt get status:interrupted and this error: INTERNALERROR> reportportal_client.errors.ResponseError: 4001: Incorrect Request. [Field 'attributes[].value' should have size from '1' to '128'.] the @pytest.mark.required_options are too long, But are there anything you can do, or do we have to live whit this?
0.0
7a0183567dcfc8f819dba716258a14fae35fd9de
[ "tests/test_helpers.py::test_gen_attributes", "tests/test_helpers.py::test_get_launch_sys_attrs", "tests/test_helpers.py::test_get_launch_sys_attrs_docker", "tests/test_helpers.py::test_get_package_version", "tests/test_helpers.py::test_verify_value_length" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-15 10:17:43+00:00
apache-2.0
5,247
requests__requests-oauthlib-279
diff --git a/HISTORY.rst b/HISTORY.rst index eed85e8..8612723 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -4,7 +4,7 @@ History UNRELEASED ++++++++++ -nothing yet +- Avoid automatic netrc authentication for OAuth2Session. v1.1.0 (9 January 2019) +++++++++++++++++++++++ diff --git a/requests_oauthlib/oauth2_session.py b/requests_oauthlib/oauth2_session.py index 7ad7b46..6fa4453 100644 --- a/requests_oauthlib/oauth2_session.py +++ b/requests_oauthlib/oauth2_session.py @@ -74,6 +74,10 @@ class OAuth2Session(requests.Session): self.auto_refresh_kwargs = auto_refresh_kwargs or {} self.token_updater = token_updater + # Ensure that requests doesn't do any automatic auth. See #278. + # The default behavior can be re-enabled by setting auth to None. + self.auth = lambda r: r + # Allow customizations for non compliant providers through various # hooks to adjust requests and responses. self.compliance_hook = {
requests/requests-oauthlib
4fb0db5d7f388bb05e3252a854cf8c83d57c27d0
diff --git a/tests/test_oauth2_session.py b/tests/test_oauth2_session.py index 9b19f1f..fda0c73 100644 --- a/tests/test_oauth2_session.py +++ b/tests/test_oauth2_session.py @@ -1,6 +1,9 @@ from __future__ import unicode_literals import json import time +import tempfile +import shutil +import os from base64 import b64encode from copy import deepcopy from unittest import TestCase @@ -242,3 +245,36 @@ class OAuth2SessionTest(TestCase): self.assertIs(sess.authorized, False) sess.fetch_token(url) self.assertIs(sess.authorized, True) + + +class OAuth2SessionNetrcTest(OAuth2SessionTest): + """Ensure that there is no magic auth handling. + + By default, requests sessions have magic handling of netrc files, + which is undesirable for this library because it will take + precedence over manually set authentication headers. + """ + + def setUp(self): + # Set up a temporary home directory + self.homedir = tempfile.mkdtemp() + self.prehome = os.environ.get('HOME', None) + os.environ['HOME'] = self.homedir + + # Write a .netrc file that will cause problems + netrc_loc = os.path.expanduser('~/.netrc') + with open(netrc_loc, 'w') as f: + f.write( + 'machine i.b\n' + ' password abc123\n' + ' login [email protected]\n' + ) + + super(OAuth2SessionNetrcTest, self).setUp() + + def tearDown(self): + super(OAuth2SessionNetrcTest, self).tearDown() + + if self.prehome is not None: + os.environ['HOME'] = self.prehome + shutil.rmtree(self.homedir)
OAuth2Session doesn't use token if netrc is present The Heroku Toolbelt client uses a `.netrc` file to store its credentials locally. When using OAuth2Session, giving a properly-formed `token` to the constructor, the `auth` property on the session is not set, and requests goes and looks for a netrc file to add them in automatically when the request is made. When we _have_ set the token, this really needs to not happen. The "ideal" fix would be to have the `OAuth2Session.auth` property set to `OAuth2`. I definitely don't know the complexities of how difficult this is, but this bug makes OAuth2Session unusable for me, and I'm having to drop down to using `OAuth2` auth directly instead for my use-case.
0.0
4fb0db5d7f388bb05e3252a854cf8c83d57c27d0
[ "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_add_token", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_refresh_token_request" ]
[ "tests/test_oauth2_session.py::OAuth2SessionTest::test_access_token_proxy", "tests/test_oauth2_session.py::OAuth2SessionTest::test_add_token", "tests/test_oauth2_session.py::OAuth2SessionTest::test_authorization_url", "tests/test_oauth2_session.py::OAuth2SessionTest::test_authorized_false", "tests/test_oauth2_session.py::OAuth2SessionTest::test_authorized_true", "tests/test_oauth2_session.py::OAuth2SessionTest::test_cleans_previous_token_before_fetching_new_one", "tests/test_oauth2_session.py::OAuth2SessionTest::test_client_id_proxy", "tests/test_oauth2_session.py::OAuth2SessionTest::test_fetch_token", "tests/test_oauth2_session.py::OAuth2SessionTest::test_refresh_token_request", "tests/test_oauth2_session.py::OAuth2SessionTest::test_token_from_fragment", "tests/test_oauth2_session.py::OAuth2SessionTest::test_token_proxy", "tests/test_oauth2_session.py::OAuth2SessionTest::test_web_app_fetch_token", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_access_token_proxy", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_authorization_url", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_authorized_false", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_authorized_true", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_cleans_previous_token_before_fetching_new_one", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_client_id_proxy", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_fetch_token", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_token_from_fragment", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_token_proxy", "tests/test_oauth2_session.py::OAuth2SessionNetrcTest::test_web_app_fetch_token" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-05-04 16:46:03+00:00
isc
5,248
resonai__ybt-92
diff --git a/yabt/cli.py b/yabt/cli.py index 9748af8..a007132 100644 --- a/yabt/cli.py +++ b/yabt/cli.py @@ -107,6 +107,7 @@ def make_parser(project_config_file: str) -> configargparse.ArgumentParser: help='Disable YBT build cache') PARSER.add('--no-docker-cache', action='store_true', help='Disable YBT Docker cache') + PARSER.add('--no-policies', action='store_true') PARSER.add('--no-test-cache', action='store_true', help='Disable YBT test cache') PARSER.add('-v', '--verbose', action='store_true', @@ -226,7 +227,7 @@ def init_and_get_conf(argv: list=None) -> Config: config.flavor_conf = call_user_func( config.settings, 'get_flavored_config', config, args) call_user_func(config.settings, 'extend_config', config, args) - # TODO: condition no "override policies" flag - config.policies = listify(call_user_func( - config.settings, 'get_policies', config)) + if not args.no_policies: + config.policies = listify(call_user_func( + config.settings, 'get_policies', config)) return config
resonai/ybt
79fbae07695e613382712b481db8db1e6450b9e8
diff --git a/conftest.py b/conftest.py index e910f10..be71f74 100644 --- a/conftest.py +++ b/conftest.py @@ -116,3 +116,13 @@ def debug_conf(): '--no-test-cache', '--no-docker-cache', 'build']) yabt.extend.Plugin.load_plugins(conf) yield conf + + +@yield_fixture +def nopolicy_conf(): + reset_parser() + conf = cli.init_and_get_conf([ + '--non-interactive', '--no-build-cache', '--no-test-cache', + '--no-docker-cache','--no-policies', 'build']) + yabt.extend.Plugin.load_plugins(conf) + yield conf diff --git a/yabt/policy_test.py b/yabt/policy_test.py index e672c75..00b371d 100644 --- a/yabt/policy_test.py +++ b/yabt/policy_test.py @@ -74,3 +74,11 @@ def test_multiple_policy_violations(basic_conf): 'Invalid licenses for prod policy: GPL-3.0' in err_str) # asserting for 2 policy violations assert 3 == len(err_str.split('\n')) + + [email protected]('in_error_project') +def test_disable_policy(nopolicy_conf): + nopolicy_conf.targets = ['policy'] + build_context = BuildContext(nopolicy_conf) + populate_targets_graph(build_context, nopolicy_conf) + # asserting no exception thrown
Flags to disable build policies Allow to run build / test that violate policies using CLI flags
0.0
79fbae07695e613382712b481db8db1e6450b9e8
[ "yabt/policy_test.py::test_disable_policy" ]
[ "yabt/policy_test.py::test_policy_violation_unknown_license_name", "yabt/policy_test.py::test_policy_violation_bad_prod_license", "yabt/policy_test.py::test_no_violation", "yabt/policy_test.py::test_multiple_policy_violations" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2018-08-15 14:32:42+00:00
apache-2.0
5,249
resync__resync-46
diff --git a/resync/client.py b/resync/client.py index 4cf99e6..8474cc6 100644 --- a/resync/client.py +++ b/resync/client.py @@ -11,7 +11,8 @@ import distutils.dir_util import re import time import logging -import requests +import shutil +import socket from .resource_list_builder import ResourceListBuilder from .resource_list import ResourceList @@ -504,15 +505,12 @@ class Client(object): # 1. GET for try_i in range(1, self.tries + 1): try: - r = requests.get(resource.uri, timeout=self.timeout, stream=True) - # Fail on 4xx or 5xx - r.raise_for_status() - with open(filename, 'wb') as fd: - for chunk in r.iter_content(chunk_size=1024): - fd.write(chunk) + with url_or_file_open(resource.uri, timeout=self.timeout) as fh_in: + with open(filename, 'wb') as fh_out: + shutil.copyfileobj(fh_in, fh_out) num_updated += 1 break - except requests.Timeout as e: + except socket.timeout as e: if try_i < self.tries: msg = 'Download timed out, retrying...' self.logger.info(msg) @@ -525,7 +523,7 @@ class Client(object): return(num_updated) else: raise ClientFatalError(msg) - except (requests.RequestException, IOError) as e: + except IOError as e: msg = "Failed to GET %s -- %s" % (resource.uri, str(e)) if (self.ignore_failures): self.logger.warning(msg) diff --git a/resync/client_utils.py b/resync/client_utils.py index 15f1e47..02a6ba1 100644 --- a/resync/client_utils.py +++ b/resync/client_utils.py @@ -7,8 +7,6 @@ import argparse from datetime import datetime import logging import logging.config -import re -from urllib.request import urlopen from .url_or_file_open import set_url_or_file_open_config diff --git a/resync/explorer.py b/resync/explorer.py index a4c102f..3e3a3bc 100644 --- a/resync/explorer.py +++ b/resync/explorer.py @@ -17,7 +17,6 @@ import distutils.dir_util import re import time import logging -import requests from .mapper import Mapper from .sitemap import Sitemap @@ -164,7 +163,7 @@ class Explorer(Client): caps = 'resource' else: caps = self.allowed_entries(capability) - elif (r.capability is 'resource'): + elif (r.capability == 'resource'): caps = r.capability else: caps = [r.capability] @@ -278,38 +277,36 @@ class Explorer(Client): print("HEAD %s" % (uri)) if (re.match(r'^\w+:', uri)): # Looks like a URI - response = requests.head(uri) + with url_or_file_open(uri, method='HEAD') as response: + status_code = response.code() + headers = response.headers() else: # Mock up response if we have a local file - response = self.head_on_file(uri) - print(" status: %s" % (response.status_code)) - if (response.status_code == '200'): + (status_code, headers) = self.head_on_file(uri) + print(" status: %s" % (status_code)) + if (status_code == '200'): # print some of the headers for header in ['content-length', 'last-modified', 'lastmod', 'content-type', 'etag']: - if header in response.headers: + if header in headers: check_str = '' if (check_headers is not None and header in check_headers): - if (response.headers[header] == check_headers[header]): + if (headers[header] == check_headers[header]): check_str = ' MATCHES EXPECTED VALUE' else: check_str = ' EXPECTED %s' % ( check_headers[header]) - print( - " %s: %s%s" % - (header, response.headers[header], check_str)) + print(" %s: %s%s" % (header, headers[header], check_str)) def head_on_file(self, file): - """Mock up requests.head(..) response on local file.""" - response = HeadResponse() - if (not os.path.isfile(file)): - response.status_code = '404' - else: - response.status_code = '200' - response.headers[ - 'last-modified'] = datetime_to_str(os.path.getmtime(file)) - response.headers['content-length'] = os.path.getsize(file) - return(response) + """Get fake status code and headers from local file.""" + status_code = '404' + headers = {} + if os.path.isfile(file): + status_code = '200' + headers['last-modified'] = datetime_to_str(os.path.getmtime(file)) + headers['content-length'] = os.path.getsize(file) + return(status_code, headers) def allowed_entries(self, capability): """Return list of allowed entries for given capability document. @@ -367,15 +364,6 @@ class XResource(object): self.checks = checks -class HeadResponse(object): - """Object to mock up requests.head(...) response.""" - - def __init__(self): - """Initialize with no status_code and no headers.""" - self.status_code = None - self.headers = {} - - class ExplorerQuit(Exception): """Exception raised when user quits normally, no error.""" diff --git a/resync/url_or_file_open.py b/resync/url_or_file_open.py index 983e1aa..4981fa4 100644 --- a/resync/url_or_file_open.py +++ b/resync/url_or_file_open.py @@ -21,11 +21,14 @@ def set_url_or_file_open_config(key, value): CONFIG[key] = value -def url_or_file_open(uri): +def url_or_file_open(uri, method=None, timeout=None): """Wrapper around urlopen() to prepend file: if no scheme provided. Can be used as a context manager because the return value from urlopen(...) supports both that and straightforwrd use as simple file handle object. + + If timeout is exceeded then urlopen(..) will raise a socket.timeout exception. If + no timeout is specified then the global default will be used. """ if (not re.match(r'''\w+:''', uri)): uri = 'file:' + uri @@ -42,4 +45,5 @@ def url_or_file_open(uri): if NUM_REQUESTS != 0 and CONFIG['delay'] is not None and not uri.startswith('file:'): time.sleep(CONFIG['delay']) NUM_REQUESTS += 1 - return urlopen(Request(url=uri, headers=headers)) + maybe_timeout = {} if timeout is None else {'timeout': timeout} + return urlopen(Request(url=uri, headers=headers, method=method), **maybe_timeout) diff --git a/setup.py b/setup.py index 8d110dd..9a049d8 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,6 @@ setup( long_description=open('README.md').read(), long_description_content_type='text/markdown', install_requires=[ - "requests", "python-dateutil>=1.5", "defusedxml>=0.4.1" ],
resync/resync
f5cd751c6706855a57c014806a19342274caa921
diff --git a/tests/test_explorer.py b/tests/test_explorer.py index e5d214f..04a1649 100644 --- a/tests/test_explorer.py +++ b/tests/test_explorer.py @@ -8,7 +8,7 @@ import sys from resync.client import Client from resync.client_utils import ClientFatalError from resync.capability_list import CapabilityList -from resync.explorer import Explorer, XResource, HeadResponse, ExplorerQuit +from resync.explorer import Explorer, XResource, ExplorerQuit from resync.resource import Resource @@ -30,11 +30,6 @@ class TestExplorer(unittest.TestCase): self.assertEqual(x.acceptable_capabilities, [1, 2]) self.assertEqual(x.checks, [3, 4]) - def test02_head_response(self): - hr = HeadResponse() - self.assertEqual(hr.status_code, None) - self.assertEqual(len(hr.headers), 0) - def test03_explorer_quit(self): eq = ExplorerQuit() self.assertTrue(isinstance(eq, Exception)) @@ -105,13 +100,14 @@ class TestExplorer(unittest.TestCase): def test08_head_on_file(self): e = Explorer() - r1 = e.head_on_file('tests/testdata/does_not_exist') - self.assertEqual(r1.status_code, '404') - r2 = e.head_on_file('tests/testdata/dir1/file_a') - self.assertEqual(r2.status_code, '200') + (status_code, headers) = e.head_on_file('tests/testdata/does_not_exist') + self.assertEqual(status_code, '404') + self.assertEqual(headers, {}) + (status_code, headers) = e.head_on_file('tests/testdata/dir1/file_a') + self.assertEqual(status_code, '200') self.assertTrue(re.match(r'^\d\d\d\d\-\d\d\-\d\d', - r2.headers['last-modified'])) - self.assertEqual(r2.headers['content-length'], 20) + headers['last-modified'])) + self.assertEqual(headers['content-length'], 20) def test09_allowed_entries(self): e = Explorer()
Access token specified to resync-sync is not exposed to resync.Client instances As @zimeon knows I've been trying to put `resync` through its paces to harvest from the POD data lake, and specifically trying to use `resync-sync` (to provide a readymade solution). While #37 added support for Bearer tokens (as needed by POD), it appears that the `--access-token` parameter doesn't propagate down to the instance of `resync.Client`, namely the [update_resource() method](https://github.com/resync/resync/blob/main/resync/client.py#L507). For what it's worth, would it be possible to pass or instantiate the same header configurations from the `CONFIG` global set in [`resync.url_or_file_open`](https://github.com/resync/resync/blob/main/resync/url_or_file_open.py), to also allow the delay/backoff, and to set the `User-Agent` header? Thanks for considering. Discovered while looking into ivplus/aggregator#324.
0.0
f5cd751c6706855a57c014806a19342274caa921
[ "tests/test_explorer.py::TestExplorer::test08_head_on_file" ]
[ "tests/test_explorer.py::TestExplorer::test01_create", "tests/test_explorer.py::TestExplorer::test01_xresource", "tests/test_explorer.py::TestExplorer::test03_explorer_quit", "tests/test_explorer.py::TestExplorer::test04_explore", "tests/test_explorer.py::TestExplorer::test05_explore_uri", "tests/test_explorer.py::TestExplorer::test06_explore_show_summary", "tests/test_explorer.py::TestExplorer::test07_explore_show_head", "tests/test_explorer.py::TestExplorer::test09_allowed_entries", "tests/test_explorer.py::TestExplorer::test10_expand_relative_uri" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-19 01:56:28+00:00
apache-2.0
5,250
resync__resync-50
diff --git a/resync/url_authority.py b/resync/url_authority.py index 7697e20..3276b45 100644 --- a/resync/url_authority.py +++ b/resync/url_authority.py @@ -14,19 +14,19 @@ class UrlAuthority(object): Two modes are supported: strict=True: requires that a query URL has the same URI - scheme (e.g. http) as the master, is on the same server + scheme (e.g. http) as the primary, is on the same server or one in a sub-domain, and that the path component is - at the same level or below the master. + at the same level or below the primary. strict=False (default): requires only that a query URL - has the same URI scheme as the master, and is on the same - server or one in a sub-domain of the master. + has the same URI scheme as the primary, and is on the same + server or one in a sub-domain of the primary. Example use: from resync.url_authority import UrlAuthority - auth = UrlAuthority("http://example.org/master") + auth = UrlAuthority("http://example.org/primary") if (auth.has_authority_over("http://example.com/res1")): # will be true if (auth.has_authority_over("http://other.com/res1")): @@ -34,40 +34,40 @@ class UrlAuthority(object): """ def __init__(self, url=None, strict=False): - """Create object and optionally set master url and/or strict mode.""" + """Create object and optionally set primary url and/or strict mode.""" self.url = url self.strict = strict if (self.url is not None): - self.set_master(self.url) + self.set_primary(self.url) else: - self.master_scheme = 'none' - self.master_netloc = 'none.none.none' - self.master_path = '/not/very/likely' + self.primary_scheme = 'none' + self.primary_netloc = 'none.none.none' + self.primary_path = '/not/very/likely' - def set_master(self, url): - """Set the master url that this object works with.""" + def set_primary(self, url): + """Set the primary url that this object works with.""" m = urlparse(url) - self.master_scheme = m.scheme - self.master_netloc = m.netloc - self.master_path = os.path.dirname(m.path) + self.primary_scheme = m.scheme + self.primary_netloc = m.netloc + self.primary_path = os.path.dirname(m.path) def has_authority_over(self, url): - """Return True of the current master has authority over url. + """Return True of the current primary has authority over url. In strict mode checks scheme, server and path. Otherwise checks just that the server names match or the query url is a - sub-domain of the master. + sub-domain of the primary. """ s = urlparse(url) - if (s.scheme != self.master_scheme): + if (s.scheme != self.primary_scheme): return(False) - if (s.netloc != self.master_netloc): - if (not s.netloc.endswith('.' + self.master_netloc)): + if (s.netloc != self.primary_netloc): + if (not s.netloc.endswith('.' + self.primary_netloc)): return(False) # Maybe should allow parallel for 3+ components, eg. a.example.org, # b.example.org path = os.path.dirname(s.path) - if (self.strict and path != self.master_path - and not path.startswith(self.master_path)): + if (self.strict and path != self.primary_path + and not path.startswith(self.primary_path)): return(False) return(True)
resync/resync
e7767bb3f5159e9fbd1dfd93f5d36f11cec201e9
diff --git a/tests/test_url_authority.py b/tests/test_url_authority.py index 6f5d60f..454a69f 100644 --- a/tests/test_url_authority.py +++ b/tests/test_url_authority.py @@ -91,7 +91,7 @@ class TestUrlAuthority(unittest.TestCase): def test07_no_init_data(self): uauth = UrlAuthority() - self.assertEqual(uauth.master_scheme, 'none') + self.assertEqual(uauth.primary_scheme, 'none') self.assertFalse(uauth.has_authority_over( 'http://a.example.org/sitemap.xml')) self.assertFalse(uauth.has_authority_over(
Fix terminology in resync/url_authority.py Use "primary" instead of "master"
0.0
e7767bb3f5159e9fbd1dfd93f5d36f11cec201e9
[ "tests/test_url_authority.py::TestUrlAuthority::test07_no_init_data" ]
[ "tests/test_url_authority.py::TestUrlAuthority::test01_strict_authority", "tests/test_url_authority.py::TestUrlAuthority::test02_strict_no_authority", "tests/test_url_authority.py::TestUrlAuthority::test03_strict_domains", "tests/test_url_authority.py::TestUrlAuthority::test04_lax_authority", "tests/test_url_authority.py::TestUrlAuthority::test05_lax_no_authority", "tests/test_url_authority.py::TestUrlAuthority::test06_lax_domains" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2021-03-23 13:11:31+00:00
apache-2.0
5,251
rgalanakis__hostthedocs-30
diff --git a/.travis.yml b/.travis.yml index 040f5d8..fc31a23 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,11 @@ language: python python: - - "2.6" - - "2.7" # See https://github.com/rgalanakis/hostthedocs/pull/24 for details # - "3.3" - "3.4" - "3.5" - "3.6" - - "pypy" + - "3.7" - "pypy3" install: - pip install tox-travis diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e398521 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## 1.1.0 - 2018-07-21 + +Final version supporting Python 2.6 and 2.7. + +See https://github.com/rgalanakis/hostthedocs/releases/tag/v1.1.0 + + +## 1.0.0 - 2014-04-11 + +Initial release + +See https://github.com/rgalanakis/hostthedocs/releases/tag/v1.0.0 diff --git a/hostthedocs/__init__.py b/hostthedocs/__init__.py index f6d860c..67e09cd 100644 --- a/hostthedocs/__init__.py +++ b/hostthedocs/__init__.py @@ -63,5 +63,4 @@ def latest(project, path): latestlink = '%s/%s' % (os.path.dirname(latestindex), path) else: latestlink = latestindex - # Should it be a 302 or something else? - return redirect(latestlink) + return redirect('/' + latestlink) diff --git a/tox.ini b/tox.ini index fe685f6..91b8465 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py26, py27, py33, py34, py35, py36, pypy, pypy3 +envlist = py33, py34, py35, py36, py37, pypy3 [testenv] commands = nosetests @@ -7,40 +7,11 @@ deps = nose mock -[testenv:py26] -basepython = python2.6 -deps = - {[testenv]deps} - unittest2 - -[testenv:py27] -basepython = python2.7 - -[testenv:py33] -basepython = python3.3 - -[testenv:py34] -basepython = python3.4 - -[testenv:py35] -basepython = python3.5 - -[testenv:py36] -basepython = python3.6 - -[testenv:pypy] -basepython = pypy - -[testenv:pypy3] -basepython = pypy3 - [travis] python = - 2.6: py26 - 2.7: py27 3.3: py33 3.4: py34 3.5: py35 3.6: py36 - pypy: pypy - pypy3: pypy3 \ No newline at end of file + 3.7: py37 + pypy3: pypy3
rgalanakis/hostthedocs
89e2a62f4b13aec4adb6000f47efda696c7e14e9
diff --git a/tests/test_hostthedocs.py b/tests/test_hostthedocs.py index 631bc6d..485f76b 100644 --- a/tests/test_hostthedocs.py +++ b/tests/test_hostthedocs.py @@ -51,12 +51,15 @@ class LatestTests(Base): def assert_redirect(self, path, code, location): resp = self.app.get(path) - self.assertEqual(resp.status_code, code) + if isinstance(code, list): + self.assertIn(resp.status_code, code) + else: + self.assertEqual(resp.status_code, code) gotloc = urlparse.urlsplit(dict(resp.headers)['Location']).path self.assertEqual(gotloc, location) def test_latest_noslash(self): - self.assert_redirect('/foo/latest', 301, '/foo/latest/') + self.assert_redirect('/foo/latest', [301, 308], '/foo/latest/') def test_latest_root(self): self.assert_redirect('/Project2/latest/', 302, '/linkroot/Project2/2.0.3/index.html')
Linking to latest doesn't work The link to latest version is not working Below is the debug log (sample2 is the project name that contains only one version 0.1.2) 127.0.0.1 - - [02/Jul/2019 15:49:54] "GET /sample2/latest HTTP/1.1" 308 - 127.0.0.1 - - [02/Jul/2019 15:51:01] "GET /sample2/latest/ HTTP/1.1" 302 - 127.0.0.1 - - [02/Jul/2019 15:52:19] "GET /sample2/latest/static/docfiles/sample2/0.1.2/index.html HTTP/1.1" 302 - 127.0.0.1 - - [02/Jul/2019 15:52:31] "GET /sample2/latest/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/index.html HTTP/1.1" 302 - 127.0.0.1 - - [02/Jul/2019 15:52:56] "GET /sample2/latest/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/static/docfiles/sample2/0.1.2/index.html HTTP/1.1" 302 -
0.0
89e2a62f4b13aec4adb6000f47efda696c7e14e9
[ "tests/test_hostthedocs.py::LatestTests::test_latest_nestedfile", "tests/test_hostthedocs.py::LatestTests::test_latest_certainfile", "tests/test_hostthedocs.py::LatestTests::test_latest_root" ]
[ "tests/test_hostthedocs.py::HomeTests::test_inserts_latest", "tests/test_hostthedocs.py::HomeTests::test_finds_all", "tests/test_hostthedocs.py::LatestTests::test_missing_returns_404", "tests/test_hostthedocs.py::LatestTests::test_latest_noslash", "tests/test_hostthedocs.py::ConfigTests::test_uses_flask_if_debug", "tests/test_hostthedocs.py::ConfigTests::test_uses_gevent_if_gevent", "tests/test_hostthedocs.py::ConfigTests::test_uses_flask_if_gevent_none", "tests/test_hostthedocs.py::ConfigTests::test_uses_flask_if_flask", "tests/test_hostthedocs.py::ConfigTests::test_uses_gevent_if_gevent_available", "tests/test_hostthedocs.py::ConfigTests::test_uses_serve_if_provided", "tests/test_hostthedocs.py::HMFDTests::test_readonly", "tests/test_hostthedocs.py::HMFDTests::test_missing_zip", "tests/test_hostthedocs.py::HMFDTests::test_delete_when_disabled", "tests/test_hostthedocs.py::HMFDTests::test_add_new", "tests/test_hostthedocs.py::HMFDTests::test_method_not_allowed", "tests/test_hostthedocs.py::HMFDTests::test_delete" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-21 12:16:22+00:00
mit
5,252
richardkiss__pycoin-353
diff --git a/pycoin/symbols/ltc.py b/pycoin/symbols/ltc.py index 37fddc1..9dd5bdb 100644 --- a/pycoin/symbols/ltc.py +++ b/pycoin/symbols/ltc.py @@ -3,5 +3,5 @@ from pycoin.networks.bitcoinish import create_bitcoinish_network network = create_bitcoinish_network( network_name="Litecoin", symbol="LTC", subnet_name="mainnet", - wif_prefix_hex="b0", sec_prefix="LTCSEC:", address_prefix_hex="30", pay_to_script_prefix_hex="05", + wif_prefix_hex="b0", sec_prefix="LTCSEC:", address_prefix_hex="30", pay_to_script_prefix_hex="32", bip32_prv_prefix_hex="019d9cfe", bip32_pub_prefix_hex="019da462", bech32_hrp="ltc")
richardkiss/pycoin
bd9491fd4cfa7285a695f52d7964ecc72afa3763
diff --git a/tests/cmds/test_cases/ku/bip32_subpaths_ltc.txt b/tests/cmds/test_cases/ku/bip32_subpaths_ltc.txt index dcbac64..5f77114 100644 --- a/tests/cmds/test_cases/ku/bip32_subpaths_ltc.txt +++ b/tests/cmds/test_cases/ku/bip32_subpaths_ltc.txt @@ -15,7 +15,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "0378a0d972953591dcf8f6220a0e1e5a2291b0a503604095d64a1e046ec8c0bfa8", "key_pair_as_sec_uncompressed": "0478a0d972953591dcf8f6220a0e1e5a2291b0a503604095d64a1e046ec8c0bfa81e81dde9b0926b2b0587286684670938d0f995a00b11bd1cf78320c38f7da863", "network": "Litecoin mainnet", - "p2sh_segwit": "3ELJbuAHwifoBaCWExbJcy5t9Za1PLjEzB", + "p2sh_segwit": "MLYSunaFtqXDz5UQLqaeScLHUGATNq7ibZ", "p2sh_segwit_script": "0014639c2e98539808eb087fa64543efc4dd7aaa5e4e", "parent_fingerprint": "5d353a2e", "private_key": "yes", @@ -49,7 +49,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "0342009b6607d46faa21abd7e71ecc8fa83b5f9add661aba2af65e997fb7f107e0", "key_pair_as_sec_uncompressed": "0442009b6607d46faa21abd7e71ecc8fa83b5f9add661aba2af65e997fb7f107e02735caaecc69ac891afbe2cc61a2f163c5f437bbdf8674c1dbbe34e9e3c67b7f", "network": "Litecoin mainnet", - "p2sh_segwit": "3MGZvnJLZfAzEo1kiS45W6EpcHWhzzFSM8", + "p2sh_segwit": "MTUiEfiJWn2R3JHepK3RKjVDvz79zx6nbx", "p2sh_segwit_script": "0014f39a290b7a6ff88c8c61cecc9a8e7b742a23ef6e", "parent_fingerprint": "5d353a2e", "private_key": "yes", @@ -83,7 +83,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "032a881c9182821c7153663572cb657cdaa69128f555bec8982d443f427c717f39", "key_pair_as_sec_uncompressed": "042a881c9182821c7153663572cb657cdaa69128f555bec8982d443f427c717f396a45e73f0b46c4d431b054b99cda747608950a1dbbc17d2c59439f558a822d71", "network": "Litecoin mainnet", - "p2sh_segwit": "3BEmuNdXqK5XdG4g5Ypz8XUTJc2hSRbE9N", + "p2sh_segwit": "MHSvDG3VnRvxRmLaBRpKxAirdJd9NQ9Ckf", "p2sh_segwit_script": "00149c6b340312237006369bba466eb846ff3b5c62f5", "parent_fingerprint": "5d353a2e", "private_key": "yes", @@ -117,7 +117,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "02288828380f4a40619ab1c54f7490f52306835e7bd5e8c540f884f9f4e3157171", "key_pair_as_sec_uncompressed": "04288828380f4a40619ab1c54f7490f52306835e7bd5e8c540f884f9f4e3157171e1b22857caa0aeff5067a0f20acdc3d2d5aca73db7f0a7b2049faaa439677ba0", "network": "Litecoin mainnet", - "p2sh_segwit": "3KRpSzFGdEr1me3ApDurGUKbSXtF7NP728", + "p2sh_segwit": "MRdxksfEaMhSa9K4v6uC67ZzmEUh89FD5e", "p2sh_segwit_script": "00141e71ebce1b3f50ecd78b44598dab4351ae426a20", "parent_fingerprint": "5d353a2e", "private_key": "yes", @@ -151,7 +151,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "02bc7c9c4b6a3944d3c8f9b1dc8fe362172a7dbe724aad6363c3f82910e41e1428", "key_pair_as_sec_uncompressed": "04bc7c9c4b6a3944d3c8f9b1dc8fe362172a7dbe724aad6363c3f82910e41e14287ea63b21525757e89a6b7ef3ec2b9714bdaafc46b1cabf8fe46e9ae2c841a754", "network": "Litecoin mainnet", - "p2sh_segwit": "32LXf368At98ibdWwLrW6pJt5PBXq9QTVo", + "p2sh_segwit": "M8YfxvW67zzZX6uR3DqqvTZHQ5myui1FeA", "p2sh_segwit_script": "0014ef264fe68474d1955d41d2e0645f2df88f569739", "parent_fingerprint": "5d353a2e", "private_key": "yes", @@ -185,7 +185,7 @@ ku -n LTC -j P:foo -s 5-10 "key_pair_as_sec": "026f2ac6865005d4e6c1e6605d4fb3d67df4ceabd582aa84d98e668c2cbbeac6cc", "key_pair_as_sec_uncompressed": "046f2ac6865005d4e6c1e6605d4fb3d67df4ceabd582aa84d98e668c2cbbeac6cc062011ce1d912338c1c3ed6ed64f7b566bebd22eb6c1865a7e34f7628171beea", "network": "Litecoin mainnet", - "p2sh_segwit": "33xCsFEYVijkrQkynb9gfsJEkLZRudGnUr", + "p2sh_segwit": "MAAMB8eWSqbBev2stU92VWYe539stALF7d", "p2sh_segwit_script": "00147d423c8fb2af77053c30219f6257dbfa0737ba0d", "parent_fingerprint": "5d353a2e", "private_key": "yes",
LTC p2sh address prefix `3` vs `M` I noticed that the address prefix for LTC results in the old `3` address format. Would a patch to change that to the new `M` format be welcome?
0.0
bd9491fd4cfa7285a695f52d7964ecc72afa3763
[ "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_ltc_txt" ]
[ "tests/address_for_script_test.py::BTCTests::test_issue_225", "tests/address_for_script_test.py::BTCTests::test_script_type_pay_to_address", "tests/address_for_script_test.py::BTCTests::test_script_type_pay_to_public_pair", "tests/address_for_script_test.py::BTCTests::test_solve_pay_to_address", "tests/address_for_script_test.py::BTCTests::test_solve_pay_to_public_pair", "tests/address_for_script_test.py::BTCTests::test_weird_tx", "tests/address_for_script_test.py::LTCTests::test_issue_225", "tests/address_for_script_test.py::LTCTests::test_script_type_pay_to_address", "tests/address_for_script_test.py::LTCTests::test_script_type_pay_to_public_pair", "tests/address_for_script_test.py::LTCTests::test_solve_pay_to_address", "tests/address_for_script_test.py::LTCTests::test_solve_pay_to_public_pair", "tests/address_for_script_test.py::LTCTests::test_weird_tx", "tests/address_for_script_test.py::BCHTests::test_issue_225", "tests/address_for_script_test.py::BCHTests::test_script_type_pay_to_address", "tests/address_for_script_test.py::BCHTests::test_script_type_pay_to_public_pair", "tests/address_for_script_test.py::BCHTests::test_solve_pay_to_address", "tests/address_for_script_test.py::BCHTests::test_solve_pay_to_public_pair", "tests/address_for_script_test.py::BCHTests::test_weird_tx", "tests/annotate_test.py::BTCTests::test_disassemble", "tests/annotate_test.py::BTCTests::test_validate", "tests/blockchain_test.py::BlockchainTestCase::test_basic", "tests/blockchain_test.py::BlockchainTestCase::test_callback", "tests/blockchain_test.py::BlockchainTestCase::test_chain_locking", "tests/blockchain_test.py::BlockchainTestCase::test_fork", "tests/blockchain_test.py::BlockchainTestCase::test_large", "tests/bloomfilter_test.py::BloomFilterTest::test_BloomFilter", "tests/bloomfilter_test.py::BloomFilterTest::test_filter_size_required", "tests/bloomfilter_test.py::BloomFilterTest::test_hash_function_count_required", "tests/bloomfilter_test.py::BloomFilterTest::test_murmur3", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_00_0e1b5688cf179cd9f7cbda1fac0090f6e684bbf8cd946660120197c3f3681809", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_01_e41ffe19dff3cbedb413a2ca3fbbcd05cb7fd7397ffa65052f8928aa9c700092", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_02_105ea4dcace3714519c3f03a2c5df38c8771d09a946995ad18466f5e4c399a87", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_03_e41ffe19dff3cbedb413a2ca3fbbcd05cb7fd7397ffa65052f8928aa9c700092", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_04_99517e5b47533453cc7daa332180f578be68b80370ecfe84dbfff7f19d791da4", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_05_743a2ad1d24538ed70bd4bab37fda6e2b0424459872bebbd2178d9e1352a5f78", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_06_0ea8dd5d0a5d36350fc1ed1ade25df63c6dc98f966b7b0546335bd966bfe3399", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_07_b9092b169f356d64f6c8f034d776cf0df52e1b2ca9f4f2c50044aa2a4fbeabf8", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_08_477b2849d66373399261510f140ff0058f09439ba38a24cc8e963cfe7290fd02", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_09_6a6b568d403db6c0ff04d018035d406280f283f023726718e63411abe4d31363", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_10_bf93c6fe89592b2508f2876c6200d5ffadbd741e18c57b5e9fe5eff3101137b3", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_11_d12fb29f9b00aaa9e89f5c34a27f43dd73f729aa796b36da0738b97f00587d0b", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_12_a87439547de75492b9fa7299b0ba1cf729c2ae53e84979bb713175171e93fe74", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_13_2d3f5c65b0ae97f5f52bef7f3b9c8ffeaeed0957289b5750a1c75bf30dd4493a", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_14_b4237d9907e68bbc9b3b8de481c8f3731118cf5474a17a806c9bd0c7bf292a7d", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_15_c36efe11c9f2d854c1111f01fc4ba644935e4dbc7fec7748921e64d0fdc18d73", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_16_b0e0ac51030e16ad2054fc43043798f0558f24bf6a5928784676f3339400c0f8", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_17_0fc0414e99bd508a7131e4f1539f5965c77b0b697db5b97c8542cddf37b0a2d8", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_18_da94fda32b55deb40c3ed92e135d69df7efc4ee6665e0beb07ef500f407c9fd2", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_19_f76f897b206e4f78d60fe40f2ccb542184cfadc34354d3bb9bdc30cc2f432b86", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_20_b0e0ac51030e16ad2054fc43043798f0558f24bf6a5928784676f3339400c0f8", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_21_3e7fb893bfd7a2fe99ffe286765e5e46055f805d41954a231ad4f313e98f73e0", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_22_472a87e8d3f992fe389f68712b94c9d927bf0fa7ec177f65b3dd787f8fbf94d2", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_23_c4070d94c05d40c96bc093f9403c3cd7085bdf006feb010e355235d6a12fdbd3", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_24_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_25_e04e6b846eb4a92ae1b1201bca26983b12269e4eb4c852c9738188db9cbe652b", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_26_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_27_1b9aef851895b93c62c29fbd6ca4d45803f4007eff266e2f96ff11e9b6ef197b", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_28_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_29_292cdc216d99c2ed6900807b3ff092c62ac4d64b6ff4e18dff502d44f32bc19c", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_30_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_31_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_32_4c6f0ef2b94ca36143789ce0de089ed5d97585d2f6dc30b7531eec27f0c20e65", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_33_bbe101db29576d8efd1cc5f58f74f7dc735f99489176947b02b4edd22870ea86", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_34_470e955d44f606f9c922e48f9cbcf96198bb7d4a145037c075381d7eba3a5431", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_35_bfb75abf6ab373fb9b81810f6ebe665e370521e6ca7d58e6449e88ceec2236b2", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_36_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_37_9950aa8756896bb6bd358e27aeb0f68f499954ed2f2ad1f335647224a09a602f", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_38_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_39_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_40_abd62b4627d8d9b2d95fcfd8c87e37d2790637ce47d28018e3aece63c1d62649", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_41_5f99c0abf511294d76cbe144d86b77238a03e086974bc7a8ea0bdb2c681a0324", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_42_1376be1799f72b1b3237333f25f7a699f2b3ec194be2242d1694f2760d022452", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_43_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_44_4d5f21e47c4bb7d82e07205fff66ac97c3ff7cbf7ff4a67ba86cfa55a740d9d5", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_45_9cbbcd670120795028be95a438c5b1d382ada41134f09347be056aae7605a046", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_46_50a1e0e6a134a564efa078e3bd088e7e8777c2c0aec10a752fd8706470103b89", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_47_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_48_b6a7adfd212fa9a26ad163d44c77ceb349e3931b53d8736b6cd559d0a3e18d57", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_49_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_50_b6a7adfd212fa9a26ad163d44c77ceb349e3931b53d8736b6cd559d0a3e18d57", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_51_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_52_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_53_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_54_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_55_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_56_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_57_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_58_f335864f7c12ec7946d2c123deb91eb978574b647af125a414262380c7fbd55c", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_59_1bef57d4fd520ca3509032fe77891cdfcfeccdffb0014858d1f13847c4a5701c", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_60_5b4bf8a6a0a93d9cea79e2ea25891f4a531e0f1c0c5f2933dda6356d145080d0", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_61_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_62_21e5c172ce9a7dc609ef695f400add2423b729c88c6d9074ace66ae74285f835", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_63_7c08a738416e6580e7c943ac52a8b99f8043e640b838af041ecea56e54e7026a", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_64_5e71b48f11542df3244f2ef76d4c2f3d60278eb33ecabb62eaf7aa7c39dff2ba", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_65_aca1909468705b5b56853fbe68f2973f3f8b980287e91f05195a0b8446144a49", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_66_c7e1402f6f591d50855b73dac51434e44679b2a3b8e7ae2bf239724df2fd30c1", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_67_cc2ade5b770f1a8caf16e382bef24e62b22a37cbcead3f3ef381dbb899b8e0de", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_68_80e6efadea2cb9d48774e708e258896e21b557547e90a6fd6732ef75edd31ab2", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_69_eb800ec3c792455e4b8e6ea34debc9e3e0483fb57bbf612efea6432f3d61f1e5", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_70_c04712aaf47b9f4e699646c50ee48d9fe8664da50459fe7f5653110a98bde05c", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_71_4903bb9737b9d535cb5aa30e83212a8821eb4fa4255988d5ba0b336833689bd1", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_72_48cce87c22eedc1293d345739c19974e80e7b398a7d626c110ec27b650d7b4a5", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_73_c000024b69ca96e1b7aa5d6c439aa53a9d455dc59f914e2630e04df620c1860f", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_74_b31cfc54902a82431265124b97f5be645db5d89fa8c13b1069ff70cb83591c0e", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_75_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_76_d30327484c830549ce97a7d4ab0b1156cc41b4632f05f6cd397f5474e4ef47ce", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_77_bb38de1659b39765b2e8bb03e53be88383fcc126f71004255b328be4d5d41d85", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_78_2349b70c54724875fec1664dd4e5a8ef5ab566429a985c74d7534917b41d95dc", "tests/btc/bc_transaction_test.py::TestTx::test_invalid_79_b933822a5fc7dd6cdc0a2a854713037dba36e66448b83e6fae109c1c74bfc778", "tests/btc/bc_transaction_test.py::TestTx::test_valid_00_23b397edccd3740a74adb603c9756370fafcde9bcc4483eb271ecad09a94dd63", "tests/btc/bc_transaction_test.py::TestTx::test_valid_01_fcabc409d8e685da28536e1e5ccc91264d755cd4c57ed4cae3dbaa4d3b93e8ed", "tests/btc/bc_transaction_test.py::TestTx::test_valid_02_c9aa95f2c48175fdb70b34c23f1c3fc44f869b073a6f79b1343fbce30c3cb575", "tests/btc/bc_transaction_test.py::TestTx::test_valid_03_da94fda32b55deb40c3ed92e135d69df7efc4ee6665e0beb07ef500f407c9fd2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_04_f76f897b206e4f78d60fe40f2ccb542184cfadc34354d3bb9bdc30cc2f432b86", "tests/btc/bc_transaction_test.py::TestTx::test_valid_05_c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73", "tests/btc/bc_transaction_test.py::TestTx::test_valid_06_e41ffe19dff3cbedb413a2ca3fbbcd05cb7fd7397ffa65052f8928aa9c700092", "tests/btc/bc_transaction_test.py::TestTx::test_valid_07_e41ffe19dff3cbedb413a2ca3fbbcd05cb7fd7397ffa65052f8928aa9c700092", "tests/btc/bc_transaction_test.py::TestTx::test_valid_08_f7fdd091fa6d8f5e7a8c2458f5c38faffff2d3f1406b6e4fe2c99dcc0d2d1cbb", "tests/btc/bc_transaction_test.py::TestTx::test_valid_09_b56471690c3ff4f7946174e51df68b47455a0d29344c351377d712e6d00eabe5", "tests/btc/bc_transaction_test.py::TestTx::test_valid_100_cdbfe209d9856d491c5d32947b0b8b2837126968755dc60333c755bbfc2b9ce2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_101_9d11076c372c9631d0b4390c594257b123d65e8a355af53606cda17c7c1d984b", "tests/btc/bc_transaction_test.py::TestTx::test_valid_102_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_valid_103_41324397e2a7a932b41af67f37d35550e6fdde5ab12334c5640f8bee892eba24", "tests/btc/bc_transaction_test.py::TestTx::test_valid_104_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_valid_105_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_valid_106_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_valid_107_2b1e44fff489d09091e5e20f9a01bbc0e8d80f0662e629fd10709cdb4922a874", "tests/btc/bc_transaction_test.py::TestTx::test_valid_108_fecccdb9be1081bf587fc39e3a7c9fcc4eb47782a485e7642f9f0fc2504d19dc", "tests/btc/bc_transaction_test.py::TestTx::test_valid_109_f911f7a3e4e3793c874452b4584f0381604744ae2c0f945da5c041f00d5f52a2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_10_3126674c647f568f0acf8b455cca41d4a3d324ddd36560d31c9e9752fceb7010", "tests/btc/bc_transaction_test.py::TestTx::test_valid_110_98229b70948f1c17851a541f1fe532bf02c408267fecf6d7e174c359ae870654", "tests/btc/bc_transaction_test.py::TestTx::test_valid_111_dbff04c7044a569f179c843e929449f6a24be183e42c66be9032f1c9eaaf5811", "tests/btc/bc_transaction_test.py::TestTx::test_valid_112_6e4dd6473b52c00afec3af31b4a522eb9b51489683ce407a6c403313a0caa7a9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_113_a8c30f28b7d3fba4cc292992f42721fdfe1729c8c418055992052a65a04f9651", "tests/btc/bc_transaction_test.py::TestTx::test_valid_114_65dab5dd46a501fc695822c73d779067f2feb7c49dc47d39f86fdb2e3960b3bd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_115_22d020638e3b7e1f2f9a63124ac76f5e333c74387862e3675f64b25e960d3641", "tests/btc/bc_transaction_test.py::TestTx::test_valid_116_651431f85e6e1ea3603d7e6a9e8e5966eab659fad5261882ae6232b845f35443", "tests/btc/bc_transaction_test.py::TestTx::test_valid_117_1aebf0c98f01381765a8c33d688f8903e4d01120589ac92b78f1185dc1f4119c", "tests/btc/bc_transaction_test.py::TestTx::test_valid_118_f73766431eac4f2c52c0be14ee74b4b65dca03c94daf31bba34d8cc0226402aa", "tests/btc/bc_transaction_test.py::TestTx::test_valid_119_c13178fedb9b03990404d2048831c8800d7e6636daa60c72ab1c7a2267fb4c51", "tests/btc/bc_transaction_test.py::TestTx::test_valid_11_99517e5b47533453cc7daa332180f578be68b80370ecfe84dbfff7f19d791da4", "tests/btc/bc_transaction_test.py::TestTx::test_valid_12_ab097537b528871b9b64cb79a769ae13c3c3cd477cc9dddeebe657eabd7fdcea", "tests/btc/bc_transaction_test.py::TestTx::test_valid_13_4d163e00f1966e9a1eab8f9374c3e37f4deb4857c247270e25f7d79a999d2dc9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_14_9fe2ef9dde70e15d78894a4800b7df3bbfb1addb9a6f7d7c204492fdb6ee6cc4", "tests/btc/bc_transaction_test.py::TestTx::test_valid_15_99d3825137602e577aeaf6a2e3c9620fd0e605323dc5265da4a570593be791d4", "tests/btc/bc_transaction_test.py::TestTx::test_valid_16_c0d67409923040cc766bbea12e4c9154393abef706db065ac2e07d91a9ba4f84", "tests/btc/bc_transaction_test.py::TestTx::test_valid_17_c610d85d3d5fdf5046be7f123db8a0890cee846ee58de8a44667cfd1ab6b8666", "tests/btc/bc_transaction_test.py::TestTx::test_valid_18_a647a7b3328d2c698bfa1ee2dd4e5e05a6cea972e764ccb9bd29ea43817ca64f", "tests/btc/bc_transaction_test.py::TestTx::test_valid_19_afd9c17f8913577ec3509520bd6e5d63e9c0fd2a5f70c787993b097ba6ca9fae", "tests/btc/bc_transaction_test.py::TestTx::test_valid_20_ddc454a1c0c35c188c98976b17670f69e586d9c0f3593ea879928332f0a069e7", "tests/btc/bc_transaction_test.py::TestTx::test_valid_21_f4b05f978689c89000f729cae187dcfbe64c9819af67a4f05c0b4d59e717d64d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_22_cc60b1f899ec0a69b7c3f25ddf32c4524096a9c5b01cbd84c6d0312a0c478984", "tests/btc/bc_transaction_test.py::TestTx::test_valid_23_1edc7f214659d52c731e2016d258701911bd62a0422f72f6c87a1bc8dd3f8667", "tests/btc/bc_transaction_test.py::TestTx::test_valid_24_018adb7133fde63add9149a2161802a1bcf4bdf12c39334e880c073480eda2ff", "tests/btc/bc_transaction_test.py::TestTx::test_valid_25_1464caf48c708a6cc19a296944ded9bb7f719c9858986d2501cf35068b9ce5a2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_26_1fb73fbfc947d52f5d80ba23b67c06a232ad83fdd49d1c0a657602f03fbe8f7a", "tests/btc/bc_transaction_test.py::TestTx::test_valid_27_24cecfce0fa880b09c9b4a66c5134499d1b09c01cc5728cd182638bea070e6ab", "tests/btc/bc_transaction_test.py::TestTx::test_valid_28_9eaa819e386d6a54256c9283da50c230f3d8cd5376d75c4dcc945afdeb157dd7", "tests/btc/bc_transaction_test.py::TestTx::test_valid_29_46224764c7870f95b58f155bce1e38d4da8e99d42dbb632d0dd7c07e092ee5aa", "tests/btc/bc_transaction_test.py::TestTx::test_valid_30_8d66836045db9f2d7b3a75212c5e6325f70603ee27c8333a3bce5bf670d9582e", "tests/btc/bc_transaction_test.py::TestTx::test_valid_31_aab7ef280abbb9cc6fbaf524d2645c3daf4fcca2b3f53370e618d9cedf65f1f8", "tests/btc/bc_transaction_test.py::TestTx::test_valid_32_6327783a064d4e350c454ad5cd90201aedf65b1fc524e73709c52f0163739190", "tests/btc/bc_transaction_test.py::TestTx::test_valid_33_892464645599cc3c2d165adcc612e5f982a200dfaa3e11e9ce1d228027f46880", "tests/btc/bc_transaction_test.py::TestTx::test_valid_34_578db8c6c404fec22c4a8afeaf32df0e7b767c4dda3478e0471575846419e8fc", "tests/btc/bc_transaction_test.py::TestTx::test_valid_35_974f5148a0946f9985e75a240bb24c573adbbdc25d61e7b016cdbb0a5355049f", "tests/btc/bc_transaction_test.py::TestTx::test_valid_36_b0097ec81df231893a212657bf5fe5a13b2bff8b28c0042aca6fc4159f79661b", "tests/btc/bc_transaction_test.py::TestTx::test_valid_37_feeba255656c80c14db595736c1c7955c8c0a497622ec96e3f2238fbdd43a7c9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_38_a0c984fc820e57ddba97f8098fa640c8a7eb3fe2f583923da886b7660f505e1e", "tests/btc/bc_transaction_test.py::TestTx::test_valid_39_5df1375ffe61ac35ca178ebb0cab9ea26dedbd0e96005dfcee7e379fa513232f", "tests/btc/bc_transaction_test.py::TestTx::test_valid_40_ded7ff51d89a4e1ec48162aee5a96447214d93dfb3837946af2301a28f65dbea", "tests/btc/bc_transaction_test.py::TestTx::test_valid_41_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_valid_42_abd62b4627d8d9b2d95fcfd8c87e37d2790637ce47d28018e3aece63c1d62649", "tests/btc/bc_transaction_test.py::TestTx::test_valid_43_abd62b4627d8d9b2d95fcfd8c87e37d2790637ce47d28018e3aece63c1d62649", "tests/btc/bc_transaction_test.py::TestTx::test_valid_44_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_valid_45_5f99c0abf511294d76cbe144d86b77238a03e086974bc7a8ea0bdb2c681a0324", "tests/btc/bc_transaction_test.py::TestTx::test_valid_46_5f99c0abf511294d76cbe144d86b77238a03e086974bc7a8ea0bdb2c681a0324", "tests/btc/bc_transaction_test.py::TestTx::test_valid_47_25d35877eaba19497710666473c50d5527d38503e3521107a3fc532b74cd7453", "tests/btc/bc_transaction_test.py::TestTx::test_valid_48_58b6de8413603b7f556270bf48caedcf17772e7105f5419f6a80be0df0b470da", "tests/btc/bc_transaction_test.py::TestTx::test_valid_49_1b9aef851895b93c62c29fbd6ca4d45803f4007eff266e2f96ff11e9b6ef197b", "tests/btc/bc_transaction_test.py::TestTx::test_valid_50_3444be2e216abe77b46015e481d8cc21abd4c20446aabf49cd78141c9b9db87e", "tests/btc/bc_transaction_test.py::TestTx::test_valid_51_f53761038a728b1f17272539380d96e93f999218f8dcb04a8469b523445cd0fd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_52_d193f0f32fceaf07bb25c897c8f99ca6f69a52f6274ca64efc2a2e180cb97fc1", "tests/btc/bc_transaction_test.py::TestTx::test_valid_53_50a1e0e6a134a564efa078e3bd088e7e8777c2c0aec10a752fd8706470103b89", "tests/btc/bc_transaction_test.py::TestTx::test_valid_54_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_valid_55_f335864f7c12ec7946d2c123deb91eb978574b647af125a414262380c7fbd55c", "tests/btc/bc_transaction_test.py::TestTx::test_valid_56_d1edbcde44691e98a7b7f556bd04966091302e29ad9af3c2baac38233667e0d2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_57_d1edbcde44691e98a7b7f556bd04966091302e29ad9af3c2baac38233667e0d2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_58_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_valid_59_bffda23e40766d292b0510a1b556453c558980c70c94ab158d8286b3413e220d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_60_01a86c65460325dc6699714d26df512a62a854a669f6ed2e6f369a238e048cfd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_61_01a86c65460325dc6699714d26df512a62a854a669f6ed2e6f369a238e048cfd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_62_f6d2359c5de2d904e10517d23e7c8210cca71076071bbf46de9fbd5f6233dbf1", "tests/btc/bc_transaction_test.py::TestTx::test_valid_63_f6d2359c5de2d904e10517d23e7c8210cca71076071bbf46de9fbd5f6233dbf1", "tests/btc/bc_transaction_test.py::TestTx::test_valid_64_19c2b7377229dae7aa3e50142a32fd37cef7171a01682f536e9ffa80c186f6c9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_65_19c2b7377229dae7aa3e50142a32fd37cef7171a01682f536e9ffa80c186f6c9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_66_c9dda3a24cc8a5acb153d1085ecd2fecf6f87083122f8cdecc515b1148d4c40d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_67_c9dda3a24cc8a5acb153d1085ecd2fecf6f87083122f8cdecc515b1148d4c40d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_68_d1edbcde44691e98a7b7f556bd04966091302e29ad9af3c2baac38233667e0d2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_69_01a86c65460325dc6699714d26df512a62a854a669f6ed2e6f369a238e048cfd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_70_c9dda3a24cc8a5acb153d1085ecd2fecf6f87083122f8cdecc515b1148d4c40d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_71_d1edbcde44691e98a7b7f556bd04966091302e29ad9af3c2baac38233667e0d2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_72_01a86c65460325dc6699714d26df512a62a854a669f6ed2e6f369a238e048cfd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_73_c9dda3a24cc8a5acb153d1085ecd2fecf6f87083122f8cdecc515b1148d4c40d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_74_d1edbcde44691e98a7b7f556bd04966091302e29ad9af3c2baac38233667e0d2", "tests/btc/bc_transaction_test.py::TestTx::test_valid_75_01a86c65460325dc6699714d26df512a62a854a669f6ed2e6f369a238e048cfd", "tests/btc/bc_transaction_test.py::TestTx::test_valid_76_c9dda3a24cc8a5acb153d1085ecd2fecf6f87083122f8cdecc515b1148d4c40d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_77_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_valid_78_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_valid_79_f335864f7c12ec7946d2c123deb91eb978574b647af125a414262380c7fbd55c", "tests/btc/bc_transaction_test.py::TestTx::test_valid_80_e2207d1aaf6b74e5d98c2fa326d2dc803b56b30a3f90ce779fa5edb762f38755", "tests/btc/bc_transaction_test.py::TestTx::test_valid_81_3a13e1b6371c545147173cc4055f0ed73686a9f73f092352fb4b39ca27d360e6", "tests/btc/bc_transaction_test.py::TestTx::test_valid_82_4b5e0aae1251a9dc66b4d5f483f1879bf518ea5e1765abc5a9f2084b43ed1ea7", "tests/btc/bc_transaction_test.py::TestTx::test_valid_83_5f16eb3ca4581e2dfb46a28140a4ee15f85e4e1c032947da8b93549b53c105f5", "tests/btc/bc_transaction_test.py::TestTx::test_valid_84_7944c8f36d682addda15124399bf954ec5d4b3a426e9d505a5f74a08644f0ebb", "tests/btc/bc_transaction_test.py::TestTx::test_valid_85_0df178d21afc9e8a46195c7c2e328aafd8544a1dbd67cf983214cad401966cf3", "tests/btc/bc_transaction_test.py::TestTx::test_valid_86_3905c86c73a5e08428ca61c8bb1a89a12c081778f337552b6a59184114c56cfa", "tests/btc/bc_transaction_test.py::TestTx::test_valid_87_466e55c43eae0d39f55190d6a32b829cd207a7ec12fa63fe19928a7cd48f4f4f", "tests/btc/bc_transaction_test.py::TestTx::test_valid_88_3ef66c47b75e6eb302638672a93026dc8ddac231646324473f68f24b9f18cdc1", "tests/btc/bc_transaction_test.py::TestTx::test_valid_89_d92aeca6efc202adaa61a08f2c562d78ee7d8c6abbf3b0fdbc104aa44665df62", "tests/btc/bc_transaction_test.py::TestTx::test_valid_90_616406f9c5e1e40b55852a3c8a8e43bc49dadfc73b12fc3a6957b2e207c7dff7", "tests/btc/bc_transaction_test.py::TestTx::test_valid_91_0504a37327ec89cc1fed77765ea024f84f34a071778331822fd1080263dc3ff9", "tests/btc/bc_transaction_test.py::TestTx::test_valid_92_908100319352a2ad99c6a49a8ec0436916745b486c2ffe3fa8d3404a8e2d911d", "tests/btc/bc_transaction_test.py::TestTx::test_valid_93_63b258276ce048342df59f75e0a3ccec41f7b2b3e31afe9182fe4136d5f91461", "tests/btc/bc_transaction_test.py::TestTx::test_valid_94_5e71b48f11542df3244f2ef76d4c2f3d60278eb33ecabb62eaf7aa7c39dff2ba", "tests/btc/bc_transaction_test.py::TestTx::test_valid_95_fd721bfa1e4edf30cb164c40a667dfbedc6465b223300105d70954360ddb450e", "tests/btc/bc_transaction_test.py::TestTx::test_valid_96_16c556aa7fe426caa995158e281d0e7dd4086d313e983edded90556f2a483f35", "tests/btc/bc_transaction_test.py::TestTx::test_valid_97_146a86e8bd5ebc32fcf5771119fae30a5e02d2b84af5d7773ede4bb72b3d7ae3", "tests/btc/bc_transaction_test.py::TestTx::test_valid_98_cfa4bd0746de8f6b9e65b4efe65406d65b3e6c6310bf92842e08b8f7005a3655", "tests/btc/bc_transaction_test.py::TestTx::test_valid_99_7c08a738416e6580e7c943ac52a8b99f8043e640b838af041ecea56e54e7026a", "tests/btc/bip32_test.py::Bip0032TestCase::test_public_subkey", "tests/btc/bip32_test.py::Bip0032TestCase::test_repr", "tests/btc/bip32_test.py::Bip0032TestCase::test_streams", "tests/btc/bip32_test.py::Bip0032TestCase::test_testnet", "tests/btc/bip32_test.py::Bip0032TestCase::test_vector_1", "tests/btc/bip32_test.py::Bip0032TestCase::test_vector_2", "tests/btc/key_translation_test.py::KeyTranslationTest::test_translation", "tests/btc/parse_block_test.py::BlockTest::test_block", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_1", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_2", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_3", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_4", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_5", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_6", "tests/btc/segwit_test.py::SegwitTest::test_bip143_tx_7", "tests/btc/segwit_test.py::SegwitTest::test_issue_224", "tests/btc/segwit_test.py::SegwitTest::test_segwit_create_tx", "tests/btc/segwit_test.py::SegwitTest::test_segwit_ui", "tests/btc/vm_script_test.py::TestTx::test_scripts_000", "tests/btc/vm_script_test.py::TestTx::test_scripts_001", "tests/btc/vm_script_test.py::TestTx::test_scripts_002", "tests/btc/vm_script_test.py::TestTx::test_scripts_003", "tests/btc/vm_script_test.py::TestTx::test_scripts_004", "tests/btc/vm_script_test.py::TestTx::test_scripts_005", "tests/btc/vm_script_test.py::TestTx::test_scripts_006", "tests/btc/vm_script_test.py::TestTx::test_scripts_007", "tests/btc/vm_script_test.py::TestTx::test_scripts_008", "tests/btc/vm_script_test.py::TestTx::test_scripts_009", "tests/btc/vm_script_test.py::TestTx::test_scripts_010", "tests/btc/vm_script_test.py::TestTx::test_scripts_011", "tests/btc/vm_script_test.py::TestTx::test_scripts_012", "tests/btc/vm_script_test.py::TestTx::test_scripts_013", "tests/btc/vm_script_test.py::TestTx::test_scripts_014", "tests/btc/vm_script_test.py::TestTx::test_scripts_015", "tests/btc/vm_script_test.py::TestTx::test_scripts_016", "tests/btc/vm_script_test.py::TestTx::test_scripts_017", "tests/btc/vm_script_test.py::TestTx::test_scripts_018", "tests/btc/vm_script_test.py::TestTx::test_scripts_019", "tests/btc/vm_script_test.py::TestTx::test_scripts_020", "tests/btc/vm_script_test.py::TestTx::test_scripts_021", "tests/btc/vm_script_test.py::TestTx::test_scripts_022", "tests/btc/vm_script_test.py::TestTx::test_scripts_023", "tests/btc/vm_script_test.py::TestTx::test_scripts_024", "tests/btc/vm_script_test.py::TestTx::test_scripts_025", "tests/btc/vm_script_test.py::TestTx::test_scripts_026", "tests/btc/vm_script_test.py::TestTx::test_scripts_027", "tests/btc/vm_script_test.py::TestTx::test_scripts_028", "tests/btc/vm_script_test.py::TestTx::test_scripts_029", "tests/btc/vm_script_test.py::TestTx::test_scripts_030", "tests/btc/vm_script_test.py::TestTx::test_scripts_031", "tests/btc/vm_script_test.py::TestTx::test_scripts_032", "tests/btc/vm_script_test.py::TestTx::test_scripts_033", "tests/btc/vm_script_test.py::TestTx::test_scripts_034", "tests/btc/vm_script_test.py::TestTx::test_scripts_035", "tests/btc/vm_script_test.py::TestTx::test_scripts_036", "tests/btc/vm_script_test.py::TestTx::test_scripts_037", "tests/btc/vm_script_test.py::TestTx::test_scripts_038", "tests/btc/vm_script_test.py::TestTx::test_scripts_039", "tests/btc/vm_script_test.py::TestTx::test_scripts_040", "tests/btc/vm_script_test.py::TestTx::test_scripts_041", "tests/btc/vm_script_test.py::TestTx::test_scripts_042", "tests/btc/vm_script_test.py::TestTx::test_scripts_043", "tests/btc/vm_script_test.py::TestTx::test_scripts_044", "tests/btc/vm_script_test.py::TestTx::test_scripts_045", "tests/btc/vm_script_test.py::TestTx::test_scripts_046", "tests/btc/vm_script_test.py::TestTx::test_scripts_047", "tests/btc/vm_script_test.py::TestTx::test_scripts_048", "tests/btc/vm_script_test.py::TestTx::test_scripts_049", "tests/btc/vm_script_test.py::TestTx::test_scripts_050", "tests/btc/vm_script_test.py::TestTx::test_scripts_051", "tests/btc/vm_script_test.py::TestTx::test_scripts_052", "tests/btc/vm_script_test.py::TestTx::test_scripts_053", "tests/btc/vm_script_test.py::TestTx::test_scripts_054", "tests/btc/vm_script_test.py::TestTx::test_scripts_055", "tests/btc/vm_script_test.py::TestTx::test_scripts_056", "tests/btc/vm_script_test.py::TestTx::test_scripts_057", "tests/btc/vm_script_test.py::TestTx::test_scripts_058", "tests/btc/vm_script_test.py::TestTx::test_scripts_059", "tests/btc/vm_script_test.py::TestTx::test_scripts_060", "tests/btc/vm_script_test.py::TestTx::test_scripts_061", "tests/btc/vm_script_test.py::TestTx::test_scripts_062", "tests/btc/vm_script_test.py::TestTx::test_scripts_063", "tests/btc/vm_script_test.py::TestTx::test_scripts_064", "tests/btc/vm_script_test.py::TestTx::test_scripts_065", "tests/btc/vm_script_test.py::TestTx::test_scripts_066", "tests/btc/vm_script_test.py::TestTx::test_scripts_067", "tests/btc/vm_script_test.py::TestTx::test_scripts_068", "tests/btc/vm_script_test.py::TestTx::test_scripts_069", "tests/btc/vm_script_test.py::TestTx::test_scripts_070", "tests/btc/vm_script_test.py::TestTx::test_scripts_071", "tests/btc/vm_script_test.py::TestTx::test_scripts_072", "tests/btc/vm_script_test.py::TestTx::test_scripts_073", "tests/btc/vm_script_test.py::TestTx::test_scripts_074", "tests/btc/vm_script_test.py::TestTx::test_scripts_075", "tests/btc/vm_script_test.py::TestTx::test_scripts_076", "tests/btc/vm_script_test.py::TestTx::test_scripts_077", "tests/btc/vm_script_test.py::TestTx::test_scripts_078", "tests/btc/vm_script_test.py::TestTx::test_scripts_079", "tests/btc/vm_script_test.py::TestTx::test_scripts_080", "tests/btc/vm_script_test.py::TestTx::test_scripts_081", "tests/btc/vm_script_test.py::TestTx::test_scripts_082", "tests/btc/vm_script_test.py::TestTx::test_scripts_083", "tests/btc/vm_script_test.py::TestTx::test_scripts_084", "tests/btc/vm_script_test.py::TestTx::test_scripts_085", "tests/btc/vm_script_test.py::TestTx::test_scripts_086", "tests/btc/vm_script_test.py::TestTx::test_scripts_087", "tests/btc/vm_script_test.py::TestTx::test_scripts_088", "tests/btc/vm_script_test.py::TestTx::test_scripts_089", "tests/btc/vm_script_test.py::TestTx::test_scripts_090", "tests/btc/vm_script_test.py::TestTx::test_scripts_091", "tests/btc/vm_script_test.py::TestTx::test_scripts_092", "tests/btc/vm_script_test.py::TestTx::test_scripts_093", "tests/btc/vm_script_test.py::TestTx::test_scripts_094", "tests/btc/vm_script_test.py::TestTx::test_scripts_095", "tests/btc/vm_script_test.py::TestTx::test_scripts_096", "tests/btc/vm_script_test.py::TestTx::test_scripts_097", "tests/btc/vm_script_test.py::TestTx::test_scripts_098", "tests/btc/vm_script_test.py::TestTx::test_scripts_099", "tests/btc/vm_script_test.py::TestTx::test_scripts_100", "tests/btc/vm_script_test.py::TestTx::test_scripts_1000", "tests/btc/vm_script_test.py::TestTx::test_scripts_1001", "tests/btc/vm_script_test.py::TestTx::test_scripts_1002", "tests/btc/vm_script_test.py::TestTx::test_scripts_1003", "tests/btc/vm_script_test.py::TestTx::test_scripts_1004", "tests/btc/vm_script_test.py::TestTx::test_scripts_1005", "tests/btc/vm_script_test.py::TestTx::test_scripts_1006", "tests/btc/vm_script_test.py::TestTx::test_scripts_1007", "tests/btc/vm_script_test.py::TestTx::test_scripts_1008", "tests/btc/vm_script_test.py::TestTx::test_scripts_1009", "tests/btc/vm_script_test.py::TestTx::test_scripts_101", "tests/btc/vm_script_test.py::TestTx::test_scripts_1010", "tests/btc/vm_script_test.py::TestTx::test_scripts_1011", "tests/btc/vm_script_test.py::TestTx::test_scripts_1012", "tests/btc/vm_script_test.py::TestTx::test_scripts_1013", "tests/btc/vm_script_test.py::TestTx::test_scripts_1014", "tests/btc/vm_script_test.py::TestTx::test_scripts_1015", "tests/btc/vm_script_test.py::TestTx::test_scripts_1016", "tests/btc/vm_script_test.py::TestTx::test_scripts_1017", "tests/btc/vm_script_test.py::TestTx::test_scripts_1018", "tests/btc/vm_script_test.py::TestTx::test_scripts_1019", "tests/btc/vm_script_test.py::TestTx::test_scripts_102", "tests/btc/vm_script_test.py::TestTx::test_scripts_1020", "tests/btc/vm_script_test.py::TestTx::test_scripts_1021", "tests/btc/vm_script_test.py::TestTx::test_scripts_1022", "tests/btc/vm_script_test.py::TestTx::test_scripts_1023", "tests/btc/vm_script_test.py::TestTx::test_scripts_1024", "tests/btc/vm_script_test.py::TestTx::test_scripts_1025", "tests/btc/vm_script_test.py::TestTx::test_scripts_1026", "tests/btc/vm_script_test.py::TestTx::test_scripts_1027", "tests/btc/vm_script_test.py::TestTx::test_scripts_1028", "tests/btc/vm_script_test.py::TestTx::test_scripts_1029", "tests/btc/vm_script_test.py::TestTx::test_scripts_103", "tests/btc/vm_script_test.py::TestTx::test_scripts_1030", "tests/btc/vm_script_test.py::TestTx::test_scripts_1031", "tests/btc/vm_script_test.py::TestTx::test_scripts_1032", "tests/btc/vm_script_test.py::TestTx::test_scripts_1033", "tests/btc/vm_script_test.py::TestTx::test_scripts_1034", "tests/btc/vm_script_test.py::TestTx::test_scripts_1035", "tests/btc/vm_script_test.py::TestTx::test_scripts_1036", "tests/btc/vm_script_test.py::TestTx::test_scripts_1037", "tests/btc/vm_script_test.py::TestTx::test_scripts_1038", "tests/btc/vm_script_test.py::TestTx::test_scripts_1039", "tests/btc/vm_script_test.py::TestTx::test_scripts_104", "tests/btc/vm_script_test.py::TestTx::test_scripts_1040", "tests/btc/vm_script_test.py::TestTx::test_scripts_1041", "tests/btc/vm_script_test.py::TestTx::test_scripts_1042", "tests/btc/vm_script_test.py::TestTx::test_scripts_1043", "tests/btc/vm_script_test.py::TestTx::test_scripts_1044", "tests/btc/vm_script_test.py::TestTx::test_scripts_1045", "tests/btc/vm_script_test.py::TestTx::test_scripts_1046", "tests/btc/vm_script_test.py::TestTx::test_scripts_1047", "tests/btc/vm_script_test.py::TestTx::test_scripts_1048", "tests/btc/vm_script_test.py::TestTx::test_scripts_1049", "tests/btc/vm_script_test.py::TestTx::test_scripts_105", "tests/btc/vm_script_test.py::TestTx::test_scripts_1050", "tests/btc/vm_script_test.py::TestTx::test_scripts_1051", "tests/btc/vm_script_test.py::TestTx::test_scripts_1052", "tests/btc/vm_script_test.py::TestTx::test_scripts_1053", "tests/btc/vm_script_test.py::TestTx::test_scripts_1054", "tests/btc/vm_script_test.py::TestTx::test_scripts_1055", "tests/btc/vm_script_test.py::TestTx::test_scripts_1056", "tests/btc/vm_script_test.py::TestTx::test_scripts_1057", "tests/btc/vm_script_test.py::TestTx::test_scripts_1058", "tests/btc/vm_script_test.py::TestTx::test_scripts_1059", "tests/btc/vm_script_test.py::TestTx::test_scripts_106", "tests/btc/vm_script_test.py::TestTx::test_scripts_1060", "tests/btc/vm_script_test.py::TestTx::test_scripts_1061", "tests/btc/vm_script_test.py::TestTx::test_scripts_1062", "tests/btc/vm_script_test.py::TestTx::test_scripts_1063", "tests/btc/vm_script_test.py::TestTx::test_scripts_1064", "tests/btc/vm_script_test.py::TestTx::test_scripts_1065", "tests/btc/vm_script_test.py::TestTx::test_scripts_1066", "tests/btc/vm_script_test.py::TestTx::test_scripts_1067", "tests/btc/vm_script_test.py::TestTx::test_scripts_1068", "tests/btc/vm_script_test.py::TestTx::test_scripts_1069", "tests/btc/vm_script_test.py::TestTx::test_scripts_107", "tests/btc/vm_script_test.py::TestTx::test_scripts_1070", "tests/btc/vm_script_test.py::TestTx::test_scripts_1071", "tests/btc/vm_script_test.py::TestTx::test_scripts_1072", "tests/btc/vm_script_test.py::TestTx::test_scripts_1073", "tests/btc/vm_script_test.py::TestTx::test_scripts_1074", "tests/btc/vm_script_test.py::TestTx::test_scripts_1075", "tests/btc/vm_script_test.py::TestTx::test_scripts_1076", "tests/btc/vm_script_test.py::TestTx::test_scripts_1077", "tests/btc/vm_script_test.py::TestTx::test_scripts_1078", "tests/btc/vm_script_test.py::TestTx::test_scripts_1079", "tests/btc/vm_script_test.py::TestTx::test_scripts_108", "tests/btc/vm_script_test.py::TestTx::test_scripts_1080", "tests/btc/vm_script_test.py::TestTx::test_scripts_1081", "tests/btc/vm_script_test.py::TestTx::test_scripts_1082", "tests/btc/vm_script_test.py::TestTx::test_scripts_1083", "tests/btc/vm_script_test.py::TestTx::test_scripts_1084", "tests/btc/vm_script_test.py::TestTx::test_scripts_1085", "tests/btc/vm_script_test.py::TestTx::test_scripts_1086", "tests/btc/vm_script_test.py::TestTx::test_scripts_1087", "tests/btc/vm_script_test.py::TestTx::test_scripts_1088", "tests/btc/vm_script_test.py::TestTx::test_scripts_1089", "tests/btc/vm_script_test.py::TestTx::test_scripts_109", "tests/btc/vm_script_test.py::TestTx::test_scripts_1090", "tests/btc/vm_script_test.py::TestTx::test_scripts_1091", "tests/btc/vm_script_test.py::TestTx::test_scripts_1092", "tests/btc/vm_script_test.py::TestTx::test_scripts_1093", "tests/btc/vm_script_test.py::TestTx::test_scripts_1094", "tests/btc/vm_script_test.py::TestTx::test_scripts_1095", "tests/btc/vm_script_test.py::TestTx::test_scripts_1096", "tests/btc/vm_script_test.py::TestTx::test_scripts_1097", "tests/btc/vm_script_test.py::TestTx::test_scripts_1098", "tests/btc/vm_script_test.py::TestTx::test_scripts_1099", "tests/btc/vm_script_test.py::TestTx::test_scripts_110", "tests/btc/vm_script_test.py::TestTx::test_scripts_1100", "tests/btc/vm_script_test.py::TestTx::test_scripts_1101", "tests/btc/vm_script_test.py::TestTx::test_scripts_1102", "tests/btc/vm_script_test.py::TestTx::test_scripts_1103", "tests/btc/vm_script_test.py::TestTx::test_scripts_1104", "tests/btc/vm_script_test.py::TestTx::test_scripts_1105", "tests/btc/vm_script_test.py::TestTx::test_scripts_1106", "tests/btc/vm_script_test.py::TestTx::test_scripts_1107", "tests/btc/vm_script_test.py::TestTx::test_scripts_1108", "tests/btc/vm_script_test.py::TestTx::test_scripts_1109", "tests/btc/vm_script_test.py::TestTx::test_scripts_111", "tests/btc/vm_script_test.py::TestTx::test_scripts_1110", "tests/btc/vm_script_test.py::TestTx::test_scripts_1111", "tests/btc/vm_script_test.py::TestTx::test_scripts_1112", "tests/btc/vm_script_test.py::TestTx::test_scripts_1113", "tests/btc/vm_script_test.py::TestTx::test_scripts_1114", "tests/btc/vm_script_test.py::TestTx::test_scripts_1115", "tests/btc/vm_script_test.py::TestTx::test_scripts_1116", "tests/btc/vm_script_test.py::TestTx::test_scripts_1117", "tests/btc/vm_script_test.py::TestTx::test_scripts_1118", "tests/btc/vm_script_test.py::TestTx::test_scripts_1119", "tests/btc/vm_script_test.py::TestTx::test_scripts_112", "tests/btc/vm_script_test.py::TestTx::test_scripts_1120", "tests/btc/vm_script_test.py::TestTx::test_scripts_1121", "tests/btc/vm_script_test.py::TestTx::test_scripts_1122", "tests/btc/vm_script_test.py::TestTx::test_scripts_1123", "tests/btc/vm_script_test.py::TestTx::test_scripts_1124", "tests/btc/vm_script_test.py::TestTx::test_scripts_1125", "tests/btc/vm_script_test.py::TestTx::test_scripts_1126", "tests/btc/vm_script_test.py::TestTx::test_scripts_1127", "tests/btc/vm_script_test.py::TestTx::test_scripts_1128", "tests/btc/vm_script_test.py::TestTx::test_scripts_1129", "tests/btc/vm_script_test.py::TestTx::test_scripts_113", "tests/btc/vm_script_test.py::TestTx::test_scripts_1130", "tests/btc/vm_script_test.py::TestTx::test_scripts_1131", "tests/btc/vm_script_test.py::TestTx::test_scripts_1132", "tests/btc/vm_script_test.py::TestTx::test_scripts_1133", "tests/btc/vm_script_test.py::TestTx::test_scripts_1134", "tests/btc/vm_script_test.py::TestTx::test_scripts_1135", "tests/btc/vm_script_test.py::TestTx::test_scripts_1136", "tests/btc/vm_script_test.py::TestTx::test_scripts_1137", "tests/btc/vm_script_test.py::TestTx::test_scripts_1138", "tests/btc/vm_script_test.py::TestTx::test_scripts_1139", "tests/btc/vm_script_test.py::TestTx::test_scripts_114", "tests/btc/vm_script_test.py::TestTx::test_scripts_1140", "tests/btc/vm_script_test.py::TestTx::test_scripts_1141", "tests/btc/vm_script_test.py::TestTx::test_scripts_1142", "tests/btc/vm_script_test.py::TestTx::test_scripts_1143", "tests/btc/vm_script_test.py::TestTx::test_scripts_1144", "tests/btc/vm_script_test.py::TestTx::test_scripts_1145", "tests/btc/vm_script_test.py::TestTx::test_scripts_1146", "tests/btc/vm_script_test.py::TestTx::test_scripts_1147", "tests/btc/vm_script_test.py::TestTx::test_scripts_1148", "tests/btc/vm_script_test.py::TestTx::test_scripts_1149", "tests/btc/vm_script_test.py::TestTx::test_scripts_115", "tests/btc/vm_script_test.py::TestTx::test_scripts_1150", "tests/btc/vm_script_test.py::TestTx::test_scripts_1151", "tests/btc/vm_script_test.py::TestTx::test_scripts_1152", "tests/btc/vm_script_test.py::TestTx::test_scripts_1153", "tests/btc/vm_script_test.py::TestTx::test_scripts_1154", "tests/btc/vm_script_test.py::TestTx::test_scripts_1155", "tests/btc/vm_script_test.py::TestTx::test_scripts_1156", "tests/btc/vm_script_test.py::TestTx::test_scripts_1157", "tests/btc/vm_script_test.py::TestTx::test_scripts_1158", "tests/btc/vm_script_test.py::TestTx::test_scripts_1159", "tests/btc/vm_script_test.py::TestTx::test_scripts_116", "tests/btc/vm_script_test.py::TestTx::test_scripts_1160", "tests/btc/vm_script_test.py::TestTx::test_scripts_1161", "tests/btc/vm_script_test.py::TestTx::test_scripts_1162", "tests/btc/vm_script_test.py::TestTx::test_scripts_1163", "tests/btc/vm_script_test.py::TestTx::test_scripts_1164", "tests/btc/vm_script_test.py::TestTx::test_scripts_1165", "tests/btc/vm_script_test.py::TestTx::test_scripts_1166", "tests/btc/vm_script_test.py::TestTx::test_scripts_1167", "tests/btc/vm_script_test.py::TestTx::test_scripts_1168", "tests/btc/vm_script_test.py::TestTx::test_scripts_1169", "tests/btc/vm_script_test.py::TestTx::test_scripts_117", "tests/btc/vm_script_test.py::TestTx::test_scripts_1170", "tests/btc/vm_script_test.py::TestTx::test_scripts_1171", "tests/btc/vm_script_test.py::TestTx::test_scripts_1172", "tests/btc/vm_script_test.py::TestTx::test_scripts_1173", "tests/btc/vm_script_test.py::TestTx::test_scripts_1174", "tests/btc/vm_script_test.py::TestTx::test_scripts_1175", "tests/btc/vm_script_test.py::TestTx::test_scripts_1176", "tests/btc/vm_script_test.py::TestTx::test_scripts_1177", "tests/btc/vm_script_test.py::TestTx::test_scripts_1178", "tests/btc/vm_script_test.py::TestTx::test_scripts_1179", "tests/btc/vm_script_test.py::TestTx::test_scripts_118", "tests/btc/vm_script_test.py::TestTx::test_scripts_1180", "tests/btc/vm_script_test.py::TestTx::test_scripts_1181", "tests/btc/vm_script_test.py::TestTx::test_scripts_1182", "tests/btc/vm_script_test.py::TestTx::test_scripts_1183", "tests/btc/vm_script_test.py::TestTx::test_scripts_1184", "tests/btc/vm_script_test.py::TestTx::test_scripts_1185", "tests/btc/vm_script_test.py::TestTx::test_scripts_1186", "tests/btc/vm_script_test.py::TestTx::test_scripts_1187", "tests/btc/vm_script_test.py::TestTx::test_scripts_1188", "tests/btc/vm_script_test.py::TestTx::test_scripts_1189", "tests/btc/vm_script_test.py::TestTx::test_scripts_119", "tests/btc/vm_script_test.py::TestTx::test_scripts_1190", "tests/btc/vm_script_test.py::TestTx::test_scripts_1191", "tests/btc/vm_script_test.py::TestTx::test_scripts_1192", "tests/btc/vm_script_test.py::TestTx::test_scripts_1193", "tests/btc/vm_script_test.py::TestTx::test_scripts_1194", "tests/btc/vm_script_test.py::TestTx::test_scripts_1195", "tests/btc/vm_script_test.py::TestTx::test_scripts_1196", "tests/btc/vm_script_test.py::TestTx::test_scripts_1197", "tests/btc/vm_script_test.py::TestTx::test_scripts_1198", "tests/btc/vm_script_test.py::TestTx::test_scripts_1199", "tests/btc/vm_script_test.py::TestTx::test_scripts_120", "tests/btc/vm_script_test.py::TestTx::test_scripts_1200", "tests/btc/vm_script_test.py::TestTx::test_scripts_1201", "tests/btc/vm_script_test.py::TestTx::test_scripts_1202", "tests/btc/vm_script_test.py::TestTx::test_scripts_1203", "tests/btc/vm_script_test.py::TestTx::test_scripts_1204", "tests/btc/vm_script_test.py::TestTx::test_scripts_121", "tests/btc/vm_script_test.py::TestTx::test_scripts_122", "tests/btc/vm_script_test.py::TestTx::test_scripts_123", "tests/btc/vm_script_test.py::TestTx::test_scripts_124", "tests/btc/vm_script_test.py::TestTx::test_scripts_125", "tests/btc/vm_script_test.py::TestTx::test_scripts_126", "tests/btc/vm_script_test.py::TestTx::test_scripts_127", "tests/btc/vm_script_test.py::TestTx::test_scripts_128", "tests/btc/vm_script_test.py::TestTx::test_scripts_129", "tests/btc/vm_script_test.py::TestTx::test_scripts_130", "tests/btc/vm_script_test.py::TestTx::test_scripts_131", "tests/btc/vm_script_test.py::TestTx::test_scripts_132", "tests/btc/vm_script_test.py::TestTx::test_scripts_133", "tests/btc/vm_script_test.py::TestTx::test_scripts_134", "tests/btc/vm_script_test.py::TestTx::test_scripts_135", "tests/btc/vm_script_test.py::TestTx::test_scripts_136", "tests/btc/vm_script_test.py::TestTx::test_scripts_137", "tests/btc/vm_script_test.py::TestTx::test_scripts_138", "tests/btc/vm_script_test.py::TestTx::test_scripts_139", "tests/btc/vm_script_test.py::TestTx::test_scripts_140", "tests/btc/vm_script_test.py::TestTx::test_scripts_141", "tests/btc/vm_script_test.py::TestTx::test_scripts_142", "tests/btc/vm_script_test.py::TestTx::test_scripts_143", "tests/btc/vm_script_test.py::TestTx::test_scripts_144", "tests/btc/vm_script_test.py::TestTx::test_scripts_145", "tests/btc/vm_script_test.py::TestTx::test_scripts_146", "tests/btc/vm_script_test.py::TestTx::test_scripts_147", "tests/btc/vm_script_test.py::TestTx::test_scripts_148", "tests/btc/vm_script_test.py::TestTx::test_scripts_149", "tests/btc/vm_script_test.py::TestTx::test_scripts_150", "tests/btc/vm_script_test.py::TestTx::test_scripts_151", "tests/btc/vm_script_test.py::TestTx::test_scripts_152", "tests/btc/vm_script_test.py::TestTx::test_scripts_153", "tests/btc/vm_script_test.py::TestTx::test_scripts_154", "tests/btc/vm_script_test.py::TestTx::test_scripts_155", "tests/btc/vm_script_test.py::TestTx::test_scripts_156", "tests/btc/vm_script_test.py::TestTx::test_scripts_157", "tests/btc/vm_script_test.py::TestTx::test_scripts_158", "tests/btc/vm_script_test.py::TestTx::test_scripts_159", "tests/btc/vm_script_test.py::TestTx::test_scripts_160", "tests/btc/vm_script_test.py::TestTx::test_scripts_161", "tests/btc/vm_script_test.py::TestTx::test_scripts_162", "tests/btc/vm_script_test.py::TestTx::test_scripts_163", "tests/btc/vm_script_test.py::TestTx::test_scripts_164", "tests/btc/vm_script_test.py::TestTx::test_scripts_165", "tests/btc/vm_script_test.py::TestTx::test_scripts_166", "tests/btc/vm_script_test.py::TestTx::test_scripts_167", "tests/btc/vm_script_test.py::TestTx::test_scripts_168", "tests/btc/vm_script_test.py::TestTx::test_scripts_169", "tests/btc/vm_script_test.py::TestTx::test_scripts_170", "tests/btc/vm_script_test.py::TestTx::test_scripts_171", "tests/btc/vm_script_test.py::TestTx::test_scripts_172", "tests/btc/vm_script_test.py::TestTx::test_scripts_173", "tests/btc/vm_script_test.py::TestTx::test_scripts_174", "tests/btc/vm_script_test.py::TestTx::test_scripts_175", "tests/btc/vm_script_test.py::TestTx::test_scripts_176", "tests/btc/vm_script_test.py::TestTx::test_scripts_177", "tests/btc/vm_script_test.py::TestTx::test_scripts_178", "tests/btc/vm_script_test.py::TestTx::test_scripts_179", "tests/btc/vm_script_test.py::TestTx::test_scripts_180", "tests/btc/vm_script_test.py::TestTx::test_scripts_181", "tests/btc/vm_script_test.py::TestTx::test_scripts_182", "tests/btc/vm_script_test.py::TestTx::test_scripts_183", "tests/btc/vm_script_test.py::TestTx::test_scripts_184", "tests/btc/vm_script_test.py::TestTx::test_scripts_185", "tests/btc/vm_script_test.py::TestTx::test_scripts_186", "tests/btc/vm_script_test.py::TestTx::test_scripts_187", "tests/btc/vm_script_test.py::TestTx::test_scripts_188", "tests/btc/vm_script_test.py::TestTx::test_scripts_189", "tests/btc/vm_script_test.py::TestTx::test_scripts_190", "tests/btc/vm_script_test.py::TestTx::test_scripts_191", "tests/btc/vm_script_test.py::TestTx::test_scripts_192", "tests/btc/vm_script_test.py::TestTx::test_scripts_193", "tests/btc/vm_script_test.py::TestTx::test_scripts_194", "tests/btc/vm_script_test.py::TestTx::test_scripts_195", "tests/btc/vm_script_test.py::TestTx::test_scripts_196", "tests/btc/vm_script_test.py::TestTx::test_scripts_197", "tests/btc/vm_script_test.py::TestTx::test_scripts_198", "tests/btc/vm_script_test.py::TestTx::test_scripts_199", "tests/btc/vm_script_test.py::TestTx::test_scripts_200", "tests/btc/vm_script_test.py::TestTx::test_scripts_201", "tests/btc/vm_script_test.py::TestTx::test_scripts_202", "tests/btc/vm_script_test.py::TestTx::test_scripts_203", "tests/btc/vm_script_test.py::TestTx::test_scripts_204", "tests/btc/vm_script_test.py::TestTx::test_scripts_205", "tests/btc/vm_script_test.py::TestTx::test_scripts_206", "tests/btc/vm_script_test.py::TestTx::test_scripts_207", "tests/btc/vm_script_test.py::TestTx::test_scripts_208", "tests/btc/vm_script_test.py::TestTx::test_scripts_209", "tests/btc/vm_script_test.py::TestTx::test_scripts_210", "tests/btc/vm_script_test.py::TestTx::test_scripts_211", "tests/btc/vm_script_test.py::TestTx::test_scripts_212", "tests/btc/vm_script_test.py::TestTx::test_scripts_213", "tests/btc/vm_script_test.py::TestTx::test_scripts_214", "tests/btc/vm_script_test.py::TestTx::test_scripts_215", "tests/btc/vm_script_test.py::TestTx::test_scripts_216", "tests/btc/vm_script_test.py::TestTx::test_scripts_217", "tests/btc/vm_script_test.py::TestTx::test_scripts_218", "tests/btc/vm_script_test.py::TestTx::test_scripts_219", "tests/btc/vm_script_test.py::TestTx::test_scripts_220", "tests/btc/vm_script_test.py::TestTx::test_scripts_221", "tests/btc/vm_script_test.py::TestTx::test_scripts_222", "tests/btc/vm_script_test.py::TestTx::test_scripts_223", "tests/btc/vm_script_test.py::TestTx::test_scripts_224", "tests/btc/vm_script_test.py::TestTx::test_scripts_225", "tests/btc/vm_script_test.py::TestTx::test_scripts_226", "tests/btc/vm_script_test.py::TestTx::test_scripts_227", "tests/btc/vm_script_test.py::TestTx::test_scripts_228", "tests/btc/vm_script_test.py::TestTx::test_scripts_229", "tests/btc/vm_script_test.py::TestTx::test_scripts_230", "tests/btc/vm_script_test.py::TestTx::test_scripts_231", "tests/btc/vm_script_test.py::TestTx::test_scripts_232", "tests/btc/vm_script_test.py::TestTx::test_scripts_233", "tests/btc/vm_script_test.py::TestTx::test_scripts_234", "tests/btc/vm_script_test.py::TestTx::test_scripts_235", "tests/btc/vm_script_test.py::TestTx::test_scripts_236", "tests/btc/vm_script_test.py::TestTx::test_scripts_237", "tests/btc/vm_script_test.py::TestTx::test_scripts_238", "tests/btc/vm_script_test.py::TestTx::test_scripts_239", "tests/btc/vm_script_test.py::TestTx::test_scripts_240", "tests/btc/vm_script_test.py::TestTx::test_scripts_241", "tests/btc/vm_script_test.py::TestTx::test_scripts_242", "tests/btc/vm_script_test.py::TestTx::test_scripts_243", "tests/btc/vm_script_test.py::TestTx::test_scripts_244", "tests/btc/vm_script_test.py::TestTx::test_scripts_245", "tests/btc/vm_script_test.py::TestTx::test_scripts_246", "tests/btc/vm_script_test.py::TestTx::test_scripts_247", "tests/btc/vm_script_test.py::TestTx::test_scripts_248", "tests/btc/vm_script_test.py::TestTx::test_scripts_249", "tests/btc/vm_script_test.py::TestTx::test_scripts_250", "tests/btc/vm_script_test.py::TestTx::test_scripts_251", "tests/btc/vm_script_test.py::TestTx::test_scripts_252", "tests/btc/vm_script_test.py::TestTx::test_scripts_253", "tests/btc/vm_script_test.py::TestTx::test_scripts_254", "tests/btc/vm_script_test.py::TestTx::test_scripts_255", "tests/btc/vm_script_test.py::TestTx::test_scripts_256", "tests/btc/vm_script_test.py::TestTx::test_scripts_257", "tests/btc/vm_script_test.py::TestTx::test_scripts_258", "tests/btc/vm_script_test.py::TestTx::test_scripts_259", "tests/btc/vm_script_test.py::TestTx::test_scripts_260", "tests/btc/vm_script_test.py::TestTx::test_scripts_261", "tests/btc/vm_script_test.py::TestTx::test_scripts_262", "tests/btc/vm_script_test.py::TestTx::test_scripts_263", "tests/btc/vm_script_test.py::TestTx::test_scripts_264", "tests/btc/vm_script_test.py::TestTx::test_scripts_265", "tests/btc/vm_script_test.py::TestTx::test_scripts_266", "tests/btc/vm_script_test.py::TestTx::test_scripts_267", "tests/btc/vm_script_test.py::TestTx::test_scripts_268", "tests/btc/vm_script_test.py::TestTx::test_scripts_269", "tests/btc/vm_script_test.py::TestTx::test_scripts_270", "tests/btc/vm_script_test.py::TestTx::test_scripts_271", "tests/btc/vm_script_test.py::TestTx::test_scripts_272", "tests/btc/vm_script_test.py::TestTx::test_scripts_273", "tests/btc/vm_script_test.py::TestTx::test_scripts_274", "tests/btc/vm_script_test.py::TestTx::test_scripts_275", "tests/btc/vm_script_test.py::TestTx::test_scripts_276", "tests/btc/vm_script_test.py::TestTx::test_scripts_277", "tests/btc/vm_script_test.py::TestTx::test_scripts_278", "tests/btc/vm_script_test.py::TestTx::test_scripts_279", "tests/btc/vm_script_test.py::TestTx::test_scripts_280", "tests/btc/vm_script_test.py::TestTx::test_scripts_281", "tests/btc/vm_script_test.py::TestTx::test_scripts_282", "tests/btc/vm_script_test.py::TestTx::test_scripts_283", "tests/btc/vm_script_test.py::TestTx::test_scripts_284", "tests/btc/vm_script_test.py::TestTx::test_scripts_285", "tests/btc/vm_script_test.py::TestTx::test_scripts_286", "tests/btc/vm_script_test.py::TestTx::test_scripts_287", "tests/btc/vm_script_test.py::TestTx::test_scripts_288", "tests/btc/vm_script_test.py::TestTx::test_scripts_289", "tests/btc/vm_script_test.py::TestTx::test_scripts_290", "tests/btc/vm_script_test.py::TestTx::test_scripts_291", "tests/btc/vm_script_test.py::TestTx::test_scripts_292", "tests/btc/vm_script_test.py::TestTx::test_scripts_293", "tests/btc/vm_script_test.py::TestTx::test_scripts_294", "tests/btc/vm_script_test.py::TestTx::test_scripts_295", "tests/btc/vm_script_test.py::TestTx::test_scripts_296", "tests/btc/vm_script_test.py::TestTx::test_scripts_297", "tests/btc/vm_script_test.py::TestTx::test_scripts_298", "tests/btc/vm_script_test.py::TestTx::test_scripts_299", "tests/btc/vm_script_test.py::TestTx::test_scripts_300", "tests/btc/vm_script_test.py::TestTx::test_scripts_301", "tests/btc/vm_script_test.py::TestTx::test_scripts_302", "tests/btc/vm_script_test.py::TestTx::test_scripts_303", "tests/btc/vm_script_test.py::TestTx::test_scripts_304", "tests/btc/vm_script_test.py::TestTx::test_scripts_305", "tests/btc/vm_script_test.py::TestTx::test_scripts_306", "tests/btc/vm_script_test.py::TestTx::test_scripts_307", "tests/btc/vm_script_test.py::TestTx::test_scripts_308", "tests/btc/vm_script_test.py::TestTx::test_scripts_309", "tests/btc/vm_script_test.py::TestTx::test_scripts_310", "tests/btc/vm_script_test.py::TestTx::test_scripts_311", "tests/btc/vm_script_test.py::TestTx::test_scripts_312", "tests/btc/vm_script_test.py::TestTx::test_scripts_313", "tests/btc/vm_script_test.py::TestTx::test_scripts_314", "tests/btc/vm_script_test.py::TestTx::test_scripts_315", "tests/btc/vm_script_test.py::TestTx::test_scripts_316", "tests/btc/vm_script_test.py::TestTx::test_scripts_317", "tests/btc/vm_script_test.py::TestTx::test_scripts_318", "tests/btc/vm_script_test.py::TestTx::test_scripts_319", "tests/btc/vm_script_test.py::TestTx::test_scripts_320", "tests/btc/vm_script_test.py::TestTx::test_scripts_321", "tests/btc/vm_script_test.py::TestTx::test_scripts_322", "tests/btc/vm_script_test.py::TestTx::test_scripts_323", "tests/btc/vm_script_test.py::TestTx::test_scripts_324", "tests/btc/vm_script_test.py::TestTx::test_scripts_325", "tests/btc/vm_script_test.py::TestTx::test_scripts_326", "tests/btc/vm_script_test.py::TestTx::test_scripts_327", "tests/btc/vm_script_test.py::TestTx::test_scripts_328", "tests/btc/vm_script_test.py::TestTx::test_scripts_329", "tests/btc/vm_script_test.py::TestTx::test_scripts_330", "tests/btc/vm_script_test.py::TestTx::test_scripts_331", "tests/btc/vm_script_test.py::TestTx::test_scripts_332", "tests/btc/vm_script_test.py::TestTx::test_scripts_333", "tests/btc/vm_script_test.py::TestTx::test_scripts_334", "tests/btc/vm_script_test.py::TestTx::test_scripts_335", "tests/btc/vm_script_test.py::TestTx::test_scripts_336", "tests/btc/vm_script_test.py::TestTx::test_scripts_337", "tests/btc/vm_script_test.py::TestTx::test_scripts_338", "tests/btc/vm_script_test.py::TestTx::test_scripts_339", "tests/btc/vm_script_test.py::TestTx::test_scripts_340", "tests/btc/vm_script_test.py::TestTx::test_scripts_341", "tests/btc/vm_script_test.py::TestTx::test_scripts_342", "tests/btc/vm_script_test.py::TestTx::test_scripts_343", "tests/btc/vm_script_test.py::TestTx::test_scripts_344", "tests/btc/vm_script_test.py::TestTx::test_scripts_345", "tests/btc/vm_script_test.py::TestTx::test_scripts_346", "tests/btc/vm_script_test.py::TestTx::test_scripts_347", "tests/btc/vm_script_test.py::TestTx::test_scripts_348", "tests/btc/vm_script_test.py::TestTx::test_scripts_349", "tests/btc/vm_script_test.py::TestTx::test_scripts_350", "tests/btc/vm_script_test.py::TestTx::test_scripts_351", "tests/btc/vm_script_test.py::TestTx::test_scripts_352", "tests/btc/vm_script_test.py::TestTx::test_scripts_353", "tests/btc/vm_script_test.py::TestTx::test_scripts_354", "tests/btc/vm_script_test.py::TestTx::test_scripts_355", "tests/btc/vm_script_test.py::TestTx::test_scripts_356", "tests/btc/vm_script_test.py::TestTx::test_scripts_357", "tests/btc/vm_script_test.py::TestTx::test_scripts_358", "tests/btc/vm_script_test.py::TestTx::test_scripts_359", "tests/btc/vm_script_test.py::TestTx::test_scripts_360", "tests/btc/vm_script_test.py::TestTx::test_scripts_361", "tests/btc/vm_script_test.py::TestTx::test_scripts_362", "tests/btc/vm_script_test.py::TestTx::test_scripts_363", "tests/btc/vm_script_test.py::TestTx::test_scripts_364", "tests/btc/vm_script_test.py::TestTx::test_scripts_365", "tests/btc/vm_script_test.py::TestTx::test_scripts_366", "tests/btc/vm_script_test.py::TestTx::test_scripts_367", "tests/btc/vm_script_test.py::TestTx::test_scripts_368", "tests/btc/vm_script_test.py::TestTx::test_scripts_369", "tests/btc/vm_script_test.py::TestTx::test_scripts_370", "tests/btc/vm_script_test.py::TestTx::test_scripts_371", "tests/btc/vm_script_test.py::TestTx::test_scripts_372", "tests/btc/vm_script_test.py::TestTx::test_scripts_373", "tests/btc/vm_script_test.py::TestTx::test_scripts_374", "tests/btc/vm_script_test.py::TestTx::test_scripts_375", "tests/btc/vm_script_test.py::TestTx::test_scripts_376", "tests/btc/vm_script_test.py::TestTx::test_scripts_377", "tests/btc/vm_script_test.py::TestTx::test_scripts_378", "tests/btc/vm_script_test.py::TestTx::test_scripts_379", "tests/btc/vm_script_test.py::TestTx::test_scripts_380", "tests/btc/vm_script_test.py::TestTx::test_scripts_381", "tests/btc/vm_script_test.py::TestTx::test_scripts_382", "tests/btc/vm_script_test.py::TestTx::test_scripts_383", "tests/btc/vm_script_test.py::TestTx::test_scripts_384", "tests/btc/vm_script_test.py::TestTx::test_scripts_385", "tests/btc/vm_script_test.py::TestTx::test_scripts_386", "tests/btc/vm_script_test.py::TestTx::test_scripts_387", "tests/btc/vm_script_test.py::TestTx::test_scripts_388", "tests/btc/vm_script_test.py::TestTx::test_scripts_389", "tests/btc/vm_script_test.py::TestTx::test_scripts_390", "tests/btc/vm_script_test.py::TestTx::test_scripts_391", "tests/btc/vm_script_test.py::TestTx::test_scripts_392", "tests/btc/vm_script_test.py::TestTx::test_scripts_393", "tests/btc/vm_script_test.py::TestTx::test_scripts_394", "tests/btc/vm_script_test.py::TestTx::test_scripts_395", "tests/btc/vm_script_test.py::TestTx::test_scripts_396", "tests/btc/vm_script_test.py::TestTx::test_scripts_397", "tests/btc/vm_script_test.py::TestTx::test_scripts_398", "tests/btc/vm_script_test.py::TestTx::test_scripts_399", "tests/btc/vm_script_test.py::TestTx::test_scripts_400", "tests/btc/vm_script_test.py::TestTx::test_scripts_401", "tests/btc/vm_script_test.py::TestTx::test_scripts_402", "tests/btc/vm_script_test.py::TestTx::test_scripts_403", "tests/btc/vm_script_test.py::TestTx::test_scripts_404", "tests/btc/vm_script_test.py::TestTx::test_scripts_405", "tests/btc/vm_script_test.py::TestTx::test_scripts_406", "tests/btc/vm_script_test.py::TestTx::test_scripts_407", "tests/btc/vm_script_test.py::TestTx::test_scripts_408", "tests/btc/vm_script_test.py::TestTx::test_scripts_409", "tests/btc/vm_script_test.py::TestTx::test_scripts_410", "tests/btc/vm_script_test.py::TestTx::test_scripts_411", "tests/btc/vm_script_test.py::TestTx::test_scripts_412", "tests/btc/vm_script_test.py::TestTx::test_scripts_413", "tests/btc/vm_script_test.py::TestTx::test_scripts_414", "tests/btc/vm_script_test.py::TestTx::test_scripts_415", "tests/btc/vm_script_test.py::TestTx::test_scripts_416", "tests/btc/vm_script_test.py::TestTx::test_scripts_417", "tests/btc/vm_script_test.py::TestTx::test_scripts_418", "tests/btc/vm_script_test.py::TestTx::test_scripts_419", "tests/btc/vm_script_test.py::TestTx::test_scripts_420", "tests/btc/vm_script_test.py::TestTx::test_scripts_421", "tests/btc/vm_script_test.py::TestTx::test_scripts_422", "tests/btc/vm_script_test.py::TestTx::test_scripts_423", "tests/btc/vm_script_test.py::TestTx::test_scripts_424", "tests/btc/vm_script_test.py::TestTx::test_scripts_425", "tests/btc/vm_script_test.py::TestTx::test_scripts_426", "tests/btc/vm_script_test.py::TestTx::test_scripts_427", "tests/btc/vm_script_test.py::TestTx::test_scripts_428", "tests/btc/vm_script_test.py::TestTx::test_scripts_429", "tests/btc/vm_script_test.py::TestTx::test_scripts_430", "tests/btc/vm_script_test.py::TestTx::test_scripts_431", "tests/btc/vm_script_test.py::TestTx::test_scripts_432", "tests/btc/vm_script_test.py::TestTx::test_scripts_433", "tests/btc/vm_script_test.py::TestTx::test_scripts_434", "tests/btc/vm_script_test.py::TestTx::test_scripts_435", "tests/btc/vm_script_test.py::TestTx::test_scripts_436", "tests/btc/vm_script_test.py::TestTx::test_scripts_437", "tests/btc/vm_script_test.py::TestTx::test_scripts_438", "tests/btc/vm_script_test.py::TestTx::test_scripts_439", "tests/btc/vm_script_test.py::TestTx::test_scripts_440", "tests/btc/vm_script_test.py::TestTx::test_scripts_441", "tests/btc/vm_script_test.py::TestTx::test_scripts_442", "tests/btc/vm_script_test.py::TestTx::test_scripts_443", "tests/btc/vm_script_test.py::TestTx::test_scripts_444", "tests/btc/vm_script_test.py::TestTx::test_scripts_445", "tests/btc/vm_script_test.py::TestTx::test_scripts_446", "tests/btc/vm_script_test.py::TestTx::test_scripts_447", "tests/btc/vm_script_test.py::TestTx::test_scripts_448", "tests/btc/vm_script_test.py::TestTx::test_scripts_449", "tests/btc/vm_script_test.py::TestTx::test_scripts_450", "tests/btc/vm_script_test.py::TestTx::test_scripts_451", "tests/btc/vm_script_test.py::TestTx::test_scripts_452", "tests/btc/vm_script_test.py::TestTx::test_scripts_453", "tests/btc/vm_script_test.py::TestTx::test_scripts_454", "tests/btc/vm_script_test.py::TestTx::test_scripts_455", "tests/btc/vm_script_test.py::TestTx::test_scripts_456", "tests/btc/vm_script_test.py::TestTx::test_scripts_457", "tests/btc/vm_script_test.py::TestTx::test_scripts_458", "tests/btc/vm_script_test.py::TestTx::test_scripts_459", "tests/btc/vm_script_test.py::TestTx::test_scripts_460", "tests/btc/vm_script_test.py::TestTx::test_scripts_461", "tests/btc/vm_script_test.py::TestTx::test_scripts_462", "tests/btc/vm_script_test.py::TestTx::test_scripts_463", "tests/btc/vm_script_test.py::TestTx::test_scripts_464", "tests/btc/vm_script_test.py::TestTx::test_scripts_465", "tests/btc/vm_script_test.py::TestTx::test_scripts_466", "tests/btc/vm_script_test.py::TestTx::test_scripts_467", "tests/btc/vm_script_test.py::TestTx::test_scripts_468", "tests/btc/vm_script_test.py::TestTx::test_scripts_469", "tests/btc/vm_script_test.py::TestTx::test_scripts_470", "tests/btc/vm_script_test.py::TestTx::test_scripts_471", "tests/btc/vm_script_test.py::TestTx::test_scripts_472", "tests/btc/vm_script_test.py::TestTx::test_scripts_473", "tests/btc/vm_script_test.py::TestTx::test_scripts_474", "tests/btc/vm_script_test.py::TestTx::test_scripts_475", "tests/btc/vm_script_test.py::TestTx::test_scripts_476", "tests/btc/vm_script_test.py::TestTx::test_scripts_477", "tests/btc/vm_script_test.py::TestTx::test_scripts_478", "tests/btc/vm_script_test.py::TestTx::test_scripts_479", "tests/btc/vm_script_test.py::TestTx::test_scripts_480", "tests/btc/vm_script_test.py::TestTx::test_scripts_481", "tests/btc/vm_script_test.py::TestTx::test_scripts_482", "tests/btc/vm_script_test.py::TestTx::test_scripts_483", "tests/btc/vm_script_test.py::TestTx::test_scripts_484", "tests/btc/vm_script_test.py::TestTx::test_scripts_485", "tests/btc/vm_script_test.py::TestTx::test_scripts_486", "tests/btc/vm_script_test.py::TestTx::test_scripts_487", "tests/btc/vm_script_test.py::TestTx::test_scripts_488", "tests/btc/vm_script_test.py::TestTx::test_scripts_489", "tests/btc/vm_script_test.py::TestTx::test_scripts_490", "tests/btc/vm_script_test.py::TestTx::test_scripts_491", "tests/btc/vm_script_test.py::TestTx::test_scripts_492", "tests/btc/vm_script_test.py::TestTx::test_scripts_493", "tests/btc/vm_script_test.py::TestTx::test_scripts_494", "tests/btc/vm_script_test.py::TestTx::test_scripts_495", "tests/btc/vm_script_test.py::TestTx::test_scripts_496", "tests/btc/vm_script_test.py::TestTx::test_scripts_497", "tests/btc/vm_script_test.py::TestTx::test_scripts_498", "tests/btc/vm_script_test.py::TestTx::test_scripts_499", "tests/btc/vm_script_test.py::TestTx::test_scripts_500", "tests/btc/vm_script_test.py::TestTx::test_scripts_501", "tests/btc/vm_script_test.py::TestTx::test_scripts_502", "tests/btc/vm_script_test.py::TestTx::test_scripts_503", "tests/btc/vm_script_test.py::TestTx::test_scripts_504", "tests/btc/vm_script_test.py::TestTx::test_scripts_505", "tests/btc/vm_script_test.py::TestTx::test_scripts_506", "tests/btc/vm_script_test.py::TestTx::test_scripts_507", "tests/btc/vm_script_test.py::TestTx::test_scripts_508", "tests/btc/vm_script_test.py::TestTx::test_scripts_509", "tests/btc/vm_script_test.py::TestTx::test_scripts_510", "tests/btc/vm_script_test.py::TestTx::test_scripts_511", "tests/btc/vm_script_test.py::TestTx::test_scripts_512", "tests/btc/vm_script_test.py::TestTx::test_scripts_513", "tests/btc/vm_script_test.py::TestTx::test_scripts_514", "tests/btc/vm_script_test.py::TestTx::test_scripts_515", "tests/btc/vm_script_test.py::TestTx::test_scripts_516", "tests/btc/vm_script_test.py::TestTx::test_scripts_517", "tests/btc/vm_script_test.py::TestTx::test_scripts_518", "tests/btc/vm_script_test.py::TestTx::test_scripts_519", "tests/btc/vm_script_test.py::TestTx::test_scripts_520", "tests/btc/vm_script_test.py::TestTx::test_scripts_521", "tests/btc/vm_script_test.py::TestTx::test_scripts_522", "tests/btc/vm_script_test.py::TestTx::test_scripts_523", "tests/btc/vm_script_test.py::TestTx::test_scripts_524", "tests/btc/vm_script_test.py::TestTx::test_scripts_525", "tests/btc/vm_script_test.py::TestTx::test_scripts_526", "tests/btc/vm_script_test.py::TestTx::test_scripts_527", "tests/btc/vm_script_test.py::TestTx::test_scripts_528", "tests/btc/vm_script_test.py::TestTx::test_scripts_529", "tests/btc/vm_script_test.py::TestTx::test_scripts_530", "tests/btc/vm_script_test.py::TestTx::test_scripts_531", "tests/btc/vm_script_test.py::TestTx::test_scripts_532", "tests/btc/vm_script_test.py::TestTx::test_scripts_533", "tests/btc/vm_script_test.py::TestTx::test_scripts_534", "tests/btc/vm_script_test.py::TestTx::test_scripts_535", "tests/btc/vm_script_test.py::TestTx::test_scripts_536", "tests/btc/vm_script_test.py::TestTx::test_scripts_537", "tests/btc/vm_script_test.py::TestTx::test_scripts_538", "tests/btc/vm_script_test.py::TestTx::test_scripts_539", "tests/btc/vm_script_test.py::TestTx::test_scripts_540", "tests/btc/vm_script_test.py::TestTx::test_scripts_541", "tests/btc/vm_script_test.py::TestTx::test_scripts_542", "tests/btc/vm_script_test.py::TestTx::test_scripts_543", "tests/btc/vm_script_test.py::TestTx::test_scripts_544", "tests/btc/vm_script_test.py::TestTx::test_scripts_545", "tests/btc/vm_script_test.py::TestTx::test_scripts_546", "tests/btc/vm_script_test.py::TestTx::test_scripts_547", "tests/btc/vm_script_test.py::TestTx::test_scripts_548", "tests/btc/vm_script_test.py::TestTx::test_scripts_549", "tests/btc/vm_script_test.py::TestTx::test_scripts_550", "tests/btc/vm_script_test.py::TestTx::test_scripts_551", "tests/btc/vm_script_test.py::TestTx::test_scripts_552", "tests/btc/vm_script_test.py::TestTx::test_scripts_553", "tests/btc/vm_script_test.py::TestTx::test_scripts_554", "tests/btc/vm_script_test.py::TestTx::test_scripts_555", "tests/btc/vm_script_test.py::TestTx::test_scripts_556", "tests/btc/vm_script_test.py::TestTx::test_scripts_557", "tests/btc/vm_script_test.py::TestTx::test_scripts_558", "tests/btc/vm_script_test.py::TestTx::test_scripts_559", "tests/btc/vm_script_test.py::TestTx::test_scripts_560", "tests/btc/vm_script_test.py::TestTx::test_scripts_561", "tests/btc/vm_script_test.py::TestTx::test_scripts_562", "tests/btc/vm_script_test.py::TestTx::test_scripts_563", "tests/btc/vm_script_test.py::TestTx::test_scripts_564", "tests/btc/vm_script_test.py::TestTx::test_scripts_565", "tests/btc/vm_script_test.py::TestTx::test_scripts_566", "tests/btc/vm_script_test.py::TestTx::test_scripts_567", "tests/btc/vm_script_test.py::TestTx::test_scripts_568", "tests/btc/vm_script_test.py::TestTx::test_scripts_569", "tests/btc/vm_script_test.py::TestTx::test_scripts_570", "tests/btc/vm_script_test.py::TestTx::test_scripts_571", "tests/btc/vm_script_test.py::TestTx::test_scripts_572", "tests/btc/vm_script_test.py::TestTx::test_scripts_573", "tests/btc/vm_script_test.py::TestTx::test_scripts_574", "tests/btc/vm_script_test.py::TestTx::test_scripts_575", "tests/btc/vm_script_test.py::TestTx::test_scripts_576", "tests/btc/vm_script_test.py::TestTx::test_scripts_577", "tests/btc/vm_script_test.py::TestTx::test_scripts_578", "tests/btc/vm_script_test.py::TestTx::test_scripts_579", "tests/btc/vm_script_test.py::TestTx::test_scripts_580", "tests/btc/vm_script_test.py::TestTx::test_scripts_581", "tests/btc/vm_script_test.py::TestTx::test_scripts_582", "tests/btc/vm_script_test.py::TestTx::test_scripts_583", "tests/btc/vm_script_test.py::TestTx::test_scripts_584", "tests/btc/vm_script_test.py::TestTx::test_scripts_585", "tests/btc/vm_script_test.py::TestTx::test_scripts_586", "tests/btc/vm_script_test.py::TestTx::test_scripts_587", "tests/btc/vm_script_test.py::TestTx::test_scripts_588", "tests/btc/vm_script_test.py::TestTx::test_scripts_589", "tests/btc/vm_script_test.py::TestTx::test_scripts_590", "tests/btc/vm_script_test.py::TestTx::test_scripts_591", "tests/btc/vm_script_test.py::TestTx::test_scripts_592", "tests/btc/vm_script_test.py::TestTx::test_scripts_593", "tests/btc/vm_script_test.py::TestTx::test_scripts_594", "tests/btc/vm_script_test.py::TestTx::test_scripts_595", "tests/btc/vm_script_test.py::TestTx::test_scripts_596", "tests/btc/vm_script_test.py::TestTx::test_scripts_597", "tests/btc/vm_script_test.py::TestTx::test_scripts_598", "tests/btc/vm_script_test.py::TestTx::test_scripts_599", "tests/btc/vm_script_test.py::TestTx::test_scripts_600", "tests/btc/vm_script_test.py::TestTx::test_scripts_601", "tests/btc/vm_script_test.py::TestTx::test_scripts_602", "tests/btc/vm_script_test.py::TestTx::test_scripts_603", "tests/btc/vm_script_test.py::TestTx::test_scripts_604", "tests/btc/vm_script_test.py::TestTx::test_scripts_605", "tests/btc/vm_script_test.py::TestTx::test_scripts_606", "tests/btc/vm_script_test.py::TestTx::test_scripts_607", "tests/btc/vm_script_test.py::TestTx::test_scripts_608", "tests/btc/vm_script_test.py::TestTx::test_scripts_609", "tests/btc/vm_script_test.py::TestTx::test_scripts_610", "tests/btc/vm_script_test.py::TestTx::test_scripts_611", "tests/btc/vm_script_test.py::TestTx::test_scripts_612", "tests/btc/vm_script_test.py::TestTx::test_scripts_613", "tests/btc/vm_script_test.py::TestTx::test_scripts_614", "tests/btc/vm_script_test.py::TestTx::test_scripts_615", "tests/btc/vm_script_test.py::TestTx::test_scripts_616", "tests/btc/vm_script_test.py::TestTx::test_scripts_617", "tests/btc/vm_script_test.py::TestTx::test_scripts_618", "tests/btc/vm_script_test.py::TestTx::test_scripts_619", "tests/btc/vm_script_test.py::TestTx::test_scripts_620", "tests/btc/vm_script_test.py::TestTx::test_scripts_621", "tests/btc/vm_script_test.py::TestTx::test_scripts_622", "tests/btc/vm_script_test.py::TestTx::test_scripts_623", "tests/btc/vm_script_test.py::TestTx::test_scripts_624", "tests/btc/vm_script_test.py::TestTx::test_scripts_625", "tests/btc/vm_script_test.py::TestTx::test_scripts_626", "tests/btc/vm_script_test.py::TestTx::test_scripts_627", "tests/btc/vm_script_test.py::TestTx::test_scripts_628", "tests/btc/vm_script_test.py::TestTx::test_scripts_629", "tests/btc/vm_script_test.py::TestTx::test_scripts_630", "tests/btc/vm_script_test.py::TestTx::test_scripts_631", "tests/btc/vm_script_test.py::TestTx::test_scripts_632", "tests/btc/vm_script_test.py::TestTx::test_scripts_633", "tests/btc/vm_script_test.py::TestTx::test_scripts_634", "tests/btc/vm_script_test.py::TestTx::test_scripts_635", "tests/btc/vm_script_test.py::TestTx::test_scripts_636", "tests/btc/vm_script_test.py::TestTx::test_scripts_637", "tests/btc/vm_script_test.py::TestTx::test_scripts_638", "tests/btc/vm_script_test.py::TestTx::test_scripts_639", "tests/btc/vm_script_test.py::TestTx::test_scripts_640", "tests/btc/vm_script_test.py::TestTx::test_scripts_641", "tests/btc/vm_script_test.py::TestTx::test_scripts_642", "tests/btc/vm_script_test.py::TestTx::test_scripts_643", "tests/btc/vm_script_test.py::TestTx::test_scripts_644", "tests/btc/vm_script_test.py::TestTx::test_scripts_645", "tests/btc/vm_script_test.py::TestTx::test_scripts_646", "tests/btc/vm_script_test.py::TestTx::test_scripts_647", "tests/btc/vm_script_test.py::TestTx::test_scripts_648", "tests/btc/vm_script_test.py::TestTx::test_scripts_649", "tests/btc/vm_script_test.py::TestTx::test_scripts_650", "tests/btc/vm_script_test.py::TestTx::test_scripts_651", "tests/btc/vm_script_test.py::TestTx::test_scripts_652", "tests/btc/vm_script_test.py::TestTx::test_scripts_653", "tests/btc/vm_script_test.py::TestTx::test_scripts_654", "tests/btc/vm_script_test.py::TestTx::test_scripts_655", "tests/btc/vm_script_test.py::TestTx::test_scripts_656", "tests/btc/vm_script_test.py::TestTx::test_scripts_657", "tests/btc/vm_script_test.py::TestTx::test_scripts_658", "tests/btc/vm_script_test.py::TestTx::test_scripts_659", "tests/btc/vm_script_test.py::TestTx::test_scripts_660", "tests/btc/vm_script_test.py::TestTx::test_scripts_661", "tests/btc/vm_script_test.py::TestTx::test_scripts_662", "tests/btc/vm_script_test.py::TestTx::test_scripts_663", "tests/btc/vm_script_test.py::TestTx::test_scripts_664", "tests/btc/vm_script_test.py::TestTx::test_scripts_665", "tests/btc/vm_script_test.py::TestTx::test_scripts_666", "tests/btc/vm_script_test.py::TestTx::test_scripts_667", "tests/btc/vm_script_test.py::TestTx::test_scripts_668", "tests/btc/vm_script_test.py::TestTx::test_scripts_669", "tests/btc/vm_script_test.py::TestTx::test_scripts_670", "tests/btc/vm_script_test.py::TestTx::test_scripts_671", "tests/btc/vm_script_test.py::TestTx::test_scripts_672", "tests/btc/vm_script_test.py::TestTx::test_scripts_673", "tests/btc/vm_script_test.py::TestTx::test_scripts_674", "tests/btc/vm_script_test.py::TestTx::test_scripts_675", "tests/btc/vm_script_test.py::TestTx::test_scripts_676", "tests/btc/vm_script_test.py::TestTx::test_scripts_677", "tests/btc/vm_script_test.py::TestTx::test_scripts_678", "tests/btc/vm_script_test.py::TestTx::test_scripts_679", "tests/btc/vm_script_test.py::TestTx::test_scripts_680", "tests/btc/vm_script_test.py::TestTx::test_scripts_681", "tests/btc/vm_script_test.py::TestTx::test_scripts_682", "tests/btc/vm_script_test.py::TestTx::test_scripts_683", "tests/btc/vm_script_test.py::TestTx::test_scripts_684", "tests/btc/vm_script_test.py::TestTx::test_scripts_685", "tests/btc/vm_script_test.py::TestTx::test_scripts_686", "tests/btc/vm_script_test.py::TestTx::test_scripts_687", "tests/btc/vm_script_test.py::TestTx::test_scripts_688", "tests/btc/vm_script_test.py::TestTx::test_scripts_689", "tests/btc/vm_script_test.py::TestTx::test_scripts_690", "tests/btc/vm_script_test.py::TestTx::test_scripts_691", "tests/btc/vm_script_test.py::TestTx::test_scripts_692", "tests/btc/vm_script_test.py::TestTx::test_scripts_693", "tests/btc/vm_script_test.py::TestTx::test_scripts_694", "tests/btc/vm_script_test.py::TestTx::test_scripts_695", "tests/btc/vm_script_test.py::TestTx::test_scripts_696", "tests/btc/vm_script_test.py::TestTx::test_scripts_697", "tests/btc/vm_script_test.py::TestTx::test_scripts_698", "tests/btc/vm_script_test.py::TestTx::test_scripts_699", "tests/btc/vm_script_test.py::TestTx::test_scripts_700", "tests/btc/vm_script_test.py::TestTx::test_scripts_701", "tests/btc/vm_script_test.py::TestTx::test_scripts_702", "tests/btc/vm_script_test.py::TestTx::test_scripts_703", "tests/btc/vm_script_test.py::TestTx::test_scripts_704", "tests/btc/vm_script_test.py::TestTx::test_scripts_705", "tests/btc/vm_script_test.py::TestTx::test_scripts_706", "tests/btc/vm_script_test.py::TestTx::test_scripts_707", "tests/btc/vm_script_test.py::TestTx::test_scripts_708", "tests/btc/vm_script_test.py::TestTx::test_scripts_709", "tests/btc/vm_script_test.py::TestTx::test_scripts_710", "tests/btc/vm_script_test.py::TestTx::test_scripts_711", "tests/btc/vm_script_test.py::TestTx::test_scripts_712", "tests/btc/vm_script_test.py::TestTx::test_scripts_713", "tests/btc/vm_script_test.py::TestTx::test_scripts_714", "tests/btc/vm_script_test.py::TestTx::test_scripts_715", "tests/btc/vm_script_test.py::TestTx::test_scripts_716", "tests/btc/vm_script_test.py::TestTx::test_scripts_717", "tests/btc/vm_script_test.py::TestTx::test_scripts_718", "tests/btc/vm_script_test.py::TestTx::test_scripts_719", "tests/btc/vm_script_test.py::TestTx::test_scripts_720", "tests/btc/vm_script_test.py::TestTx::test_scripts_721", "tests/btc/vm_script_test.py::TestTx::test_scripts_722", "tests/btc/vm_script_test.py::TestTx::test_scripts_723", "tests/btc/vm_script_test.py::TestTx::test_scripts_724", "tests/btc/vm_script_test.py::TestTx::test_scripts_725", "tests/btc/vm_script_test.py::TestTx::test_scripts_726", "tests/btc/vm_script_test.py::TestTx::test_scripts_727", "tests/btc/vm_script_test.py::TestTx::test_scripts_728", "tests/btc/vm_script_test.py::TestTx::test_scripts_729", "tests/btc/vm_script_test.py::TestTx::test_scripts_730", "tests/btc/vm_script_test.py::TestTx::test_scripts_731", "tests/btc/vm_script_test.py::TestTx::test_scripts_732", "tests/btc/vm_script_test.py::TestTx::test_scripts_733", "tests/btc/vm_script_test.py::TestTx::test_scripts_734", "tests/btc/vm_script_test.py::TestTx::test_scripts_735", "tests/btc/vm_script_test.py::TestTx::test_scripts_736", "tests/btc/vm_script_test.py::TestTx::test_scripts_737", "tests/btc/vm_script_test.py::TestTx::test_scripts_738", "tests/btc/vm_script_test.py::TestTx::test_scripts_739", "tests/btc/vm_script_test.py::TestTx::test_scripts_740", "tests/btc/vm_script_test.py::TestTx::test_scripts_741", "tests/btc/vm_script_test.py::TestTx::test_scripts_742", "tests/btc/vm_script_test.py::TestTx::test_scripts_743", "tests/btc/vm_script_test.py::TestTx::test_scripts_744", "tests/btc/vm_script_test.py::TestTx::test_scripts_745", "tests/btc/vm_script_test.py::TestTx::test_scripts_746", "tests/btc/vm_script_test.py::TestTx::test_scripts_747", "tests/btc/vm_script_test.py::TestTx::test_scripts_748", "tests/btc/vm_script_test.py::TestTx::test_scripts_749", "tests/btc/vm_script_test.py::TestTx::test_scripts_750", "tests/btc/vm_script_test.py::TestTx::test_scripts_751", "tests/btc/vm_script_test.py::TestTx::test_scripts_752", "tests/btc/vm_script_test.py::TestTx::test_scripts_753", "tests/btc/vm_script_test.py::TestTx::test_scripts_754", "tests/btc/vm_script_test.py::TestTx::test_scripts_755", "tests/btc/vm_script_test.py::TestTx::test_scripts_756", "tests/btc/vm_script_test.py::TestTx::test_scripts_757", "tests/btc/vm_script_test.py::TestTx::test_scripts_758", "tests/btc/vm_script_test.py::TestTx::test_scripts_759", "tests/btc/vm_script_test.py::TestTx::test_scripts_760", "tests/btc/vm_script_test.py::TestTx::test_scripts_761", "tests/btc/vm_script_test.py::TestTx::test_scripts_762", "tests/btc/vm_script_test.py::TestTx::test_scripts_763", "tests/btc/vm_script_test.py::TestTx::test_scripts_764", "tests/btc/vm_script_test.py::TestTx::test_scripts_765", "tests/btc/vm_script_test.py::TestTx::test_scripts_766", "tests/btc/vm_script_test.py::TestTx::test_scripts_767", "tests/btc/vm_script_test.py::TestTx::test_scripts_768", "tests/btc/vm_script_test.py::TestTx::test_scripts_769", "tests/btc/vm_script_test.py::TestTx::test_scripts_770", "tests/btc/vm_script_test.py::TestTx::test_scripts_771", "tests/btc/vm_script_test.py::TestTx::test_scripts_772", "tests/btc/vm_script_test.py::TestTx::test_scripts_773", "tests/btc/vm_script_test.py::TestTx::test_scripts_774", "tests/btc/vm_script_test.py::TestTx::test_scripts_775", "tests/btc/vm_script_test.py::TestTx::test_scripts_776", "tests/btc/vm_script_test.py::TestTx::test_scripts_777", "tests/btc/vm_script_test.py::TestTx::test_scripts_778", "tests/btc/vm_script_test.py::TestTx::test_scripts_779", "tests/btc/vm_script_test.py::TestTx::test_scripts_780", "tests/btc/vm_script_test.py::TestTx::test_scripts_781", "tests/btc/vm_script_test.py::TestTx::test_scripts_782", "tests/btc/vm_script_test.py::TestTx::test_scripts_783", "tests/btc/vm_script_test.py::TestTx::test_scripts_784", "tests/btc/vm_script_test.py::TestTx::test_scripts_785", "tests/btc/vm_script_test.py::TestTx::test_scripts_786", "tests/btc/vm_script_test.py::TestTx::test_scripts_787", "tests/btc/vm_script_test.py::TestTx::test_scripts_788", "tests/btc/vm_script_test.py::TestTx::test_scripts_789", "tests/btc/vm_script_test.py::TestTx::test_scripts_790", "tests/btc/vm_script_test.py::TestTx::test_scripts_791", "tests/btc/vm_script_test.py::TestTx::test_scripts_792", "tests/btc/vm_script_test.py::TestTx::test_scripts_793", "tests/btc/vm_script_test.py::TestTx::test_scripts_794", "tests/btc/vm_script_test.py::TestTx::test_scripts_795", "tests/btc/vm_script_test.py::TestTx::test_scripts_796", "tests/btc/vm_script_test.py::TestTx::test_scripts_797", "tests/btc/vm_script_test.py::TestTx::test_scripts_798", "tests/btc/vm_script_test.py::TestTx::test_scripts_799", "tests/btc/vm_script_test.py::TestTx::test_scripts_800", "tests/btc/vm_script_test.py::TestTx::test_scripts_801", "tests/btc/vm_script_test.py::TestTx::test_scripts_802", "tests/btc/vm_script_test.py::TestTx::test_scripts_803", "tests/btc/vm_script_test.py::TestTx::test_scripts_804", "tests/btc/vm_script_test.py::TestTx::test_scripts_805", "tests/btc/vm_script_test.py::TestTx::test_scripts_806", "tests/btc/vm_script_test.py::TestTx::test_scripts_807", "tests/btc/vm_script_test.py::TestTx::test_scripts_808", "tests/btc/vm_script_test.py::TestTx::test_scripts_809", "tests/btc/vm_script_test.py::TestTx::test_scripts_810", "tests/btc/vm_script_test.py::TestTx::test_scripts_811", "tests/btc/vm_script_test.py::TestTx::test_scripts_812", "tests/btc/vm_script_test.py::TestTx::test_scripts_813", "tests/btc/vm_script_test.py::TestTx::test_scripts_814", "tests/btc/vm_script_test.py::TestTx::test_scripts_815", "tests/btc/vm_script_test.py::TestTx::test_scripts_816", "tests/btc/vm_script_test.py::TestTx::test_scripts_817", "tests/btc/vm_script_test.py::TestTx::test_scripts_818", "tests/btc/vm_script_test.py::TestTx::test_scripts_819", "tests/btc/vm_script_test.py::TestTx::test_scripts_820", "tests/btc/vm_script_test.py::TestTx::test_scripts_821", "tests/btc/vm_script_test.py::TestTx::test_scripts_822", "tests/btc/vm_script_test.py::TestTx::test_scripts_823", "tests/btc/vm_script_test.py::TestTx::test_scripts_824", "tests/btc/vm_script_test.py::TestTx::test_scripts_825", "tests/btc/vm_script_test.py::TestTx::test_scripts_826", "tests/btc/vm_script_test.py::TestTx::test_scripts_827", "tests/btc/vm_script_test.py::TestTx::test_scripts_828", "tests/btc/vm_script_test.py::TestTx::test_scripts_829", "tests/btc/vm_script_test.py::TestTx::test_scripts_830", "tests/btc/vm_script_test.py::TestTx::test_scripts_831", "tests/btc/vm_script_test.py::TestTx::test_scripts_832", "tests/btc/vm_script_test.py::TestTx::test_scripts_833", "tests/btc/vm_script_test.py::TestTx::test_scripts_834", "tests/btc/vm_script_test.py::TestTx::test_scripts_835", "tests/btc/vm_script_test.py::TestTx::test_scripts_836", "tests/btc/vm_script_test.py::TestTx::test_scripts_837", "tests/btc/vm_script_test.py::TestTx::test_scripts_838", "tests/btc/vm_script_test.py::TestTx::test_scripts_839", "tests/btc/vm_script_test.py::TestTx::test_scripts_840", "tests/btc/vm_script_test.py::TestTx::test_scripts_841", "tests/btc/vm_script_test.py::TestTx::test_scripts_842", "tests/btc/vm_script_test.py::TestTx::test_scripts_843", "tests/btc/vm_script_test.py::TestTx::test_scripts_844", "tests/btc/vm_script_test.py::TestTx::test_scripts_845", "tests/btc/vm_script_test.py::TestTx::test_scripts_846", "tests/btc/vm_script_test.py::TestTx::test_scripts_847", "tests/btc/vm_script_test.py::TestTx::test_scripts_848", "tests/btc/vm_script_test.py::TestTx::test_scripts_849", "tests/btc/vm_script_test.py::TestTx::test_scripts_850", "tests/btc/vm_script_test.py::TestTx::test_scripts_851", "tests/btc/vm_script_test.py::TestTx::test_scripts_852", "tests/btc/vm_script_test.py::TestTx::test_scripts_853", "tests/btc/vm_script_test.py::TestTx::test_scripts_854", "tests/btc/vm_script_test.py::TestTx::test_scripts_855", "tests/btc/vm_script_test.py::TestTx::test_scripts_856", "tests/btc/vm_script_test.py::TestTx::test_scripts_857", "tests/btc/vm_script_test.py::TestTx::test_scripts_858", "tests/btc/vm_script_test.py::TestTx::test_scripts_859", "tests/btc/vm_script_test.py::TestTx::test_scripts_860", "tests/btc/vm_script_test.py::TestTx::test_scripts_861", "tests/btc/vm_script_test.py::TestTx::test_scripts_862", "tests/btc/vm_script_test.py::TestTx::test_scripts_863", "tests/btc/vm_script_test.py::TestTx::test_scripts_864", "tests/btc/vm_script_test.py::TestTx::test_scripts_865", "tests/btc/vm_script_test.py::TestTx::test_scripts_866", "tests/btc/vm_script_test.py::TestTx::test_scripts_867", "tests/btc/vm_script_test.py::TestTx::test_scripts_868", "tests/btc/vm_script_test.py::TestTx::test_scripts_869", "tests/btc/vm_script_test.py::TestTx::test_scripts_870", "tests/btc/vm_script_test.py::TestTx::test_scripts_871", "tests/btc/vm_script_test.py::TestTx::test_scripts_872", "tests/btc/vm_script_test.py::TestTx::test_scripts_873", "tests/btc/vm_script_test.py::TestTx::test_scripts_874", "tests/btc/vm_script_test.py::TestTx::test_scripts_875", "tests/btc/vm_script_test.py::TestTx::test_scripts_876", "tests/btc/vm_script_test.py::TestTx::test_scripts_877", "tests/btc/vm_script_test.py::TestTx::test_scripts_878", "tests/btc/vm_script_test.py::TestTx::test_scripts_879", "tests/btc/vm_script_test.py::TestTx::test_scripts_880", "tests/btc/vm_script_test.py::TestTx::test_scripts_881", "tests/btc/vm_script_test.py::TestTx::test_scripts_882", "tests/btc/vm_script_test.py::TestTx::test_scripts_883", "tests/btc/vm_script_test.py::TestTx::test_scripts_884", "tests/btc/vm_script_test.py::TestTx::test_scripts_885", "tests/btc/vm_script_test.py::TestTx::test_scripts_886", "tests/btc/vm_script_test.py::TestTx::test_scripts_887", "tests/btc/vm_script_test.py::TestTx::test_scripts_888", "tests/btc/vm_script_test.py::TestTx::test_scripts_889", "tests/btc/vm_script_test.py::TestTx::test_scripts_890", "tests/btc/vm_script_test.py::TestTx::test_scripts_891", "tests/btc/vm_script_test.py::TestTx::test_scripts_892", "tests/btc/vm_script_test.py::TestTx::test_scripts_893", "tests/btc/vm_script_test.py::TestTx::test_scripts_894", "tests/btc/vm_script_test.py::TestTx::test_scripts_895", "tests/btc/vm_script_test.py::TestTx::test_scripts_896", "tests/btc/vm_script_test.py::TestTx::test_scripts_897", "tests/btc/vm_script_test.py::TestTx::test_scripts_898", "tests/btc/vm_script_test.py::TestTx::test_scripts_899", "tests/btc/vm_script_test.py::TestTx::test_scripts_900", "tests/btc/vm_script_test.py::TestTx::test_scripts_901", "tests/btc/vm_script_test.py::TestTx::test_scripts_902", "tests/btc/vm_script_test.py::TestTx::test_scripts_903", "tests/btc/vm_script_test.py::TestTx::test_scripts_904", "tests/btc/vm_script_test.py::TestTx::test_scripts_905", "tests/btc/vm_script_test.py::TestTx::test_scripts_906", "tests/btc/vm_script_test.py::TestTx::test_scripts_907", "tests/btc/vm_script_test.py::TestTx::test_scripts_908", "tests/btc/vm_script_test.py::TestTx::test_scripts_909", "tests/btc/vm_script_test.py::TestTx::test_scripts_910", "tests/btc/vm_script_test.py::TestTx::test_scripts_911", "tests/btc/vm_script_test.py::TestTx::test_scripts_912", "tests/btc/vm_script_test.py::TestTx::test_scripts_913", "tests/btc/vm_script_test.py::TestTx::test_scripts_914", "tests/btc/vm_script_test.py::TestTx::test_scripts_915", "tests/btc/vm_script_test.py::TestTx::test_scripts_916", "tests/btc/vm_script_test.py::TestTx::test_scripts_917", "tests/btc/vm_script_test.py::TestTx::test_scripts_918", "tests/btc/vm_script_test.py::TestTx::test_scripts_919", "tests/btc/vm_script_test.py::TestTx::test_scripts_920", "tests/btc/vm_script_test.py::TestTx::test_scripts_921", "tests/btc/vm_script_test.py::TestTx::test_scripts_922", "tests/btc/vm_script_test.py::TestTx::test_scripts_923", "tests/btc/vm_script_test.py::TestTx::test_scripts_924", "tests/btc/vm_script_test.py::TestTx::test_scripts_925", "tests/btc/vm_script_test.py::TestTx::test_scripts_926", "tests/btc/vm_script_test.py::TestTx::test_scripts_927", "tests/btc/vm_script_test.py::TestTx::test_scripts_928", "tests/btc/vm_script_test.py::TestTx::test_scripts_929", "tests/btc/vm_script_test.py::TestTx::test_scripts_930", "tests/btc/vm_script_test.py::TestTx::test_scripts_931", "tests/btc/vm_script_test.py::TestTx::test_scripts_932", "tests/btc/vm_script_test.py::TestTx::test_scripts_933", "tests/btc/vm_script_test.py::TestTx::test_scripts_934", "tests/btc/vm_script_test.py::TestTx::test_scripts_935", "tests/btc/vm_script_test.py::TestTx::test_scripts_936", "tests/btc/vm_script_test.py::TestTx::test_scripts_937", "tests/btc/vm_script_test.py::TestTx::test_scripts_938", "tests/btc/vm_script_test.py::TestTx::test_scripts_939", "tests/btc/vm_script_test.py::TestTx::test_scripts_940", "tests/btc/vm_script_test.py::TestTx::test_scripts_941", "tests/btc/vm_script_test.py::TestTx::test_scripts_942", "tests/btc/vm_script_test.py::TestTx::test_scripts_943", "tests/btc/vm_script_test.py::TestTx::test_scripts_944", "tests/btc/vm_script_test.py::TestTx::test_scripts_945", "tests/btc/vm_script_test.py::TestTx::test_scripts_946", "tests/btc/vm_script_test.py::TestTx::test_scripts_947", "tests/btc/vm_script_test.py::TestTx::test_scripts_948", "tests/btc/vm_script_test.py::TestTx::test_scripts_949", "tests/btc/vm_script_test.py::TestTx::test_scripts_950", "tests/btc/vm_script_test.py::TestTx::test_scripts_951", "tests/btc/vm_script_test.py::TestTx::test_scripts_952", "tests/btc/vm_script_test.py::TestTx::test_scripts_953", "tests/btc/vm_script_test.py::TestTx::test_scripts_954", "tests/btc/vm_script_test.py::TestTx::test_scripts_955", "tests/btc/vm_script_test.py::TestTx::test_scripts_956", "tests/btc/vm_script_test.py::TestTx::test_scripts_957", "tests/btc/vm_script_test.py::TestTx::test_scripts_958", "tests/btc/vm_script_test.py::TestTx::test_scripts_959", "tests/btc/vm_script_test.py::TestTx::test_scripts_960", "tests/btc/vm_script_test.py::TestTx::test_scripts_961", "tests/btc/vm_script_test.py::TestTx::test_scripts_962", "tests/btc/vm_script_test.py::TestTx::test_scripts_963", "tests/btc/vm_script_test.py::TestTx::test_scripts_964", "tests/btc/vm_script_test.py::TestTx::test_scripts_965", "tests/btc/vm_script_test.py::TestTx::test_scripts_966", "tests/btc/vm_script_test.py::TestTx::test_scripts_967", "tests/btc/vm_script_test.py::TestTx::test_scripts_968", "tests/btc/vm_script_test.py::TestTx::test_scripts_969", "tests/btc/vm_script_test.py::TestTx::test_scripts_970", "tests/btc/vm_script_test.py::TestTx::test_scripts_971", "tests/btc/vm_script_test.py::TestTx::test_scripts_972", "tests/btc/vm_script_test.py::TestTx::test_scripts_973", "tests/btc/vm_script_test.py::TestTx::test_scripts_974", "tests/btc/vm_script_test.py::TestTx::test_scripts_975", "tests/btc/vm_script_test.py::TestTx::test_scripts_976", "tests/btc/vm_script_test.py::TestTx::test_scripts_977", "tests/btc/vm_script_test.py::TestTx::test_scripts_978", "tests/btc/vm_script_test.py::TestTx::test_scripts_979", "tests/btc/vm_script_test.py::TestTx::test_scripts_980", "tests/btc/vm_script_test.py::TestTx::test_scripts_981", "tests/btc/vm_script_test.py::TestTx::test_scripts_982", "tests/btc/vm_script_test.py::TestTx::test_scripts_983", "tests/btc/vm_script_test.py::TestTx::test_scripts_984", "tests/btc/vm_script_test.py::TestTx::test_scripts_985", "tests/btc/vm_script_test.py::TestTx::test_scripts_986", "tests/btc/vm_script_test.py::TestTx::test_scripts_987", "tests/btc/vm_script_test.py::TestTx::test_scripts_988", "tests/btc/vm_script_test.py::TestTx::test_scripts_989", "tests/btc/vm_script_test.py::TestTx::test_scripts_990", "tests/btc/vm_script_test.py::TestTx::test_scripts_991", "tests/btc/vm_script_test.py::TestTx::test_scripts_992", "tests/btc/vm_script_test.py::TestTx::test_scripts_993", "tests/btc/vm_script_test.py::TestTx::test_scripts_994", "tests/btc/vm_script_test.py::TestTx::test_scripts_995", "tests/btc/vm_script_test.py::TestTx::test_scripts_996", "tests/btc/vm_script_test.py::TestTx::test_scripts_997", "tests/btc/vm_script_test.py::TestTx::test_scripts_998", "tests/btc/vm_script_test.py::TestTx::test_scripts_999", "tests/build_tx_test.py::BuildTxTest::test_build_spends", "tests/build_tx_test.py::BuildTxTest::test_coinbase_tx", "tests/build_tx_test.py::BuildTxTest::test_signature_hash", "tests/build_tx_test.py::BuildTxTest::test_standard_tx_out", "tests/build_tx_test.py::BuildTxTest::test_tx_out_address", "tests/chainfinder_test.py::ChainFinderTestCase::test_0123", "tests/chainfinder_test.py::ChainFinderTestCase::test_all_orphans", "tests/chainfinder_test.py::ChainFinderTestCase::test_basics", "tests/chainfinder_test.py::ChainFinderTestCase::test_branch", "tests/chainfinder_test.py::ChainFinderTestCase::test_branch_switch", "tests/chainfinder_test.py::ChainFinderTestCase::test_find_ancestral_path", "tests/chainfinder_test.py::ChainFinderTestCase::test_large", "tests/chainfinder_test.py::ChainFinderTestCase::test_longest_chain_endpoint", "tests/chainfinder_test.py::ChainFinderTestCase::test_scramble", "tests/cmds/block_test.py::BlockTest::test_block_dump", "tests/cmds/cmdline_test.py::CmdlineTest::test_coinc_coinc_compile_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_coinc_coinc_hex_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_keyphrase_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_base_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_bc_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_bsd_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_btc_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_btdx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_btx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_cha_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_dash_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_doge_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_mec_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_pivx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_tvi_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_via_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_xlt_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_subpaths_xtn_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_bip32_xprv_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_electrum_initial_key_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_electrum_master_private_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_electrum_master_public_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_hex_passphrase_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_just_address_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_just_wif_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_override_network_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_address_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_hash160_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_sec_02_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_sec_03_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_sec_04_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_wif_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_parse_wif_uncompressed_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_secret_exponent_2_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_secret_exponent_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_subkey_series_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_testnet_subkey_addresses_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_x_decimal_even_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_x_hex_even_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_x_y_decimal_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_ku_x_y_hex_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_msg_sign_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_msg_simple_verify_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_msg_verify_without_address_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_bcash-validate_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_bgold-validate_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_create_dump_sign_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_create_dump_unsigned_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_create_sign_tx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_disassemble_tx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_coinbase_tx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_lock_time_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_secs_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_sig_info_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_signatures_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_tx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_dump_unspents_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_keychain_signature_bip32_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_keychain_signature_electrum_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_known_sec_signature_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_locktime_block_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_locktime_date_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_multisig_btg_1_of_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_multisig_btg_2_of_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_multisig_btg_3_of_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_pay_to_script_hash_3_of_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_pay_to_script_hash_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_prep_unsigned_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_remove_tx_in_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_remove_tx_out_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_sign_tx_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_split_pool_2_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_split_pool_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_split_pool_custom_fee_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_trace_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_version_3_txt", "tests/cmds/cmdline_test.py::CmdlineTest::test_tx_version_5_txt", "tests/cmds/ku_test.py::BTCTests::test_ku_create", "tests/cmds/ku_test.py::LTCTests::test_ku_create", "tests/cmds/ku_test.py::BCHTests::test_ku_create", "tests/cmds/ku_test.py::DOGETests::test_ku_create", "tests/cmds/ku_test.py::XTNTests::test_ku_create", "tests/cmds/tx_test.py::TxTest::test_cache_tx", "tests/cmds/tx_test.py::TxTest::test_pay_to_script_file", "tests/crack_bip32_test.py::CrackBIP32Test::test_ascend_bip32", "tests/crack_bip32_test.py::CrackBIP32Test::test_crack_bip32", "tests/crack_sig_test.py::CrackSigTest::test_crack_k_from_sigs", "tests/crack_sig_test.py::CrackSigTest::test_crack_secret_exponent_from_k", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_add", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_custom_k", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_endian", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_infinity", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_inverse_mod", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_multiply", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_sign_simple", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_sign_verify", "tests/ecdsa/ecdsa_test.py::ECDSATestCase::test_verify_simple", "tests/ecdsa/encrypt_test.py::SharedPublicKeyTest::test_gen_shared", "tests/ecdsa/generator_test.py::GeneratorTestCase::test_all", "tests/ecdsa/libsecp256k1_test.py::ECDSATestCase::test_multiply_by_group_generator", "tests/ecdsa/libsecp256k1_test.py::ECDSATestCase::test_verify", "tests/ecdsa/rfc6979_test.py::RFC6979TestCase::test_deterministic_generate_k_A_1", "tests/ecdsa/rfc6979_test.py::RFC6979TestCase::test_deterministic_generate_k_A_2_1", "tests/ecdsa/rfc6979_test.py::RFC6979TestCase::test_deterministic_generate_k_A_2_5", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_bad_0_generator", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_bad_0_key", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_multiply", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_1", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_10", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_11", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_112233445566778899", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_112233445566778899112233445566778899", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494317", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494318", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494319", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494320", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494321", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494322", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494323", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494324", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494325", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494326", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494327", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494328", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494329", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494330", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494331", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494332", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494333", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494334", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494335", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_115792089237316195423570985008687907852837564279074904382605163141518161494336", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_12", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_12273211894667011703512737764620331640061282752752292412867254036384822317497", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_13", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_14", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_15", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_16", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_17", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_18", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_19", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_2", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_20", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_25064893971726669359337550616456557257214342170707064423873020557698416954604", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_28948022309329048855892746252171976963209391069768726095651290785379540373584", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_3", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_4", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_45404262439013082639639640676052574300732448114466951153301639213084959216733", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_5", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_57068342215440698567564368834304843313972799247029998661603969804853926820579", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_57896044618658097711785492504343953926418782139537452191302581570759080747168", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_6", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_7", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_77059549740374936337596179780007572461065571555507600191520924336939429631266", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_8", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_86844066927987146567678238756515930889628173209306178286953872356138621120752", "tests/ecdsa/secp256k1_test.py::Secp256k1Test::test_vector_9", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_multiply", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_1", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_10", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_11", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_112233445566778899", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_112233445566778899112233445566778899", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_113078210460870548944811695960290644973229224625838436424477095834645696384", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044349", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044350", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044351", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044352", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044353", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044354", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044355", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044356", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044357", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044358", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044359", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044360", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044361", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044362", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044363", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044364", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044365", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044366", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044367", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_115792089210356248762697446949407573529996955224135760342422259061068512044368", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_12", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_12078056106883488161242983286051341125085761470677906721917479268909056", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_13", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_14", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_15", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_16", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_17", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_1766845392945710151501889105729049882997660004824848915955419660366636031", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_18", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_19", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_2", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_20", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_28948025760307534517734791687894775804466072615242963443097661355606862201087", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_29852220098221261079183923314599206100666902414330245206392788703677545185283", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_3", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_4", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_452312848374287284681282171017647412726433684238464212999305864837160993279", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_5", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_57782969857385448082319957860328652998540760998293976083718804450708503920639", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_57896017119460046759583662757090100341435943767777707906455551163257755533312", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_57896042899961394862005778464643882389978449576758748073725983489954366354431", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_6", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_7", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_8", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_9", "tests/ecdsa/secp256r1_test.py::Secp256r1Test::test_vector_904571339174065134293634407946054000774746055866917729876676367558469746684", "tests/ecdsa/signature_test.py::SigningTest::test_sign", "tests/electrum_test.py::ElectrumTest::test_initial_key", "tests/electrum_test.py::ElectrumTest::test_master_public_and_private", "tests/encoding_test.py::EncodingTestCase::test_double_sha256", "tests/encoding_test.py::EncodingTestCase::test_hash160", "tests/encoding_test.py::EncodingTestCase::test_public_pair_to_sec", "tests/encoding_test.py::EncodingTestCase::test_sec", "tests/encoding_test.py::EncodingTestCase::test_to_bytes_32", "tests/encoding_test.py::EncodingTestCase::test_to_from_base58", "tests/encoding_test.py::EncodingTestCase::test_to_from_hashed_base58", "tests/encoding_test.py::EncodingTestCase::test_to_from_long", "tests/encoding_test.py::EncodingTestCase::test_wif_to_from_secret_exponent", "tests/key_test.py::KeyTest::test_sign_verify", "tests/key_test.py::KeyTest::test_translation", "tests/key_validate_test.py::KeyUtilsTest::test_address_valid_btc", "tests/key_validate_test.py::KeyUtilsTest::test_is_public_private_bip32_valid", "tests/key_validate_test.py::KeyUtilsTest::test_is_wif_valid", "tests/key_validate_test.py::KeyUtilsTest::test_key_limits", "tests/key_validate_test.py::KeyUtilsTest::test_repr", "tests/keychain_test.py::KeychainTest::test_keychain", "tests/keyparser_test.py::KeyParserTest::test_parse_address", "tests/keyparser_test.py::KeyParserTest::test_parse_bad_address", "tests/keyparser_test.py::KeyParserTest::test_parse_bad_bip32_prv", "tests/keyparser_test.py::KeyParserTest::test_parse_bad_wif", "tests/keyparser_test.py::KeyParserTest::test_parse_bip32_prv", "tests/keyparser_test.py::KeyParserTest::test_parse_bip32_prv_xtn", "tests/keyparser_test.py::KeyParserTest::test_parse_bip32_pub", "tests/keyparser_test.py::KeyParserTest::test_parse_electrum_master_private", "tests/keyparser_test.py::KeyParserTest::test_parse_electrum_seed", "tests/keyparser_test.py::KeyParserTest::test_parse_wif", "tests/message_test.py::MessageTest::test_InvItem", "tests/message_test.py::MessageTest::test_PeerAddress", "tests/message_test.py::MessageTest::test_ipv4", "tests/message_test.py::MessageTest::test_ipv6", "tests/message_test.py::MessageTest::test_make_parser_and_packer", "tests/msg_signing_test.py::test_against_myself", "tests/msg_signing_test.py::test_msg_parse", "tests/multisig_individual_test.py::MultisigIndividualTest::test_multisig_one_at_a_time", "tests/parse_test.py::ParseTest::test_parse_address_p2pkh", "tests/parse_test.py::ParseTest::test_parse_address_p2pkh_wit", "tests/parse_test.py::ParseTest::test_parse_address_p2sh", "tests/parse_test.py::ParseTest::test_parse_address_p2sh_wit", "tests/parse_test.py::ParseTest::test_parse_bip32_prv", "tests/parse_test.py::ParseTest::test_parse_bip32_pub", "tests/parse_test.py::ParseTest::test_parse_bip32_seed", "tests/parse_test.py::ParseTest::test_parse_electrum_prv", "tests/parse_test.py::ParseTest::test_parse_electrum_pub", "tests/parse_test.py::ParseTest::test_parse_electrum_seed", "tests/parse_test.py::ParseTest::test_parse_script", "tests/parse_test.py::ParseTest::test_parse_wif", "tests/pay_to_test.py::PayToTest::test_nulldata", "tests/pay_to_test.py::PayToTest::test_nulldata_push", "tests/pay_to_test.py::PayToTest::test_recognize_multisig", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_2DROP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_2DUP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_2OVER", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_2ROT", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_2SWAP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_3DUP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_CAT", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_DROP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_DUP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_HASH160", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_HASH256", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_IFDUP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_NIP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_OVER", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_RIPEMD160", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_ROT", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_SHA1", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_SHA256", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_SWAP", "tests/script/stackops_test.py::StackOpsTest::test_do_OP_TUCK", "tests/services/services_test.py::ServicesTest::test_BitcoindProvider", "tests/services/services_test.py::ServicesTest::test_env", "tests/services/services_test.py::ServicesTest::test_thread_provider", "tests/sighash_single_test.py::SighashSingleTest::test_sighash_single", "tests/sign_test.py::SignTest::test_multisig_one_at_a_time", "tests/sign_test.py::SignTest::test_p2sh_multisig_sequential_signing", "tests/sign_test.py::SignTest::test_sign_bitcoind_partially_signed_2_of_2", "tests/sign_test.py::SignTest::test_sign_multisig_1_of_2", "tests/sign_test.py::SignTest::test_sign_multisig_2_of_3", "tests/sign_test.py::SignTest::test_sign_p2sh", "tests/sign_test.py::SignTest::test_sign_pay_to_script_multisig", "tests/solver_test.py::SolverTest::test_if", "tests/solver_test.py::SolverTest::test_nonstandard_p2pkh", "tests/solver_test.py::SolverTest::test_p2multisig", "tests/solver_test.py::SolverTest::test_p2multisig_incremental", "tests/solver_test.py::SolverTest::test_p2multisig_wit", "tests/solver_test.py::SolverTest::test_p2pk", "tests/solver_test.py::SolverTest::test_p2pkh", "tests/solver_test.py::SolverTest::test_p2pkh_wit", "tests/solver_test.py::SolverTest::test_p2sh", "tests/solver_test.py::SolverTest::test_p2sh_wit", "tests/tools_test.py::ToolsTest::test_compile_decompile", "tests/tools_test.py::ToolsTest::test_compile_push_data_list", "tests/tools_test.py::ToolsTest::test_int_to_from_script_bytes", "tests/tools_test.py::ToolsTest::test_tx_7e0114e93f903892b4dff5526a8cab674b2825fd715c4a95f852a1aed634a0f6", "tests/tx_test.py::TxTest::test_blanked_hash", "tests/tx_test.py::TxTest::test_issue_39", "tests/tx_test.py::TxTest::test_tx_api", "tests/tx_utils_test.py::SpendTest::test_confirm_input", "tests/tx_utils_test.py::SpendTest::test_confirm_input_raises", "tests/tx_utils_test.py::SpendTest::test_simple_spend", "tests/validation_test.py::ValidationTest::test_validate_block_data", "tests/validation_test.py::ValidationTest::test_validate_multisig_tx", "tests/validation_test.py::ValidationTest::test_validate_p2pkh", "tests/validation_test.py::ValidationTest::test_validate_p2pkh_wit", "tests/validation_test.py::ValidationTest::test_validate_p2s_of_p2pkh", "tests/validation_test.py::ValidationTest::test_validate_p2s_of_p2s_wit_of_p2pkh", "tests/validation_test.py::ValidationTest::test_validate_p2s_wit_of_p2pkh", "tests/validation_test.py::ValidationTest::test_validate_two_inputs", "tests/who_signed_test.py::WhoSignedTest::test_create_multisig_1_of_2", "tests/who_signed_test.py::WhoSignedTest::test_create_multisig_2_of_3", "tests/who_signed_test.py::WhoSignedTest::test_multisig_one_at_a_time", "tests/who_signed_test.py::WhoSignedTest::test_sign_pay_to_script_multisig" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-10-10 13:19:58+00:00
mit
5,253
riffdog__riffdog-52
diff --git a/riffdog/command_line.py b/riffdog/command_line.py index e3c46df..7009182 100644 --- a/riffdog/command_line.py +++ b/riffdog/command_line.py @@ -77,6 +77,7 @@ def _add_core_arguments(parser): parser.add_argument('--json', help='Produce Json output rather then Human readble', action='store_const', const=True) # noqa: E501 parser.add_argument('--show-matched', help='Shows all resources, including those that matched', action='store_const', const=True) # noqa: E501 parser.add_argument('--exclude-resource', help="Excludes a particular resource", action='append', default=[]) + parser.add_argument('--include-resource', help="Includes a particular resource", action="append", default=[]) def main(*args): @@ -112,6 +113,8 @@ def main(*args): config = RDConfig() config.external_resource_libs += pre_parsed_args.include + config.excluded_resources = pre_parsed_args.exclude_resource + config.included_resources = pre_parsed_args.include_resource find_arguments(parser, config.external_resource_libs) diff --git a/riffdog/config.py b/riffdog/config.py index 4e1d847..d5d3536 100644 --- a/riffdog/config.py +++ b/riffdog/config.py @@ -24,8 +24,11 @@ class RDConfig: @property def elements_to_scan(self): - return (x for x in self.base_elements_to_scan if x not in self.excluded_resources) - + if self.included_resources: + resources = (x for x in self.included_resources) + else: + resources = (x for x in self.base_elements_to_scan if x not in self.excluded_resources) + return resources def __init__(self): # Set defaults and must-have settings @@ -37,6 +40,7 @@ class RDConfig: self.state_file_locations = [] self.excluded_resources = [] + self.included_resources = [] self.base_elements_to_scan = [] diff --git a/riffdog/scanner.py b/riffdog/scanner.py index bf576bb..f4c1001 100644 --- a/riffdog/scanner.py +++ b/riffdog/scanner.py @@ -150,6 +150,7 @@ def _search_state(bucket_name, key, s3): obj = s3.Object(bucket_name, key) content = obj.get()['Body'].read() rd = ResourceDirectory() + config = RDConfig() parsed = "" try: parsed = json.loads(content) @@ -160,11 +161,14 @@ def _search_state(bucket_name, key, s3): elements = parsed['modules'][0]['resources'].values() for res in elements: - element = rd.lookup(res['type']) - if element: - element.process_state_resource(res, key) + if res['type'] in config.elements_to_scan: + element = rd.lookup(res['type']) + if element: + element.process_state_resource(res, key) + else: + logging.debug(" Unsupported resource %s" % res['type']) else: - logging.debug(" Unsupported resource %s" % res['type']) + logging.debug("Skipped %s as not in elments to scan" % res['type']) except Exception as e: # FIXME: tighten this up could be - file not Json issue, permission of s3 etc, as well as the terraform state
riffdog/riffdog
588f5c55fba6675868d8c20138647568025c1174
diff --git a/tests/test_data_structures.py b/tests/test_data_structures.py index fd745ff..cca9100 100644 --- a/tests/test_data_structures.py +++ b/tests/test_data_structures.py @@ -14,6 +14,19 @@ class TestRDConfig: assert list(config.elements_to_scan) == config.base_elements_to_scan[1:] + def test_include_no_exclude(self): + config = RDConfig() + config.included_resources = ['aws_bucket'] + + assert list(config.elements_to_scan) == config.included_resources + + def test_include_with_excluded(self): + config = RDConfig() + config.exclude_resources = ['aws_s3_bucket'] + config.included_resources = ['aws_vpc', 'aws_subnet'] + + assert list(config.elements_to_scan) == config.included_resources + def test_singleton(self): config = RDConfig() config.regions = ['us-east-1', 'eu-west-1']
Revisit `--exclude` and create an `--only` option Using `--exclude` is more difficult now there are lots of resources - instead we should consider using an `--only` element to specify. I don't like the word `--only` though so feedback and ideas here appreciated.
0.0
588f5c55fba6675868d8c20138647568025c1174
[ "tests/test_data_structures.py::TestRDConfig::test_include_no_exclude", "tests/test_data_structures.py::TestRDConfig::test_include_with_excluded" ]
[ "tests/test_data_structures.py::TestRDConfig::test_exclude_no_elements", "tests/test_data_structures.py::TestRDConfig::test_exclude_one_element", "tests/test_data_structures.py::TestRDConfig::test_singleton" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-04 21:20:00+00:00
mit
5,254
riga__scinum-8
diff --git a/docs/index.rst b/docs/index.rst index ceaef6c..4a1252d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -52,6 +52,12 @@ Functions .. autofunction:: combine_uncertainties +``calculate_uncertainty`` +------------------------- + +.. autofunction:: calculate_uncertainty + + ``ensure_number`` ----------------- @@ -70,6 +76,18 @@ Functions .. autofunction:: is_numpy +``is_ufloat`` +------------- + +.. autofunction:: is_ufloat + + +``parse_ufloat`` +---------------- + +.. autofunction:: parse_ufloat + + ``infer_math`` -------------- diff --git a/scinum.py b/scinum.py index cbdbb8d..75745d3 100644 --- a/scinum.py +++ b/scinum.py @@ -23,6 +23,7 @@ import functools import operator import types import decimal +from collections import defaultdict # optional imports try: @@ -32,6 +33,13 @@ except ImportError: np = None HAS_NUMPY = False +try: + import uncertainties as _uncs + HAS_UNCERTAINTIES = True +except ImportError: + _uncs = None + HAS_UNCERTAINTIES = False + # version related adjustments string_types = (str,) @@ -300,6 +308,14 @@ class Number(object): # numpy settings self.dtype = np.float32 if HAS_NUMPY else None + # prepare conversion from uncertainties.ufloat + if is_ufloat(nominal): + # uncertainties must not be set + if uncertainties: + raise ValueError("uncertainties must not be set when converting a ufloat") + # extract nominal value and uncertainties + nominal, uncertainties = parse_ufloat(nominal) + # set initial values self.nominal = nominal if uncertainties is not None: @@ -1003,7 +1019,7 @@ class ops(with_metaclass(OpsMeta, object)): # -# Pre-registered operations. +# pre-registered operations # @ops.register @@ -1292,62 +1308,9 @@ def atanh(x): return 1. / (1. - x**2.) +# # helper functions - -_op_map = { - "+": operator.add, - "-": operator.sub, - "*": operator.mul, - "/": operator.truediv, - "**": operator.pow, -} - -_op_map_reverse = dict(zip(_op_map.values(), _op_map.keys())) - - -def combine_uncertainties(op, unc1, unc2, nom1=None, nom2=None, rho=0.): - """ - Combines two uncertainties *unc1* and *unc2* according to an operator *op* which must be either - ``"+"``, ``"-"``, ``"*"``, ``"/"``, or ``"**"``. The three latter operators require that you - also pass the nominal values *nom1* and *nom2*, respectively. The correlation can be configured - via *rho*. - """ - # operator valid? - if op in _op_map: - f = _op_map[op] - elif op in _op_map_reverse: - f = op - op = _op_map_reverse[op] - else: - raise ValueError("unknown operator: {}".format(op)) - - # prepare values for combination, depends on operator - if op in ("*", "/", "**"): - if nom1 is None or nom2 is None: - raise ValueError("operator '{}' requires nominal values".format(op)) - # numpy-safe conversion to float - nom1 *= 1. - nom2 *= 1. - # convert uncertainties to relative values, taking into account zeros - if unc1 or nom1: - unc1 /= nom1 - if unc2 or nom2: - unc2 /= nom2 - # determine - nom = abs(f(nom1, nom2)) - else: - nom = 1. - - # combined formula - if op == "**": - return nom * abs(nom2) * (unc1**2. + (math.log(nom1) * unc2)**2. + 2 * rho * - math.log(nom1) * unc1 * unc2)**0.5 - else: - # flip rho for sub and div - if op in ("-", "/"): - rho = -rho - return nom * (unc1**2. + unc2**2. + 2. * rho * unc1 * unc2)**0.5 - +# def ensure_number(num, *args, **kwargs): """ @@ -1372,6 +1335,36 @@ def is_numpy(x): return HAS_NUMPY and type(x).__module__ == np.__name__ +def is_ufloat(x): + """ + Returns *True* when the "uncertainties" package is available on your system and *x* is a + ``ufloat``. + """ + return HAS_UNCERTAINTIES and isinstance(x, _uncs.core.AffineScalarFunc) + + +def parse_ufloat(x, default_tag=Number.DEFAULT): + """ + Takes a ``ufloat`` object *x* from the "uncertainties" package and returns a tuple with two + elements containing its nominal value and a dictionary with its uncertainties. When the error + components of *x* contain multiple uncertainties with the same name, they are combined under the + assumption of full correlation. When an error component is not tagged, *default_tag* is used. + """ + # store error components to be combined per tag + components = defaultdict(list) + for comp, value in x.error_components().items(): + name = comp.tag if comp.tag is not None else default_tag + components[name].append((x.derivatives[comp], value)) + + # combine components to uncertainties, assume full correlation + uncertainties = { + name: calculate_uncertainty(terms, rho=1.) + for name, terms in components.items() + } + + return x.nominal_value, uncertainties + + def infer_math(x): """ Returns the numpy module when :py:func:`is_numpy` for *x* is *True*, and the math module @@ -1486,6 +1479,100 @@ def _infer_precision(unc, sig, mag, method): return prec, sig, mag +_op_map = { + "+": operator.add, + "-": operator.sub, + "*": operator.mul, + "/": operator.truediv, + "**": operator.pow, +} + +_op_map_reverse = dict(zip(_op_map.values(), _op_map.keys())) + + +def calculate_uncertainty(terms, rho=0.): + """ + Generically calculates the uncertainty of a quantity that depends on multiple *terms*. Each term + is expected to be a 2-tuple containing the derivative and the uncertainty of the term. + Correlations can be defined via *rho*. When *rho* is a numner, all correlations are set to this + value. It can also be a mapping of a 2-tuple, the two indices of the terms to describe, to their + correlation coefficient. In case the indices of two terms are not included in this mapping, they + are assumed to be uncorrelated. Example: + + .. code-block:: python + + calculate_uncertainty([(3, 0.5), (4, 0.5)]) + # uncorrelated + # -> 2.5 + + calculate_uncertainty([(3, 0.5), (4, 0.5)], rho=1) + # fully correlated + # -> 3.5 + + calculate_uncertainty([(3, 0.5), (4, 0.5)], rho={(0, 1): 1}) + # fully correlated + # -> 3.5 + + calculate_uncertainty([(3, 0.5), (4, 0.5)], rho={(1, 2): 1}) + # no rho value defined for pair (0, 1), assumes zero correlation + # -> 2.5 + """ + # sum over squaresall single terms + variance = sum((derivative * uncertainty)**2. for derivative, uncertainty in terms) + + # add second order terms of all pairs + for i in range(len(terms) - 1): + for j in range(i + 1, len(terms)): + _rho = rho.get((i, j), 0.) if isinstance(rho, dict) else rho + variance += 2. * terms[i][0] * terms[j][0] * _rho * terms[i][1] * terms[j][1] + + return variance**0.5 + + +def combine_uncertainties(op, unc1, unc2, nom1=None, nom2=None, rho=0.): + """ + Combines two uncertainties *unc1* and *unc2* according to an operator *op* which must be either + ``"+"``, ``"-"``, ``"*"``, ``"/"``, or ``"**"``. The three latter operators require that you + also pass the nominal values *nom1* and *nom2*, respectively. The correlation can be configured + via *rho*. + """ + # operator valid? + if op in _op_map: + f = _op_map[op] + elif op in _op_map_reverse: + f = op + op = _op_map_reverse[op] + else: + raise ValueError("unknown operator: {}".format(op)) + + # prepare values for combination, depends on operator + if op in ("*", "/", "**"): + if nom1 is None or nom2 is None: + raise ValueError("operator '{}' requires nominal values".format(op)) + # numpy-safe conversion to float + nom1 *= 1. + nom2 *= 1. + # convert uncertainties to relative values, taking into account zeros + if unc1 or nom1: + unc1 /= nom1 + if unc2 or nom2: + unc2 /= nom2 + # determine + nom = abs(f(nom1, nom2)) + else: + nom = 1. + + # combined formula + if op == "**": + return nom * abs(nom2) * (unc1**2. + (math.log(nom1) * unc2)**2. + 2 * rho * + math.log(nom1) * unc1 * unc2)**0.5 + else: + # flip rho for sub and div + if op in ("-", "/"): + rho = -rho + return nom * (unc1**2. + unc2**2. + 2. * rho * unc1 * unc2)**0.5 + + def round_uncertainty(unc, method="publication"): """ Rounds an uncertainty *unc* following a specific *method* and returns a 2-tuple containing the
riga/scinum
74733a6c6767eb1a5d81364d183ed8d6b3fdd140
diff --git a/tests/__init__.py b/tests/__init__.py index 934ad03..b310322 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -14,13 +14,16 @@ import unittest base = os.path.normpath(os.path.join(os.path.abspath(__file__), "../..")) sys.path.append(base) from scinum import ( - Number, ops, HAS_NUMPY, split_value, match_precision, round_uncertainty, round_value, - infer_si_prefix, + Number, ops, HAS_NUMPY, HAS_UNCERTAINTIES, split_value, match_precision, calculate_uncertainty, + round_uncertainty, round_value, infer_si_prefix, ) if HAS_NUMPY: import numpy as np +if HAS_UNCERTAINTIES: + from uncertainties import ufloat + UP = Number.UP DOWN = Number.DOWN @@ -29,6 +32,10 @@ def if_numpy(func): return func if HAS_NUMPY else (lambda self: None) +def if_uncertainties(func): + return func if HAS_UNCERTAINTIES else (lambda self: None) + + def ptgr(*args): return sum([a ** 2. for a in args]) ** 0.5 @@ -85,6 +92,32 @@ class TestCase(unittest.TestCase): with self.assertRaises(ValueError): num.set_uncertainty("B", np.arange(5, 9)) + @if_uncertainties + def test_constructor_ufloat(self): + num = Number(ufloat(42, 5)) + self.assertEqual(num.nominal, 42.) + self.assertEqual(num.get_uncertainty(Number.DEFAULT), (5., 5.)) + + with self.assertRaises(ValueError): + Number(ufloat(42, 5), uncertainties={"other_error": 123}) + + num = Number(ufloat(42, 5, tag="foo")) + self.assertEqual(num.get_uncertainty("foo"), (5., 5.)) + + num = Number(ufloat(42, 5) + ufloat(2, 2)) + self.assertEqual(num.nominal, 44.) + self.assertEqual(num.get_uncertainty(Number.DEFAULT), (7., 7.)) + + num = Number(ufloat(42, 5, tag="foo") + ufloat(2, 2, tag="bar")) + self.assertEqual(num.nominal, 44.) + self.assertEqual(num.get_uncertainty("foo"), (5., 5.)) + self.assertEqual(num.get_uncertainty("bar"), (2., 2.)) + + num = Number(ufloat(42, 5, tag="foo") + ufloat(2, 2, tag="bar") + ufloat(1, 1, tag="bar")) + self.assertEqual(num.nominal, 45.) + self.assertEqual(num.get_uncertainty("foo"), (5., 5.)) + self.assertEqual(num.get_uncertainty("bar"), (3., 3.)) + def test_copy(self): num = self.num.copy() self.assertFalse(num is self.num) @@ -341,6 +374,12 @@ class TestCase(unittest.TestCase): self.assertEqual(tuple(match_precision(a, "1.")), (b"1", b"0", b"-42", b"0")) self.assertEqual(tuple(match_precision(a, ".1")), (b"1.0", b"0.1", b"-42.5", b"0.0")) + def test_calculate_uncertainty(self): + self.assertEqual(calculate_uncertainty([(3, 0.5), (4, 0.5)]), 2.5) + self.assertEqual(calculate_uncertainty([(3, 0.5), (4, 0.5)], rho=1), 3.5) + self.assertEqual(calculate_uncertainty([(3, 0.5), (4, 0.5)], rho={(0, 1): 1}), 3.5) + self.assertEqual(calculate_uncertainty([(3, 0.5), (4, 0.5)], rho={(1, 2): 1}), 2.5) + def test_round_uncertainty(self): self.assertEqual(round_uncertainty(0.352, "pdg"), ("35", -2)) self.assertEqual(round_uncertainty(0.352, "pub"), ("352", -3))
Accept uncertainties.{ufloat,uarray} in constructor. Converting from `uncertainties` to `scinum` should be fairly trivial.
0.0
74733a6c6767eb1a5d81364d183ed8d6b3fdd140
[ "tests/__init__.py::TestCase::test_calculate_uncertainty", "tests/__init__.py::TestCase::test_constructor", "tests/__init__.py::TestCase::test_constructor_numpy", "tests/__init__.py::TestCase::test_constructor_ufloat", "tests/__init__.py::TestCase::test_copy", "tests/__init__.py::TestCase::test_copy_numpy", "tests/__init__.py::TestCase::test_infer_si_prefix", "tests/__init__.py::TestCase::test_match_precision", "tests/__init__.py::TestCase::test_match_precision_numpy", "tests/__init__.py::TestCase::test_op_cos", "tests/__init__.py::TestCase::test_op_exp", "tests/__init__.py::TestCase::test_op_log", "tests/__init__.py::TestCase::test_op_pow", "tests/__init__.py::TestCase::test_op_sin", "tests/__init__.py::TestCase::test_op_tan", "tests/__init__.py::TestCase::test_ops_registration", "tests/__init__.py::TestCase::test_round_uncertainty", "tests/__init__.py::TestCase::test_round_uncertainty_numpy", "tests/__init__.py::TestCase::test_round_value", "tests/__init__.py::TestCase::test_round_value_list", "tests/__init__.py::TestCase::test_round_value_numpy", "tests/__init__.py::TestCase::test_split_value", "tests/__init__.py::TestCase::test_split_value_numpy", "tests/__init__.py::TestCase::test_strings", "tests/__init__.py::TestCase::test_uncertainty_combination", "tests/__init__.py::TestCase::test_uncertainty_parsing", "tests/__init__.py::TestCase::test_uncertainty_propagation" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-07-17 11:55:28+00:00
bsd-3-clause
5,255
riga__scinum-9
diff --git a/scinum.py b/scinum.py index 75745d3..fc95843 100644 --- a/scinum.py +++ b/scinum.py @@ -456,6 +456,19 @@ class Number(object): uncertainties = self.__class__.uncertainties.fparse(self, {name: value}) self._uncertainties.update(uncertainties) + def clear(self, nominal=None, uncertainties=None): + """ + Removes all uncertainties and sets the nominal value to zero (float). When *nominal* and + *uncertainties* are given, these new values are set on this instance. + """ + self.uncertainties = {} + self.nominal = 0. + + if nominal is not None: + self.nominal = nominal + if uncertainties is not None: + self.uncertainties = uncertainties + def str(self, format=None, unit=None, scientific=False, si=False, labels=True, style="plain", styles=None, force_asymmetric=False, **kwargs): r""" @@ -609,7 +622,8 @@ class Number(object): if not self.is_numpy: text = "'" + self.str(*args, **kwargs) + "'" else: - text = "{} numpy array, {} uncertainties".format(self.shape, len(self.uncertainties)) + text = "numpy array, shape {}, {} uncertainties".format(self.shape, + len(self.uncertainties)) return "<{} at {}, {}>".format(self.__class__.__name__, hex(id(self)), text) @@ -733,11 +747,34 @@ class Number(object): nom1=num.nominal, nom2=other.nominal, rho=_rho) for i in range(2)) # store values - num.nominal = nom - num.uncertainties = uncs + num.clear(nom, uncs) return num + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + # only direct calls of the ufunc are supported + if method != "__call__": + return NotImplemented + + # try to find the proper op for that ufunc + op = ops.get_ufunc_operation(ufunc) + if op is None: + return NotImplemented + + # extract kwargs + out = kwargs.pop("out", None) + + # apply the op + result = op(*inputs, **kwargs) + + # insert in-place to an "out" object? + if out is not None: + out = out[0] + out.clear(result.nominal, result.uncertainties) + result = out + + return result + def __call__(self, *args, **kwargs): # shorthand for get return self.get(*args, **kwargs) @@ -897,12 +934,13 @@ class Operation(object): The name of the operation. """ - def __init__(self, function, derivative=None, name=None): + def __init__(self, function, derivative=None, name=None, ufunc_name=None): super(Operation, self).__init__() self.function = function self.derivative = derivative self._name = name or function.__name__ + self._ufunc_name = ufunc_name # decorator for setting the derivative def derive(derivative): @@ -914,9 +952,35 @@ class Operation(object): def name(self): return self._name + @property + def ufunc_name(self): + return self._ufunc_name + def __repr__(self): return "<{} '{}' at {}>".format(self.__class__.__name__, self.name, hex(id(self))) + def __call__(self, num, *args, **kwargs): + if self.derivative is None: + raise Exception("cannot run operation '{}', no derivative registered".format( + self.name)) + + # ensure we deal with a number instance + num = ensure_number(num) + + # apply to the nominal value + nominal = self.function(num.nominal, *args, **kwargs) + + # apply to all uncertainties via + # unc_f = derivative_f(x) * unc_x + x = abs(self.derivative(num.nominal, *args, **kwargs)) + uncertainties = {} + for name in num.uncertainties: + up, down = num.get_uncertainty(name) + uncertainties[name] = (x * up, x * down) + + # create and return the new number + return num.__class__(nominal, uncertainties) + class OpsMeta(type): @@ -936,10 +1000,14 @@ class ops(with_metaclass(OpsMeta, object)): print(num) # -> 25.00 (+10.00, -10.00) """ + # registered operations mapped to their names _instances = {} + # mapping of ufunc names to operation names for faster lookup + _ufuncs = {} + @classmethod - def register(cls, function=None, name=None): + def register(cls, function=None, name=None, ufunc=None): """ Registers a new math function *function* with *name* and returns an :py:class:`Operation` instance. A math function expects a :py:class:`Number` as its first argument, followed by @@ -965,36 +1033,25 @@ class ops(with_metaclass(OpsMeta, object)): Please note that there is no need to register *simple* functions as in the particular example above as most of them are just composite operations whose derivatives are already known. - """ - def register(function): - op = Operation(function, name=name) - - @functools.wraps(function) - def wrapper(num, *args, **kwargs): - if op.derivative is None: - raise Exception("cannot run operation '{}', no derivative registered".format( - op.name)) - - # ensure we deal with a number instance - num = ensure_number(num) - # apply to the nominal value - nominal = op.function(num.nominal, *args, **kwargs) - - # apply to all uncertainties via - # unc_f = derivative_f(x) * unc_x - x = abs(op.derivative(num.nominal, *args, **kwargs)) - uncertainties = {} - for name in num.uncertainties.keys(): - up, down = num.get_uncertainty(name) - uncertainties[name] = (x * up, x * down) + To comply with NumPy's ufuncs (https://numpy.org/neps/nep-0013-ufunc-overrides.html) that + are handled by :py:meth:`Number.__array_ufunc__`, an operation might define a *ufunc* name + to signalize that it should be used when a ufunc with that name is called with a number + instance as its argument. + """ + ufunc_name = None + if ufunc is not None: + ufunc_name = ufunc if isinstance(ufunc, string_types) else ufunc.__name__ - # create and return the new number - return num.__class__(nominal, uncertainties) + def register(function): + op = Operation(function, name=name, ufunc_name=ufunc_name) - # actual registration + # save as class attribute and also in _instances cls._instances[op.name] = op - setattr(cls, op.name, staticmethod(wrapper)) + setattr(cls, op.name, op) + + # add to ufunc mapping + cls._ufuncs[op.ufunc_name] = op.name return op @@ -1017,12 +1074,37 @@ class ops(with_metaclass(OpsMeta, object)): """ return cls.get_operation(*args, **kwargs) + @classmethod + def get_ufunc_operation(cls, ufunc): + """ + Returns an operation that was previously registered to handle a NumPy *ufunc*, which can be + a string or the function itself. *None* is returned when no operation was found to handle + the function. + """ + ufunc_name = ufunc if isinstance(ufunc, string_types) else ufunc.__name__ + + if ufunc_name not in cls._ufuncs: + return None + + op_name = cls._ufuncs[ufunc_name] + return cls.get_operation(op_name) + + @classmethod + def rebuilt_ufunc_cache(cls): + """ + Rebuilts the internal cache of ufuncs. + """ + cls._ufuncs.clear() + for name, op in cls._instances.items(): + if op.ufunc_name: + cls._ufuncs[op.ufunc_name] = name + # # pre-registered operations # [email protected] [email protected](ufunc="add") def add(x, n): """ add(x, n) Addition function. @@ -1035,7 +1117,7 @@ def add(x, n): return 1. [email protected] [email protected](ufunc="subtract") def sub(x, n): """ sub(x, n) Subtraction function. @@ -1048,7 +1130,7 @@ def sub(x, n): return 1. [email protected] [email protected](ufunc="multiply") def mul(x, n): """ mul(x, n) Multiplication function. @@ -1061,7 +1143,7 @@ def mul(x, n): return n [email protected] [email protected](ufunc="divide") def div(x, n): """ div(x, n) Division function. @@ -1074,7 +1156,7 @@ def div(x, n): return 1. / n [email protected] [email protected](ufunc="power") def pow(x, n): """ pow(x, n) Power function. @@ -1087,7 +1169,7 @@ def pow(x, n): return n * x**(n - 1.) [email protected] [email protected](ufunc="exp") def exp(x): """ exp(x) Exponential function. @@ -1098,7 +1180,7 @@ def exp(x): exp.derivative = exp.function [email protected] [email protected](ufunc="log") def log(x, base=None): """ log(x, base=e) Logarithmic function. @@ -1121,7 +1203,33 @@ def log(x, base=None): return 1. / (x * infer_math(x).log(base)) [email protected] [email protected](ufunc="log10") +def log10(x): + """ log10(x) + Logarithmic function with base 10. + """ + return log.function(x, base=10.) + + [email protected] +def log10(x): + return log.derivative(x, base=10.) + + [email protected](ufunc="log2") +def log2(x): + """ log2(x) + Logarithmic function with base 2. + """ + return log.function(x, base=2.) + + [email protected] +def log2(x): + return log.derivative(x, base=2.) + + [email protected](ufunc="sqrt") def sqrt(x): """ sqrt(x) Square root function. @@ -1134,7 +1242,7 @@ def sqrt(x): return 1. / (2 * infer_math(x).sqrt(x)) [email protected] [email protected](ufunc="sin") def sin(x): """ sin(x) Trigonometric sin function. @@ -1147,7 +1255,7 @@ def sin(x): return infer_math(x).cos(x) [email protected] [email protected](ufunc="cos") def cos(x): """ cos(x) Trigonometric cos function. @@ -1160,7 +1268,7 @@ def cos(x): return -infer_math(x).sin(x) [email protected] [email protected](ufunc="tan") def tan(x): """ tan(x) Trigonometric tan function. @@ -1173,7 +1281,7 @@ def tan(x): return 1. / infer_math(x).cos(x)**2. [email protected] [email protected](ufunc="arcsin") def asin(x): """ asin(x) Trigonometric arc sin function. @@ -1190,7 +1298,7 @@ def asin(x): return 1. / infer_math(x).sqrt(1 - x**2.) [email protected] [email protected](ufunc="arccos") def acos(x): """ acos(x) Trigonometric arc cos function. @@ -1207,7 +1315,7 @@ def acos(x): return -1. / infer_math(x).sqrt(1 - x**2.) [email protected] [email protected](ufunc="arctan") def atan(x): """ tan(x) Trigonometric arc tan function. @@ -1224,7 +1332,7 @@ def atan(x): return 1. / (1 + x**2.) [email protected] [email protected](ufunc="sinh") def sinh(x): """ sinh(x) Hyperbolic sin function. @@ -1237,7 +1345,7 @@ def sinh(x): return infer_math(x).cosh(x) [email protected] [email protected](ufunc="cosh") def cosh(x): """ cosh(x) Hyperbolic cos function. @@ -1250,7 +1358,7 @@ def cosh(x): return infer_math(x).sinh(x) [email protected] [email protected](ufunc="tanh") def tanh(x): """ tanh(x) Hyperbolic tan function. @@ -1263,7 +1371,7 @@ def tanh(x): return 1. / infer_math(x).cosh(x)**2. [email protected] [email protected](ufunc="arcsinh") def asinh(x): """ asinh(x) Hyperbolic arc sin function. @@ -1275,7 +1383,7 @@ def asinh(x): return _math.arcsinh(x) [email protected] [email protected](ufunc="arccosh") def acosh(x): """ acosh(x) Hyperbolic arc cos function. @@ -1291,7 +1399,7 @@ asinh.derivative = acosh.function acosh.derivative = asinh.function [email protected] [email protected](ufunc="arctanh") def atanh(x): """ atanh(x) Hyperbolic arc tan function.
riga/scinum
6cce25ebc2ca3afdb37b40635cbcc34ef2cdd62b
diff --git a/tests/__init__.py b/tests/__init__.py index b310322..a91386a 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -298,7 +298,7 @@ class TestCase(unittest.TestCase): self.assertFalse("foo" in ops) - @ops.register + @ops.register(ufunc="abc") def foo(x, a, b, c): return a + b * x + c * x ** 2 @@ -306,12 +306,29 @@ class TestCase(unittest.TestCase): self.assertEqual(ops.get_operation("foo"), foo) self.assertIsNone(foo.derivative) + self.assertEqual(foo.ufunc_name, "abc") + self.assertEqual(ops.get_ufunc_operation("abc"), foo) + @foo.derive def foo(x, a, b, c): return b + 2 * c * x self.assertTrue(callable(foo.derivative)) + @if_numpy + def test_ufuncs(self): + num = np.multiply(self.num, 2) + self.assertAlmostEqual(num(), self.num() * 2.) + self.assertAlmostEqual(num.u("A", UP), 1.) + self.assertAlmostEqual(num.u("B", UP), 2.) + self.assertAlmostEqual(num.u("C", DOWN), 3.) + + num = np.exp(Number(np.array([1., 2.]), 3.)) + self.assertAlmostEqual(num.nominal[0], 2.71828, 4) + self.assertAlmostEqual(num.nominal[1], 7.38906, 4) + self.assertAlmostEqual(num.get(UP)[0], 10.87313, 4) + self.assertAlmostEqual(num.get(UP)[1], 29.55623, 4) + def test_op_pow(self): num = ops.pow(self.num, 2) self.assertEqual(num(), self.num() ** 2.)
Implement numpy ufuncs Example: ```python import numpy >>> class WithVariance(numpy.lib.mixins.NDArrayOperatorsMixin): ... def __init__(self, number, variance): ... self.number = number ... self.variance = variance ... ... @property ... def error(self): ... return numpy.sqrt(variance) ... ... def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): ... if method != "__call__" or len(inputs) == 0 or "out" in kwargs: ... return NotImplemented ... ... if ufunc is numpy.add: ... return WithVariance( ... inputs[0].number + inputs[1].number, ... inputs[0].variance + inputs[1].variance, ... ) ... else: ... return NotImplemented >>> x = WithVariance(numpy.array([1, 2, 3]), numpy.array([0.1, 0.2, 0.3])**2) >>> y = WithVariance(numpy.array([1, 2, 3]), numpy.array([0.1, 0.2, 0.3])**2) >>> (x + y).number array([2, 4, 6]) >>> (x + y).variance array([0.02, 0.08, 0.18]) ```
0.0
6cce25ebc2ca3afdb37b40635cbcc34ef2cdd62b
[ "tests/__init__.py::TestCase::test_ops_registration" ]
[ "tests/__init__.py::TestCase::test_calculate_uncertainty", "tests/__init__.py::TestCase::test_constructor", "tests/__init__.py::TestCase::test_constructor_numpy", "tests/__init__.py::TestCase::test_constructor_ufloat", "tests/__init__.py::TestCase::test_copy", "tests/__init__.py::TestCase::test_copy_numpy", "tests/__init__.py::TestCase::test_infer_si_prefix", "tests/__init__.py::TestCase::test_match_precision", "tests/__init__.py::TestCase::test_match_precision_numpy", "tests/__init__.py::TestCase::test_op_cos", "tests/__init__.py::TestCase::test_op_exp", "tests/__init__.py::TestCase::test_op_log", "tests/__init__.py::TestCase::test_op_pow", "tests/__init__.py::TestCase::test_op_sin", "tests/__init__.py::TestCase::test_op_tan", "tests/__init__.py::TestCase::test_round_uncertainty", "tests/__init__.py::TestCase::test_round_uncertainty_numpy", "tests/__init__.py::TestCase::test_round_value", "tests/__init__.py::TestCase::test_round_value_list", "tests/__init__.py::TestCase::test_round_value_numpy", "tests/__init__.py::TestCase::test_split_value", "tests/__init__.py::TestCase::test_split_value_numpy", "tests/__init__.py::TestCase::test_strings", "tests/__init__.py::TestCase::test_ufuncs", "tests/__init__.py::TestCase::test_uncertainty_combination", "tests/__init__.py::TestCase::test_uncertainty_parsing", "tests/__init__.py::TestCase::test_uncertainty_propagation" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-17 14:16:27+00:00
bsd-3-clause
5,256
rigetti__pyquil-1419
diff --git a/CHANGELOG.md b/CHANGELOG.md index 88a9f21..caaff41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ Changelog - Allow `np.ndarray` when writing QAM memory. Disallow non-integer and non-float types. - Fix typo where `qc.compiler.calibration_program` should be `qc.compiler.get_calibration_program()`. +- `DefFrame` string-valued fields that contain JSON strings now round trip to valid Quil and back to + JSON via `DefFrame.out` and `parse`. Quil and JSON both claim `"` as their only string delimiter, + so the JSON `"`s are escaped in the Quil. [v3.0.0](https://github.com/rigetti/pyquil/releases/tag/v3.0.0) ------------------------------------------------------------------------------------ diff --git a/pyquil/_parser/grammar.lark b/pyquil/_parser/grammar.lark index 5f0b93a..9a5da3f 100644 --- a/pyquil/_parser/grammar.lark +++ b/pyquil/_parser/grammar.lark @@ -60,7 +60,7 @@ def_circuit : "DEFCIRCUIT" name [ variables ] [ qubit_designators ] ":" indented // | "DEFCIRCUIT" name [ variables ] qubit_designators ":" indented_instrs -> def_circuit_qubits def_frame : "DEFFRAME" frame ( ":" frame_spec+ )? -frame_spec : _NEWLINE_TAB frame_attr ":" (expression | string ) +frame_spec : _NEWLINE_TAB frame_attr ":" ( expression | string ) !frame_attr : "SAMPLE-RATE" | "INITIAL-FREQUENCY" | "DIRECTION" diff --git a/pyquil/_parser/parser.py b/pyquil/_parser/parser.py index 0b345fd..c8ebd28 100644 --- a/pyquil/_parser/parser.py +++ b/pyquil/_parser/parser.py @@ -1,3 +1,4 @@ +import json import pkgutil import operator from typing import List @@ -142,10 +143,7 @@ class QuilTransformer(Transformer): # type: ignore for (spec_name, spec_value) in specs: name = names.get(spec_name, None) if name: - if isinstance(spec_value, str) and spec_value[0] == '"' and spec_value[-1] == '"': - # Strip quotes if necessary - spec_value = spec_value[1:-1] - options[name] = spec_value + options[name] = json.loads(str(spec_value)) else: raise ValueError( f"Unexpectected attribute {spec_name} in definition of frame {frame}. " f"{frame}, {specs}" diff --git a/pyquil/quilbase.py b/pyquil/quilbase.py index f3ec7b0..476602d 100644 --- a/pyquil/quilbase.py +++ b/pyquil/quilbase.py @@ -17,6 +17,8 @@ Contains the core pyQuil objects that correspond to Quil instructions. """ import collections +import json + from numbers import Complex from typing import ( Any, @@ -1375,7 +1377,6 @@ class DefFrame(AbstractInstruction): for value, name in options: if value is None: continue - if isinstance(value, str): - value = f'"{value}"' - r += f"\n {name}: {value}" + else: + r += f"\n {name}: {json.dumps(value)}" return r + "\n"
rigetti/pyquil
010fde6b15797a629620aba03715ecf7d51d6cc7
diff --git a/test/unit/test_parser.py b/test/unit/test_parser.py index 16b190b..c0995c1 100644 --- a/test/unit/test_parser.py +++ b/test/unit/test_parser.py @@ -604,6 +604,29 @@ def test_parsing_defframe(): assert excp.value.token == Token("IDENTIFIER", "UNSUPPORTED") +def test_parsing_defframe_round_trip_with_json(): + fdef = DefFrame( + frame=Frame(qubits=[FormalArgument("My-Cool-Qubit")], name="bananas"), + direction="go west", + initial_frequency=123.4, + center_frequency=124.5, + hardware_object='{"key1": 3.1, "key2": "value2"}', + sample_rate=5, + ) + fdef_out = fdef.out() + assert ( + fdef.out() + == r"""DEFFRAME My-Cool-Qubit "bananas": + DIRECTION: "go west" + INITIAL-FREQUENCY: 123.4 + CENTER-FREQUENCY: 124.5 + HARDWARE-OBJECT: "{\"key1\": 3.1, \"key2\": \"value2\"}" + SAMPLE-RATE: 5 +""" + ) + parse_equals(fdef_out, fdef) + + def test_parsing_defcal(): parse_equals("DEFCAL X 0:\n" " NOP\n", DefCalibration("X", [], [Qubit(0)], [NOP])) parse_equals(
Pyquil cannot round-trip programs as strings if they contain special characters Section 12.1.1 of the [Quil specification](https://quil-lang.github.io/) says that the predicate of a frame specification may contain a string. Thus, I expect to be able to round-trip the following program: ``` from pyquil import Program from pyquil.quilbase import DefFrame from pyquil.quilatom import Frame, Qubit qubit = Qubit(1) tx_frame = Frame(qubits=[qubit], name=f"transmitter_q1") df = DefFrame( frame=tx_frame, direction="tx", initial_frequency=7.125e9, center_frequency=7.125e9, hardware_object='{"key": "value", "key2": "value2"}', sample_rate=1000000000, ) p = Program(df) assert Program(str(p)) == p ``` However, `pyquil 3.0.1` throws an exception on parsing: ``` UnexpectedCharacters: No terminal matches '{' in the current parser context ``` There appear to be two problems here: 1. pyquil's `grammar.lark` defines the predicate of a frame specification to be a `name` surrounded by double quotes, rather than a string. I think this is what's causing the parsing error on the curly braces. This is in contrast to PRAGMA's grammar definition, which allows strings. (Curly braces are used inside FILTER-NODE definitions) 2. pyquil does not escape the double quotes inside the hardware object string before returning the program in string format.
0.0
010fde6b15797a629620aba03715ecf7d51d6cc7
[ "test/unit/test_parser.py::test_parsing_defframe_round_trip_with_json" ]
[ "test/unit/test_parser.py::test_simple_gate", "test/unit/test_parser.py::test_standard_gates", "test/unit/test_parser.py::test_def_gate", "test/unit/test_parser.py::test_def_gate_with_variables", "test/unit/test_parser.py::test_def_gate_as", "test/unit/test_parser.py::test_def_gate_as_matrix", "test/unit/test_parser.py::test_def_permutation_gate", "test/unit/test_parser.py::test_def_gate_as_permutation", "test/unit/test_parser.py::test_parameters", "test/unit/test_parser.py::test_expressions", "test/unit/test_parser.py::test_measure", "test/unit/test_parser.py::test_jumps", "test/unit/test_parser.py::test_others", "test/unit/test_parser.py::test_memory_commands", "test/unit/test_parser.py::test_classical", "test/unit/test_parser.py::test_pragma", "test/unit/test_parser.py::test_empty_program", "test/unit/test_parser.py::test_def_circuit", "test/unit/test_parser.py::test_parse_reset_qubit", "test/unit/test_parser.py::test_parse_dagger", "test/unit/test_parser.py::test_parse_controlled", "test/unit/test_parser.py::test_parse_forked", "test/unit/test_parser.py::test_messy_modifiers", "test/unit/test_parser.py::test_parse_template_waveforms", "test/unit/test_parser.py::test_parse_template_waveform_strict_values", "test/unit/test_parser.py::test_parse_pulse", "test/unit/test_parser.py::test_parsing_capture", "test/unit/test_parser.py::test_parsing_raw_capture", "test/unit/test_parser.py::test_parsing_frame_mutations", "test/unit/test_parser.py::test_parsing_swap_phase", "test/unit/test_parser.py::test_parsing_delay", "test/unit/test_parser.py::test_parsing_fence", "test/unit/test_parser.py::test_parsing_defwaveform", "test/unit/test_parser.py::test_parsing_defframe", "test/unit/test_parser.py::test_parsing_defcal", "test/unit/test_parser.py::test_parsing_defcal_measure", "test/unit/test_parser.py::test_parse_defcal_error_on_mref", "test/unit/test_parser.py::test_parse_defgate_as_pauli", "test/unit/test_parser.py::test_parse_comments[#", "test/unit/test_parser.py::test_parse_comments[H", "test/unit/test_parser.py::test_parse_strings_with_spaces" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-09 06:20:09+00:00
apache-2.0
5,257
rigetti__pyquil-1694
diff --git a/pyquil/api/_qpu.py b/pyquil/api/_qpu.py index 0dee979..a4815fe 100644 --- a/pyquil/api/_qpu.py +++ b/pyquil/api/_qpu.py @@ -188,16 +188,17 @@ class QPU(QAM[QPUExecuteResponse]): memory_map = memory_map or {} patch_values = build_patch_values(executable.recalculation_table, memory_map) + effective_execution_options = execution_options or self.execution_options job_id = submit( program=executable.program, patch_values=patch_values, quantum_processor_id=self.quantum_processor_id, client=self._client_configuration, - execution_options=execution_options or self.execution_options, + execution_options=effective_execution_options, ) - return QPUExecuteResponse(_executable=executable, job_id=job_id, execution_options=execution_options) + return QPUExecuteResponse(_executable=executable, job_id=job_id, execution_options=effective_execution_options) def get_result(self, execute_response: QPUExecuteResponse) -> QAMExecutionResult: """
rigetti/pyquil
a6429bd2bd623e8571728e7108e6bdf50fa92cbb
diff --git a/test/unit/test_qpu.py b/test/unit/test_qpu.py index 8857982..8f90633 100644 --- a/test/unit/test_qpu.py +++ b/test/unit/test_qpu.py @@ -3,7 +3,7 @@ from unittest.mock import patch, MagicMock import numpy as np -from pyquil.api import ConnectionStrategy, ExecutionOptions, RegisterMatrixConversionError +from pyquil.api import ConnectionStrategy, ExecutionOptions, RegisterMatrixConversionError, ExecutionOptionsBuilder from pyquil.api._qpu import QPU from pyquil.api._abstract_compiler import EncryptedProgram from pyquil.quil import Program @@ -105,3 +105,77 @@ def test_qpu_execute_jagged_results( assert raw_readout_data.mappings == {"ro[0]": "q0", "ro[1]": "q1"} assert raw_readout_data.readout_values == {"q0": [1, 1], "q1": [1, 1, 1, 1]} + + +class TestQPUExecutionOptions: + @patch("pyquil.api._qpu.retrieve_results") + @patch("pyquil.api._qpu.submit") + def test_submit_with_class_options( + self, mock_submit: MagicMock, mock_retrieve_results: MagicMock, mock_encrypted_program: EncryptedProgram + ): + """ + Asserts that a ``QPU``'s execution_options property is used for submission, appears in the returned + ``QPUExecuteResponse``, and is used for retrieval of results when execution options are not provided to + ``QPU.execute``. + """ + qpu = QPU(quantum_processor_id="test") + execution_options_builder = ExecutionOptionsBuilder() + execution_options_builder.timeout_seconds = 10.0 + execution_options_builder.connection_strategy = ConnectionStrategy.endpoint_id("some-endpoint-id") + execution_options = execution_options_builder.build() + qpu.execution_options = execution_options + + mock_submit.return_value = "some-job-id" + execute_response = qpu.execute(mock_encrypted_program) + assert execute_response.execution_options == qpu.execution_options + + mock_retrieve_results.return_value = ExecutionResults( + { + "q0": ExecutionResult.from_register(Register.from_i32([1, 1])), + "q1": ExecutionResult.from_register(Register.from_i32([1, 1, 1, 1])), + } + ) + + qpu.get_result(execute_response) + + mock_retrieve_results.assert_called_once_with( + job_id="some-job-id", + quantum_processor_id="test", + client=qpu._client_configuration, + execution_options=qpu.execution_options, + ) + + @patch("pyquil.api._qpu.retrieve_results") + @patch("pyquil.api._qpu.submit") + def test_submit_with_options( + self, mock_submit: MagicMock, mock_retrieve_results: MagicMock, mock_encrypted_program: EncryptedProgram + ): + """ + Asserts that execution_options provided to ``QPU.execute`` are used for submission, appear in the returned + ``QPUExecuteResponse``, and are used for retrieval of results. + """ + qpu = QPU(quantum_processor_id="test") + + mock_submit.return_value = "some-job-id" + execution_options_builder = ExecutionOptionsBuilder() + execution_options_builder.timeout_seconds = 10.0 + execution_options_builder.connection_strategy = ConnectionStrategy.endpoint_id("some-endpoint-id") + execution_options = execution_options_builder.build() + execute_response = qpu.execute(mock_encrypted_program, execution_options=execution_options) + assert execute_response.execution_options == execution_options + + mock_retrieve_results.return_value = ExecutionResults( + { + "q0": ExecutionResult.from_register(Register.from_i32([1, 1])), + "q1": ExecutionResult.from_register(Register.from_i32([1, 1, 1, 1])), + } + ) + + qpu.get_result(execute_response) + + mock_retrieve_results.assert_called_once_with( + job_id="some-job-id", + quantum_processor_id="test", + client=qpu._client_configuration, + execution_options=execution_options, + )
Bug: QPU.execution_options not used for QPU.retrieve_results `QPU` allows `execution_options` to be set on both the class instance itself (`self.execution_options`) or on the `.execute` request(`execution_options` arg). It follows the right precedence order when calling `submit`, but does not consider `self.execution_options` in the construction of `QPUExecuteResponse` ([here](https://github.com/rigetti/pyquil/blob/a6429bd2bd623e8571728e7108e6bdf50fa92cbb/pyquil/api/_qpu.py#L200)). One effect of this: if `get_qc()` is invoked with an `endpoint_id`, that endpoint is not used for results retrieval, and pyQuil tries to use the default instead (gateway). If no such gateway exists, then results retrieval fails. This can be quickly fixed, and should be covered with a new test.
0.0
a6429bd2bd623e8571728e7108e6bdf50fa92cbb
[ "test/unit/test_qpu.py::TestQPUExecutionOptions::test_submit_with_class_options" ]
[ "test/unit/test_qpu.py::test_default_execution_options", "test/unit/test_qpu.py::test_provided_execution_options", "test/unit/test_qpu.py::test_qpu_execute", "test/unit/test_qpu.py::test_qpu_execute_jagged_results", "test/unit/test_qpu.py::TestQPUExecutionOptions::test_submit_with_options" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-11-15 19:52:43+00:00
apache-2.0
5,258
rigetti__pyquil-1756
diff --git a/pyquil/quilatom.py b/pyquil/quilatom.py index 7cd7e7c..ab23c12 100644 --- a/pyquil/quilatom.py +++ b/pyquil/quilatom.py @@ -791,8 +791,12 @@ def _expression_to_string(expression: ExpressionDesignator) -> str: right = "(" + right + ")" # If op2 is a float, it will maybe represented as a multiple # of pi in right. If that is the case, then we need to take - # extra care to insert parens. See gh-943. - elif isinstance(expression.op2, float) and (("pi" in right and right != "pi")): + # extra care to insert parens. Similarly, complex numbers need + # to be wrapped in parens so the imaginary part is captured. + # See gh-943,1734. + elif (isinstance(expression.op2, float) and (("pi" in right and right != "pi"))) or isinstance( + expression.op2, complex + ): right = "(" + right + ")" return left + expression.operator + right
rigetti/pyquil
2cabc84d7f0c379f9b59e0403e8418d1411b55c0
diff --git a/test/unit/test_parameters.py b/test/unit/test_parameters.py index ebbbd73..80dac81 100644 --- a/test/unit/test_parameters.py +++ b/test/unit/test_parameters.py @@ -65,12 +65,15 @@ def test_expression_to_string(): assert str((x + y) - 2) == "%x + %y - 2" assert str(x + (y - 2)) == "%x + %y - 2" - assert str(x ** y ** 2) == "%x^%y^2" - assert str(x ** (y ** 2)) == "%x^%y^2" - assert str((x ** y) ** 2) == "(%x^%y)^2" + assert str(x**y**2) == "%x^%y^2" + assert str(x ** (y**2)) == "%x^%y^2" + assert str((x**y) ** 2) == "(%x^%y)^2" assert str(quil_sin(x)) == "SIN(%x)" assert str(3 * quil_sin(x + y)) == "3*SIN(%x + %y)" + assert ( + str(quil_exp(-1j * x / 2) * np.exp(1j * np.pi / 4)) == "EXP(-i*%x/2)*(0.7071067811865476+0.7071067811865475i)" + ) def test_contained_parameters(): @@ -80,7 +83,7 @@ def test_contained_parameters(): y = Parameter("y") assert _contained_parameters(x + y) == {x, y} - assert _contained_parameters(x ** y ** quil_sin(x * y * 4)) == {x, y} + assert _contained_parameters(x**y ** quil_sin(x * y * 4)) == {x, y} def test_eval(): @@ -93,7 +96,7 @@ def test_eval(): assert substitute(quil_exp(x), {y: 5}) != np.exp(5) assert substitute(quil_exp(x), {x: 5}) == np.exp(5) - assert np.isclose(substitute(quil_sin(x * x ** 2 / y), {x: 5.0, y: 10.0}), np.sin(12.5)) + assert np.isclose(substitute(quil_sin(x * x**2 / y), {x: 5.0, y: 10.0}), np.sin(12.5)) assert np.isclose(substitute(quil_sqrt(x), {x: 5.0, y: 10.0}), np.sqrt(5.0)) assert np.isclose(substitute(quil_cis(x), {x: 5.0, y: 10.0}), np.exp(1j * 5.0)) assert np.isclose(substitute(x - y, {x: 5.0, y: 10.0}), -5.0) diff --git a/test/unit/test_rewrite_arithmetic.py b/test/unit/test_rewrite_arithmetic.py index c846f65..896428a 100644 --- a/test/unit/test_rewrite_arithmetic.py +++ b/test/unit/test_rewrite_arithmetic.py @@ -36,7 +36,7 @@ def test_rewrite_arithmetic_duplicate_exprs(): assert response == RewriteArithmeticResponse( original_memory_descriptors={"theta": ParameterSpec(length=1, type="REAL")}, - recalculation_table={ParameterAref(index=0, name="__P1"): "theta[0]*1.5/(2*pi)"}, + recalculation_table={ParameterAref(index=0, name="__P1"): "theta[0]*(1.5)/(2*pi)"}, quil=Program("DECLARE __P1 REAL[1]", "DECLARE theta REAL[1]", "RZ(__P1[0]) 0", "RX(__P1[0]) 0").out(), )
Expressions are parsed incorrectly by Defgate ### Code Snippet ```python import numpy as np from pyquil.quilbase import DefGate from pyquil.quilatom import quil_exp, Parameter phi = Parameter("phi") rz = np.array( [ [quil_exp(-1j*phi/2), 0], [0, quil_exp(+1j*phi/2)], ] ) print(DefGate(name="blarg", matrix=rz, parameters=[phi])) rz2 = np.array( [ [quil_exp(-1j*phi/2)*np.exp(1j*np.pi/4), 0], [0, quil_exp(+1j*phi/2)*np.exp(1j*np.pi/4)], ] ) print(rz2[0,0]) print(DefGate(name="blarg", matrix=rz2, parameters=[phi])) ``` ### Error Output The first defgate outputs as expected. The second output is the expression, `EXP(-i*%phi/2)*0.7071067811865476+0.7071067811865475i` While the expression is ambiguous, a closer look reveals that it is structured correctly: `Mul(Function('EXP',Div(Mul((-0-1j),Parameter('phi')),2),<ufunc 'exp'>),(0.7071067811865476+0.7071067811865475j)) ` The exponential is multiplied by the complex number. In the defgate, it's clear this is not the case. The expression is the exponential multiplied by the real part of the complex number, while the imaginary part is then added after the fact. Ie: `(a+bi)*exp(theta)` vs `a*exp(theta) + bi` A closer look at the matrix reveals this to be the case: `Add(Mul(Function('EXP',Div(Mul((-0-1j),Parameter('phi')),(2+0j)),<ufunc 'exp'>),(0.7071067811865476+0j)),0.7071067811865475j) ` ``` DEFGATE blarg(%phi) AS MATRIX: exp((-1.0i*%phi)/2), 0 0, exp((1.0i*%phi)/2) EXP(-i*%phi/2)*0.7071067811865476+0.7071067811865475i DEFGATE blarg(%phi) AS MATRIX: (exp((-1.0i*%phi)/2)*0.7071067811865476)+0.7071067811865475i, 0 0, (exp((1.0i*%phi)/2)*0.7071067811865476)+0.7071067811865475i ```
0.0
2cabc84d7f0c379f9b59e0403e8418d1411b55c0
[ "test/unit/test_parameters.py::test_expression_to_string", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_duplicate_exprs" ]
[ "test/unit/test_parameters.py::test_format_parameter", "test/unit/test_parameters.py::test_pretty_print_pi", "test/unit/test_parameters.py::test_contained_parameters", "test/unit/test_parameters.py::test_eval", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_no_params", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_simple_mref", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_mixed", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_set_scale", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_frequency", "test/unit/test_rewrite_arithmetic.py::test_rewrite_arithmetic_mixed_mutations" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2024-03-25 22:46:54+00:00
apache-2.0
5,259
rikithreddy__datastructs-pylibrary-10
diff --git a/datastructs/arrays/SingleDimensionArray.py b/datastructs/arrays/SingleDimensionArray.py index eca4e4e..69f94a7 100644 --- a/datastructs/arrays/SingleDimensionArray.py +++ b/datastructs/arrays/SingleDimensionArray.py @@ -1,14 +1,29 @@ from ..common import Node +from ..exceptions.custom import ( + InvalidArraySize, + InvalidDataType, + InvalidArrayIndex, + InvalidArrayInitializerSize + ) + class SingleDimensionArray: def _check_index(self, index): if index < 0 or index >= self.size: - raise IndexError + raise InvalidArrayIndex( + "Expected range of index 0 to {}, Provided {}". + format(self.size, index) + ) def _check_value(self, elem): if not isinstance(elem, self.elem_type): - raise ValueError + raise InvalidDataType( + "Expected data object of {}, Recieved {}".format( + self.elem_type, + type(elem) + ) + ) def __init__(self, elem_type, size, init=[]): self.size = size @@ -21,8 +36,7 @@ class SingleDimensionArray: self._check_value(elem) self.array[id].data = elem else: - print("Invalid initialization size") - raise ValueError + raise InvalidArrayInitializerSize def get(self, index): self._check_index(index) diff --git a/datastructs/exceptions/__init__.py b/datastructs/exceptions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/datastructs/exceptions/custom.py b/datastructs/exceptions/custom.py new file mode 100644 index 0000000..e700a6f --- /dev/null +++ b/datastructs/exceptions/custom.py @@ -0,0 +1,31 @@ +class StackOverFlowException(Exception): + def __init__(self, message): + super().__init__(message) + +class StackUnderFlowException(Exception): + def __init__(self): + super().__init__("The stack is empty") + +class StackEmpty(Exception): + pass + +class QueueEmpty(Exception): + pass + +class LinkedListEmpty(Exception): + pass + +class InvalidArraySize(Exception): + pass + +class InvalidArrayIndex(Exception): + def __init__(self, message): + super().__init__(message) + +class InvalidArrayInitializerSize(Exception): + pass + + +class InvalidDataType(Exception): + def __init__(self, msg): + super().__init__(msg) \ No newline at end of file diff --git a/datastructs/lists/SingleLinkList.py b/datastructs/lists/SingleLinkList.py index 1ff2b8e..601f178 100644 --- a/datastructs/lists/SingleLinkList.py +++ b/datastructs/lists/SingleLinkList.py @@ -2,11 +2,21 @@ from ..common import Node from sys import stdout from copy import copy +from ..exceptions.custom import ( + InvalidDataType, + LinkedListEmpty + ) + class SingleLinkList: def _check_value(self, elem): if not isinstance(elem, self.elem_type): - raise ValueError + raise InvalidDataType( + "Expected data object of {}, Recieved {}".format( + self.elem_type, + type(elem) + ) + ) def __init__(self, elem_type, has_tail=True): self.head = Node() @@ -42,15 +52,12 @@ class SingleLinkList: if self.head.next is not None: return self.head.next.data else: - # TODO: Add Error - print("List is empty") - raise IndexError + raise LinkedListEmpty def pop_first_element(self): if self.head and not self.head.next: - # TODO: Add error - print("Error List is empty") - raise IndexError + raise LinkedListEmpty + if self.has_tail and self.tail == self.head.next: self.tail = self.head node = self.head.next @@ -90,9 +97,7 @@ class SingleLinkList: if not self.list_empty(): return self.get_last_node().data else: - # TODO: Add Error - print("List is empty") - raise IndexError + raise LinkedListEmpty def find_element(self, data): ''' diff --git a/datastructs/queues/ListQueue.py b/datastructs/queues/ListQueue.py index 89e10c2..e562e52 100644 --- a/datastructs/queues/ListQueue.py +++ b/datastructs/queues/ListQueue.py @@ -1,4 +1,8 @@ from ..lists.SingleLinkList import SingleLinkList +from ..exceptions.custom import ( + QueueEmpty, + LinkedListEmpty + ) class ListQueue: @@ -12,11 +16,14 @@ class ListQueue: def next_key(self): if self.queue_empty(): - raise IndexError + raise QueueEmpty return self.top.next.data def enqueue(self, key): self.queue.add_to_back(key) def dequeue(self): - return self.queue.pop_first_element() \ No newline at end of file + try: + return self.queue.pop_first_element() + except LinkedListEmpty: + raise QueueEmpty \ No newline at end of file diff --git a/datastructs/stacks/ListStack.py b/datastructs/stacks/ListStack.py index 177ebc8..bcaae8d 100644 --- a/datastructs/stacks/ListStack.py +++ b/datastructs/stacks/ListStack.py @@ -1,4 +1,8 @@ from ..lists.SingleLinkList import SingleLinkList +from ..exceptions.custom import ( + StackUnderFlowException, + LinkedListEmpty + ) class ListStack: @@ -12,11 +16,14 @@ class ListStack: def top_elem(self): if self.stack_empty(): - raise IndexError + raise StackUnderFlowException return self.top.next.data def pop(self): - return self.stack.pop_first_element() - + try: + return self.stack.pop_first_element() + except LinkedListEmpty: + raise StackUnderFlowException + def push(self, elem_type): self.stack.add_to_front(elem_type) \ No newline at end of file
rikithreddy/datastructs-pylibrary
ea0b22fe15f3cd19be0a46742f11b99de6faeef2
diff --git a/tests/test_array.py b/tests/test_array.py index fe18aff..0601584 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -1,29 +1,37 @@ from datastructs.arrays.SingleDimensionArray import SingleDimensionArray as array import unittest +from datastructs.exceptions.custom import ( + InvalidArraySize, + InvalidDataType, + InvalidArrayIndex, + InvalidArrayInitializerSize + ) + + class TestArray(unittest.TestCase): def test_1d_Array(self): - self.assertRaises(ValueError, array, int, 1, [1,2]) + self.assertRaises(InvalidArrayInitializerSize, array, int, 1, [1,2]) - self.assertRaises(ValueError, array, int, 2, [1]) + self.assertRaises(InvalidArrayInitializerSize, array, int, 2, [1]) - self.assertRaises(ValueError, array, str, 1, [1]) + self.assertRaises(InvalidDataType, array, str, 1, [1]) - self.assertRaises(ValueError, array, int, 2, [1,"12"]) + self.assertRaises(InvalidDataType, array, int, 2, [1,"12"]) ar = array(int, 5, [1, 2, 3, 4, 5]) ar.update(1, 99) self.assertEqual(ar.get(0), 1) self.assertEqual(ar.get(1), 99) - self.assertRaises(ValueError, ar.update, 1, "0") - self.assertRaises(IndexError, ar.update, -1, 0) - self.assertRaises(IndexError, ar.update, 1000, 0) - self.assertRaises(IndexError, ar.get, 1000) - self.assertRaises(IndexError, ar.get, -1) + self.assertRaises(InvalidDataType, ar.update, 1, "0") + self.assertRaises(InvalidArrayIndex, ar.update, -1, 0) + self.assertRaises(InvalidArrayIndex, ar.update, 1000, 0) + self.assertRaises(InvalidArrayIndex, ar.get, 1000) + self.assertRaises(InvalidArrayIndex, ar.get, -1) if __name__ == '__main__': diff --git a/tests/test_lists.py b/tests/test_lists.py index 4692215..1cfbd9e 100644 --- a/tests/test_lists.py +++ b/tests/test_lists.py @@ -1,12 +1,16 @@ -from datastructs.lists.SingleLinkList import SingleLinkList import unittest +from datastructs.lists.SingleLinkList import SingleLinkList +from datastructs.exceptions.custom import ( + InvalidDataType, + LinkedListEmpty + ) class TestSingleLinkList(unittest.TestCase): def list_operations(self, custom_list): - self.assertRaises(IndexError, custom_list.pop_first_element) - self.assertRaises(IndexError, custom_list.get_first_element) - self.assertRaises(IndexError, custom_list.get_last_element) + self.assertRaises(LinkedListEmpty, custom_list.pop_first_element) + self.assertRaises(LinkedListEmpty, custom_list.get_first_element) + self.assertRaises(LinkedListEmpty, custom_list.get_last_element) self.assertTrue(custom_list.list_empty()) custom_list.add_to_front(0) custom_list.add_to_back(1) @@ -23,8 +27,8 @@ class TestSingleLinkList(unittest.TestCase): self.assertFalse(custom_list.has_element(0)) self.assertTrue(custom_list.has_element(1)) - self.assertRaises(ValueError, custom_list.add_to_front, "123") - self.assertRaises(ValueError, custom_list.add_to_back, "123") + self.assertRaises(InvalidDataType, custom_list.add_to_front, "123") + self.assertRaises(InvalidDataType, custom_list.add_to_back, "123") def test_add_remove(self): custom_list = SingleLinkList(int) diff --git a/tests/test_queue.py b/tests/test_queue.py index 1d52adc..1df34e5 100644 --- a/tests/test_queue.py +++ b/tests/test_queue.py @@ -1,20 +1,24 @@ -from datastructs.queues.ListQueue import ListQueue import unittest +from datastructs.queues.ListQueue import ListQueue +from datastructs.exceptions.custom import ( + InvalidDataType, + QueueEmpty + ) -class TestArray(unittest.TestCase): +class TestQueue(unittest.TestCase): def test_list_queue(self): queue = ListQueue(int) self.assertTrue(queue.queue_empty()) - self.assertRaises(IndexError, queue.dequeue) - self.assertRaises(IndexError, queue.next_key) + self.assertRaises(QueueEmpty, queue.dequeue) + self.assertRaises(QueueEmpty, queue.next_key) queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) - self.assertRaises(ValueError, queue.enqueue, "4") + self.assertRaises(InvalidDataType, queue.enqueue, "4") self.assertEqual(queue.dequeue(), 1) self.assertEqual(queue.next_key(), 2) diff --git a/tests/test_stack.py b/tests/test_stack.py index 4b7e91f..fe0b0a6 100644 --- a/tests/test_stack.py +++ b/tests/test_stack.py @@ -1,5 +1,9 @@ -from datastructs.stacks.ListStack import ListStack import unittest +from datastructs.stacks.ListStack import ListStack +from datastructs.exceptions.custom import ( + StackUnderFlowException, + InvalidDataType, + ) class TestStack(unittest.TestCase): @@ -8,13 +12,14 @@ class TestStack(unittest.TestCase): stack = ListStack(int) self.assertTrue(stack.stack_empty()) - self.assertRaises(IndexError, stack.pop) - self.assertRaises(IndexError, stack.top_elem) + self.assertRaises(StackUnderFlowException, stack.pop) + self.assertRaises(StackUnderFlowException, stack.top_elem) stack.push(1) stack.push(2) stack.push(3) - self.assertRaises(ValueError, stack.push, "4") + + self.assertRaises(InvalidDataType, stack.push, "4") self.assertEqual(stack.pop(), 3) self.assertEqual(stack.top_elem(), 2)
Add custom exceptions/errors for lists module
0.0
ea0b22fe15f3cd19be0a46742f11b99de6faeef2
[ "tests/test_array.py::TestArray::test_1d_Array", "tests/test_lists.py::TestSingleLinkList::test_add_remove", "tests/test_queue.py::TestQueue::test_list_queue", "tests/test_stack.py::TestStack::test_list_stack" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-04-18 12:38:04+00:00
mit
5,260
riotkit-org__infracheck-34
diff --git a/docs/source/check-configuration-reference.rst b/docs/source/check-configuration-reference.rst new file mode 100644 index 0000000..275bd08 --- /dev/null +++ b/docs/source/check-configuration-reference.rst @@ -0,0 +1,61 @@ +Check configuration reference +############################# + +.. code:: json + + { + "type": "http", + "description": "IWA-AIT check", + "input": { + "url": "http://iwa-ait.org", + "expect_keyword": "iwa", + "not_expect_keyword": "Server error" + }, + "hooks": { + "on_each_up": [ + "rm -f /var/www/maintenance.html" + ], + "on_each_down": [ + "echo \"Site under maintenance\" > /var/www/maintenance.html" + ] + } + } + + +type +**** + +Name of the binary/script file placed in the "checks" directory. At first will look at path specified by "--directory" +CLI parameter, then will fallback to Infracheck internal check library. + +Example values: + +- disk-space +- load-average +- http +- smtp_credentials_check.py + + +description +*********** + +Optional text field, there can be left a note for other administrators to exchange knowledge in a quick way in case +of a failure. + + +input +***** + +Parameters passed to the binary/script file (chosen in "type" field). Case insensitive, everything is converted +to UPPERCASE and passed as environment variables. + +**Notice:** *Environment variables and internal variables can be injected using templating feature - check* :ref:`Templating` + +hooks +***** + +Execute shell commands on given events. + +- on_each_up: Everytime the check is OK +- on_each_down: Everytime the check is FAILING + diff --git a/docs/source/index.rst b/docs/source/index.rst index 5f18c06..2e22400 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -46,6 +46,7 @@ Simple, easy to setup, easy to understand. Works perfectly with Docker. A perfec first-steps hooks reference + check-configuration-reference templating custom-scripts cache diff --git a/infracheck/infracheck/model.py b/infracheck/infracheck/model.py index a9f3dd3..569ca8c 100644 --- a/infracheck/infracheck/model.py +++ b/infracheck/infracheck/model.py @@ -12,21 +12,24 @@ class ExecutedCheckResult(object): hooks_output: str configured_name: str refresh_time: datetime + description: str - def __init__(self, configured_name: str, output: str, exit_status: bool, hooks_output: str): + def __init__(self, configured_name: str, output: str, exit_status: bool, hooks_output: str, description: str): self.configured_name = configured_name self.output = output self.exit_status = exit_status self.hooks_output = hooks_output self.refresh_time = datetime.now() + self.description = description @classmethod - def from_not_ready(cls, configured_name: str): + def from_not_ready(cls, configured_name: str, description: str): check = cls( configured_name=configured_name, output='Check not ready', exit_status=False, - hooks_output='' + hooks_output='', + description=description ) check.refresh_time = None @@ -37,6 +40,7 @@ class ExecutedCheckResult(object): return { 'status': self.exit_status, 'output': self.output, + 'description': self.description, 'hooks_output': self.hooks_output, 'ident': self.configured_name + '=' + str(self.exit_status), 'checked_at': self.refresh_time.strftime('%Y-%m-%d %H-%M-%S') if self.refresh_time else '' diff --git a/infracheck/infracheck/runner.py b/infracheck/infracheck/runner.py index 0fd54ca..0e11dac 100644 --- a/infracheck/infracheck/runner.py +++ b/infracheck/infracheck/runner.py @@ -99,7 +99,8 @@ class Runner(object): output=output.decode('utf-8'), exit_status=exit_status, hooks_output=hooks_out, - configured_name=configured_name + configured_name=configured_name, + description=config.get('description', '') ) def run_checks(self, enabled_configs: list) -> None: @@ -116,7 +117,8 @@ class Runner(object): if not result: try: - result = self.run_single_check(config_name, config['type'], config['input'], config.get('hooks', {}), config) + result = self.run_single_check(config_name, config['type'], config['input'], + config.get('hooks', {}), config) except CheckNotReadyShouldBeSkippedSignal: continue @@ -138,9 +140,11 @@ class Runner(object): for config_name in enabled_configs: result = self.repository.retrieve_from_cache(config_name) + config = self.config_loader.load(config_name) if not result: - result = ExecutedCheckResult.from_not_ready(configured_name=config_name) + result = ExecutedCheckResult.from_not_ready(configured_name=config_name, + description=config.get('description', '')) results.add(config_name, result)
riotkit-org/infracheck
17b2cacd7045335c24f61e5fb8733004e651cfd7
diff --git a/tests/unit_test_executed_checks_result_list.py b/tests/unit_test_executed_checks_result_list.py index ebbc092..9c4e12b 100644 --- a/tests/unit_test_executed_checks_result_list.py +++ b/tests/unit_test_executed_checks_result_list.py @@ -21,13 +21,15 @@ class ExecutedChecksResultListTest(BasicTestingCase): configured_name='first', output='Test', exit_status=False, - hooks_output='' + hooks_output='', + description='First in test' )) results.add('second', ExecutedCheckResult( configured_name='second', output='Test', exit_status=True, - hooks_output='' + hooks_output='', + description='Second in test' )) self.assertFalse(results.is_global_status_success()) @@ -38,13 +40,15 @@ class ExecutedChecksResultListTest(BasicTestingCase): configured_name='first', output='Test', exit_status=True, - hooks_output='' + hooks_output='', + description='First in test' )) results.add('second', ExecutedCheckResult( configured_name='second', output='Test', exit_status=True, - hooks_output='' + hooks_output='', + description='Second in test' )) self.assertTrue(results.is_global_status_success()) @@ -55,13 +59,15 @@ class ExecutedChecksResultListTest(BasicTestingCase): configured_name='first', output='Test', exit_status=False, - hooks_output='' + hooks_output='', + description='First in test' )) results.add('second', ExecutedCheckResult( configured_name='second', output='Test', exit_status=False, - hooks_output='' + hooks_output='', + description='Second in test' )) self.assertFalse(results.is_global_status_success()) diff --git a/tests/unit_test_model_executed_check_result.py b/tests/unit_test_model_executed_check_result.py index b8e2dae..c638e1e 100644 --- a/tests/unit_test_model_executed_check_result.py +++ b/tests/unit_test_model_executed_check_result.py @@ -13,7 +13,7 @@ from infracheck.infracheck.model import ExecutedCheckResult class ExecutedCheckResultTest(BasicTestingCase): def test_from_not_ready(self): - result = ExecutedCheckResult.from_not_ready('Durruti') + result = ExecutedCheckResult.from_not_ready('Durruti', description='Buenaventura') self.assertEqual(False, result.exit_status) self.assertIsNone(result.refresh_time) @@ -23,7 +23,8 @@ class ExecutedCheckResultTest(BasicTestingCase): configured_name='Durruti', output='Viva la revolution!', exit_status=True, - hooks_output='A las barricadas!' + hooks_output='A las barricadas!', + description='For the triumph of the libertarian confederation!' ) check.refresh_time = datetime(2020, 11, 27, 23, 40, 18) # mock the time @@ -34,5 +35,6 @@ class ExecutedCheckResultTest(BasicTestingCase): 'hooks_output': 'A las barricadas!', 'ident': 'Durruti=True', 'output': 'Viva la revolution!', - 'status': True + 'status': True, + 'description': 'For the triumph of the libertarian confederation!' }, as_hash)
[Core] Add optional description field Optional `description` field can be helpful to keep the note for other administrators
0.0
17b2cacd7045335c24f61e5fb8733004e651cfd7
[ "tests/unit_test_executed_checks_result_list.py::ExecutedChecksResultListTest::test_is_global_status_success", "tests/unit_test_model_executed_check_result.py::ExecutedCheckResultTest::test_from_not_ready", "tests/unit_test_model_executed_check_result.py::ExecutedCheckResultTest::test_to_hash" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-23 08:24:55+00:00
apache-2.0
5,261
riyasyash__CompetitiveProgramming-27
diff --git a/NumberSystems/ExcelConverter.py b/NumberSystems/ExcelConverter.py new file mode 100644 index 0000000..27c14d7 --- /dev/null +++ b/NumberSystems/ExcelConverter.py @@ -0,0 +1,22 @@ +class ExcelConverter: + column_start_ascii = 65 + column = None + column_number = None + column_literal_base = 26 + + def value(self, column_literal): + return (ord(column_literal) - self.column_start_ascii) + 1 + + def is_valid_column(self): + return self.column.isalpha() + + def to_capital(self): + self.column = self.column.upper() + + def to_column_number(self): + if self.is_valid_column(): + self.to_capital() + self.column = self.column[::-1] + self.column_number = 0 + for i, literal in enumerate(self.column): + self.column_number += pow(self.column_literal_base, i) * self.value(literal) diff --git a/NumberSystems/__init__.py b/NumberSystems/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Readme.md b/Readme.md index 2e17a97..725a66f 100644 --- a/Readme.md +++ b/Readme.md @@ -16,3 +16,6 @@ This repo contains the implementations of different data structures and solution #### [Queue](Queue) * [Implementation of Queue](Queue/Queue.py) * [Stack using Queue](Queue/stack_with_queue.py) + +#### [Number Systems](NumberSystems) +* [Convert Excel column names to numbers](NumberSystems/ExcelConverter.py)
riyasyash/CompetitiveProgramming
ca411660e09f91d17c243cbd9491e0010398ede0
diff --git a/tests/test_excel_converter.py b/tests/test_excel_converter.py new file mode 100644 index 0000000..a293276 --- /dev/null +++ b/tests/test_excel_converter.py @@ -0,0 +1,64 @@ +import unittest + +from NumberSystems.ExcelConverter import ExcelConverter + + +class TestExcelConverter(unittest.TestCase): + def setUp(self): + self.converter = ExcelConverter() + + def tearDown(self): + self.converter.column_number = None + self.converter.column = None + + def test_converter_is_initialised(self): + self.assertIsNone(self.converter.column_number) + self.assertIsNone(self.converter.column) + + def test_to_capital(self): + self.converter.column = 'Hello world' + self.converter.to_capital() + self.assertEqual('HELLO WORLD', self.converter.column) + + def test_is_valid_column(self): + self.converter.column = 'apple' + self.assertEqual(True, self.converter.is_valid_column()) + self.converter.column = 'a1pple' + self.assertEqual(False, self.converter.is_valid_column()) + self.converter.column = 'a pple' + self.assertEqual(False, self.converter.is_valid_column()) + self.converter.column = 'a-pple' + self.assertEqual(False, self.converter.is_valid_column()) + self.converter.column = '123' + self.assertEqual(False, self.converter.is_valid_column()) + + def test_converter_converts_single_colums(self): + self.converter.column = 'A' + self.converter.to_column_number() + self.assertEqual(1, self.converter.column_number) + self.converter.column = 'B' + self.converter.to_column_number() + self.assertEqual(2, self.converter.column_number) + self.converter.column = 'z' + self.converter.to_column_number() + self.assertEqual(26, self.converter.column_number) + + def test_converter_converts_double_colums(self): + self.converter.column = 'AA' + self.converter.to_column_number() + self.assertEqual(27, self.converter.column_number) + self.converter.column = 'AB' + self.converter.to_column_number() + self.assertEqual(28, self.converter.column_number) + self.converter.column = 'BC' + self.converter.to_column_number() + self.assertEqual(55, self.converter.column_number) + + def test_converter_converts_multiple_colums(self): + self.converter.column = 'AAZZ' + self.converter.to_column_number() + self.assertEqual(18954, self.converter.column_number) + self.converter.column = 'ZZAAA' + self.converter.to_column_number() + self.assertEqual(12339055, self.converter.column_number) +
Column Name to Number Come out with an algorithm for getting the column number provided the column name in an excel sheet and vice versa. Excel has a naming convention of A, B..Z, AA, AB, AC...ZZ,AAA... This had to be converted to the column numbers. A will be 1 and AA will 27... Also the algorithm to find the name provided column number.
0.0
ca411660e09f91d17c243cbd9491e0010398ede0
[ "tests/test_excel_converter.py::TestExcelConverter::test_converter_converts_double_colums", "tests/test_excel_converter.py::TestExcelConverter::test_converter_converts_multiple_colums", "tests/test_excel_converter.py::TestExcelConverter::test_converter_converts_single_colums", "tests/test_excel_converter.py::TestExcelConverter::test_converter_is_initialised", "tests/test_excel_converter.py::TestExcelConverter::test_is_valid_column", "tests/test_excel_converter.py::TestExcelConverter::test_to_capital" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-06-10 16:58:57+00:00
apache-2.0
5,262
rj79__pynetstring-4
diff --git a/README.rst b/README.rst index 2a1c20c..010528f 100644 --- a/README.rst +++ b/README.rst @@ -57,6 +57,16 @@ The receiving side could look something like this: for item in decoded_list: print(item) +Also Decoder class supports limit on maximal decoded netstring length. It is +required for network applications to restrict maximal length of input buffer +in order to prevent memory bloat. Netstring length limit specified as first +argument in this case: +:: + decoder = pynetstring.Decoder(maxlen=1024) + +Decoder will raise TooLong exception as soon as it'll discover next string +can't fit limit. + Data encoding ------------- Regardless of the type of the data that is sent to encode(), it will always @@ -78,11 +88,16 @@ e.g. UTF-8, you have to explicitly do that conversion. Error handling -------------- -A ValueError exception will be raised if trying to decode an invalid +A ParseError subclass exception will be raised if trying to decode an invalid netstring. :: - # ValueError exception due to leading zero in non-empty netstring: - pynetstring.decode('01:A,') + # IncompleteString exception due to missing trailing comma: + pynetstring.decode('3:ABC_') + + decoder = Decoder(3) + # TooLong exception due to exceeded netstring limit in stream parser: + decoder.feed(b'4:ABCD,') + - # ValueError exception due to missing trailing comma: - pynetstring.decode('3:ABC_') \ No newline at end of file +All other exceptions of this module can be expected to be subclass of +NetstringException. diff --git a/pynetstring.py b/pynetstring.py index a461e15..29dfa72 100644 --- a/pynetstring.py +++ b/pynetstring.py @@ -1,4 +1,5 @@ from enum import Enum +import math def _encode(data): if isinstance(data, str): @@ -11,17 +12,35 @@ def encode(data): return _encode(data) +class NetstringException(Exception): + pass + + +class ParseError(NetstringException): + pass + + +class TooLong(ParseError): + pass + + +class IncompleteString(ParseError): + pass + + class State(Enum): PARSE_LENGTH = 0 PARSE_DATA = 1 class Decoder: - def __init__(self): + def __init__(self, maxlen=0): self._buffer = bytearray() self._state = State.PARSE_LENGTH self._length = None self._decoded = [] + self._maxlen = maxlen + self._maxlen_bytes = math.log10(self._maxlen) + 1 if self._maxlen else 0 def feed(self, data): @@ -35,11 +54,17 @@ class Decoder: length_end = self._buffer.find(b':') if length_end == -1: # There is not enough data yet to decode the length + # Compact leading zeroes in buffer + self._buffer = self._buffer[:-1].lstrip(b'0') + self._buffer[-1:] + # Check if length field already too long: + if self._maxlen_bytes and len(self._buffer) > self._maxlen_bytes: + raise TooLong("Read too many bytes but length end" + " marker wasn't met.") break else: self._length = int(self._buffer[:length_end]) - if self._length > 0 and self._buffer[0] == ord(b'0'): - raise ValueError('Leading zero in non-empty netstring.') + if self._maxlen and self._length > self._maxlen: + raise TooLong("Specified netstring length is over limit.") # Consume what has been parsed self._buffer = self._buffer[length_end + 1:] self._state = State.PARSE_DATA @@ -51,7 +76,7 @@ class Decoder: break else: if self._buffer[self._length] != ord(b','): - raise ValueError('Missing trailing comma.') + raise IncompleteString('Missing trailing comma.') data = self._buffer[:self._length] self._buffer = self._buffer[self._length + 1:] self._decoded.append(bytes(data))
rj79/pynetstring
4f5d58c84fd5f06a1b9617c569b0c537b5732bc1
diff --git a/tests/tests.py b/tests/tests.py index 20343d7..2c5fa77 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -7,15 +7,14 @@ class TestNetString(unittest.TestCase): self.assertEqual(b'0:,', netstring.encode('')) self.assertEqual(b'0:,', netstring.encode(b'')) - def test_leading_zero_in_length_raises_exception_if_data_nonempty(self): - with self.assertRaises(ValueError): - netstring.decode('01:X,') + def test_accept_leading_zero(self): + self.assertEqual([b'X'], netstring.decode('01:X,')) def test_decode_empty_string(self): self.assertEqual([b''], netstring.decode(b'0:,')) def test_decode_missing_comma_fails(self): - with self.assertRaises(ValueError): + with self.assertRaises(netstring.IncompleteString): netstring.decode('3:abc_') def test_encode_one_byte_string(self): @@ -23,7 +22,7 @@ class TestNetString(unittest.TestCase): self.assertEqual(b'1:X,', netstring.encode(b'X')) def test_decode_nested(self): - self.assertEqual([b'5:Hello,6:World!'], netstring.decode('16:5:Hello,6:World!,,')) + self.assertEqual([b'5:Hello,6:World!,'], netstring.decode('17:5:Hello,6:World!,,')) def test_feed_empty_string_partially(self): decoder = netstring.Decoder() @@ -43,3 +42,42 @@ class TestNetString(unittest.TestCase): def test_encode_sequence(self): self.assertEqual([b'3:foo,', b'3:bar,'], netstring.encode(['foo', 'bar'])) + + def test_no_limit_error_when_content_shorter(self): + decoder = netstring.Decoder(10) + try: + self.assertEqual([b'XXXXXXXXX'], decoder.feed(b'9:XXXXXXXXX,')) + except netstring.TooLong: + self.assertFalse(True) + + def test_no_limit_error_when_content_just_right(self): + decoder = netstring.Decoder(1) + try: + self.assertEqual([b'X'], decoder.feed(b'1:X,')) + except netstring.TooLong: + self.assertFalse(True) + + decoder = netstring.Decoder(10) + try: + self.assertEqual([b'XXXXXXXXXX'], decoder.feed(b'10:XXXXXXXXXX,')) + except netstring.TooLong: + self.assertFalse(True) + + def test_limit_error_when_content_too_long(self): + decoder = netstring.Decoder(1) + with self.assertRaises(netstring.TooLong): + decoder.feed(b'2:XX,') + + def test_limit_error_when_missing_comma(self): + decoder = netstring.Decoder(10) + with self.assertRaises(netstring.IncompleteString): + decoder.feed(b'10:XXXXXXXXXXX,') + + def test_limit_error_when_length_declaration_inplausibly_long(self): + decoder = netstring.Decoder(100) + with self.assertRaises(netstring.TooLong): + # The length declaration of a netstring with content of 100 bytes + # takes up at most log10(100) + 1 = 3 bytes. + # Error raised already here because 4 bytes of length parsed but + # no length end marker ":" found yet. + decoder.feed(b'1000')
Leading zeroes before empty netstrings Hello! Thank you for your project! It appeared to be very useful. [Specification of netstring format](http://cr.yp.to/proto/netstrings.txt) is not very clear about leading zeroes. It makes statements and provides few examples without specifying whether leading zeroes rules are limited to these examples or leading zero rule is universal: > Any string of 8-bit bytes may be encoded as [len]":"[string]",". Here [string] is the string and [len] is a nonempty sequence of ASCII digits giving the length of [string] in decimal. The ASCII digits are <30> for 0, <31> for 1, and so on up through <39> for 9. Extra zeros at the front of [len] are prohibited: [len] begins with <30> exactly when [string] is empty. > > For example, the string "hello world!" is encoded as <31 32 3a 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 2c>, i.e., "12:hello world!,". The empty string is encoded as "0:,". It's hard to say from specification whether netstring `b"000000000:,"` is allowed or not. [Wikipedia article on Netstring](https://en.wikipedia.org/wiki/Netstring) states: > The length is written without leading zeroes. Empty string is the only netstring that begins with zero. There is exactly one legal netstring encoding for any byte string. This particular restriction about only one legal netstring representation vouches for prohibiting leading zeroes in all cases. However, I could not find any reliable source which backs this statement. Current code allows leading zeroes before empty netstring. It allows unrestricted bloat of input buffer with zeroes. I see two approaches to handle this: * Restrict all `[len]` from having leading zero. Pros: faster, follows idea of unique netstring representation for each bytestring. Cons: rejects inputs generated by ill applications. * Silently consume leading zeroes when parsing length, saving only meaningful data into input buffer. This will require additional logic on each length parsing step, but it'll work in all cases without potential input buffer bloat. Pros: follows classic [Robustness principle](https://en.wikipedia.org/wiki/Robustness_principle) "be conservative in what you do, be liberal in what you accept from others.". Cons: slower. What do you think, which approach is correct one? If you need help with implementing either approach, please indicate and I'll try to make PR with solution.
0.0
4f5d58c84fd5f06a1b9617c569b0c537b5732bc1
[ "tests/tests.py::TestNetString::test_accept_leading_zero", "tests/tests.py::TestNetString::test_decode_missing_comma_fails", "tests/tests.py::TestNetString::test_limit_error_when_content_too_long", "tests/tests.py::TestNetString::test_limit_error_when_length_declaration_inplausibly_long", "tests/tests.py::TestNetString::test_limit_error_when_missing_comma", "tests/tests.py::TestNetString::test_no_limit_error_when_content_just_right", "tests/tests.py::TestNetString::test_no_limit_error_when_content_shorter" ]
[ "tests/tests.py::TestNetString::test_decode_empty_string", "tests/tests.py::TestNetString::test_decode_nested", "tests/tests.py::TestNetString::test_encode_empty_string", "tests/tests.py::TestNetString::test_encode_one_byte_string", "tests/tests.py::TestNetString::test_encode_sequence", "tests/tests.py::TestNetString::test_feed_empty_string_partially", "tests/tests.py::TestNetString::test_feed_multiple", "tests/tests.py::TestNetString::test_feed_multiple_and_partial" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-01-11 03:46:27+00:00
mit
5,263
roaldnefs__salt-lint-18
diff --git a/lib/saltlint/rules/JinjaCommentHasSpacesRule.py b/lib/saltlint/rules/JinjaCommentHasSpacesRule.py index 7b7c468..2253cdb 100644 --- a/lib/saltlint/rules/JinjaCommentHasSpacesRule.py +++ b/lib/saltlint/rules/JinjaCommentHasSpacesRule.py @@ -14,7 +14,7 @@ class JinjaCommentHasSpacesRule(SaltLintRule): tags = ['formatting'] version_added = 'v0.0.5' - bracket_regex = re.compile(r"{#[^ -]|{#-[^ ]|[^ -]#}|[^ ]-#}") + bracket_regex = re.compile(r"{#[^ \-\+]|{#[\-\+][^ ]|[^ \-\+]#}|[^ ][\-\+]#}") def match(self, file, line): return self.bracket_regex.search(line) diff --git a/lib/saltlint/rules/JinjaStatementHasSpacesRule.py b/lib/saltlint/rules/JinjaStatementHasSpacesRule.py index 327cca7..80fa45f 100644 --- a/lib/saltlint/rules/JinjaStatementHasSpacesRule.py +++ b/lib/saltlint/rules/JinjaStatementHasSpacesRule.py @@ -14,7 +14,7 @@ class JinjaStatementHasSpacesRule(SaltLintRule): tags = ['formatting'] version_added = 'v0.0.2' - bracket_regex = re.compile(r"{%[^ -]|{%-[^ ]|[^ -]%}|[^ ]-%}") + bracket_regex = re.compile(r"{%[^ \-\+]|{%[\-\+][^ ]|[^ \-\+]%}|[^ ][\-\+]%}") def match(self, file, line): return self.bracket_regex.search(line) diff --git a/lib/saltlint/rules/JinjaVariableHasSpacesRule.py b/lib/saltlint/rules/JinjaVariableHasSpacesRule.py index fe808f8..67da64d 100644 --- a/lib/saltlint/rules/JinjaVariableHasSpacesRule.py +++ b/lib/saltlint/rules/JinjaVariableHasSpacesRule.py @@ -14,7 +14,7 @@ class JinjaVariableHasSpacesRule(SaltLintRule): tags = ['formatting'] version_added = 'v0.0.1' - bracket_regex = re.compile(r"{{[^ -]|{{-[^ ]|[^ -]}}|[^ ]-}}") + bracket_regex = re.compile(r"{{[^ \-\+]|{{[-\+][^ ]|[^ \-\+]}}|[^ ][-\+]}}") def match(self, file, line): return self.bracket_regex.search(line)
roaldnefs/salt-lint
025a8e7dc451ed76f34cdb25a73146ab6efe1be1
diff --git a/tests/unit/TestJinjaCommentHasSpaces.py b/tests/unit/TestJinjaCommentHasSpaces.py index 16ddb2f..6e2ae54 100644 --- a/tests/unit/TestJinjaCommentHasSpaces.py +++ b/tests/unit/TestJinjaCommentHasSpaces.py @@ -10,11 +10,11 @@ from tests import RunFromText GOOD_COMMENT_LINE = ''' -{#- set example='good' -#} +{#- set example='good' +#} ''' BAD_COMMENT_LINE = ''' -{#-set example='bad'-#} +{#-set example='bad'+#} ''' class TestLineTooLongRule(unittest.TestCase): diff --git a/tests/unit/TestJinjaStatementHasSpaces.py b/tests/unit/TestJinjaStatementHasSpaces.py index 56f59c8..cf81c2e 100644 --- a/tests/unit/TestJinjaStatementHasSpaces.py +++ b/tests/unit/TestJinjaStatementHasSpaces.py @@ -10,11 +10,11 @@ from tests import RunFromText GOOD_STATEMENT_LINE = ''' -{%- set example='good' -%} +{%- set example='good' +%} ''' BAD_STATEMENT_LINE = ''' -{%-set example='bad'-%} +{%-set example='bad'+%} ''' class TestLineTooLongRule(unittest.TestCase): diff --git a/tests/unit/TestJinjaVariableHasSpaces.py b/tests/unit/TestJinjaVariableHasSpaces.py index 9c537e0..5e27b09 100644 --- a/tests/unit/TestJinjaVariableHasSpaces.py +++ b/tests/unit/TestJinjaVariableHasSpaces.py @@ -10,11 +10,11 @@ from tests import RunFromText GOOD_VARIABLE_LINE = ''' -{{- variable -}} +{{- variable +}} ''' BAD_VARIABLE_LINE = ''' -{{-variable-}} +{{-variable+}} ''' class TestLineTooLongRule(unittest.TestCase):
Fix whitespace control in Jinja rules Currently only the `-` character is accepted by the Jinja whitespace rules but technically `+` should be supported as well, i.e.: {%+ ... +%} {{+ ... +}} {#+ ... +#} That's mentioned in the [upstream documentation](https://jinja.palletsprojects.com/en/2.10.x/templates/#whitespace-control) as well. Thanks @myii, for mentioning this is https://github.com/roaldnefs/salt-lint/pull/13#issuecomment-538547711!
0.0
025a8e7dc451ed76f34cdb25a73146ab6efe1be1
[ "tests/unit/TestJinjaCommentHasSpaces.py::TestLineTooLongRule::test_comment_positive", "tests/unit/TestJinjaStatementHasSpaces.py::TestLineTooLongRule::test_statement_positive", "tests/unit/TestJinjaVariableHasSpaces.py::TestLineTooLongRule::test_statement_positive" ]
[ "tests/unit/TestJinjaCommentHasSpaces.py::TestLineTooLongRule::test_comment_negative", "tests/unit/TestJinjaStatementHasSpaces.py::TestLineTooLongRule::test_statement_negative", "tests/unit/TestJinjaVariableHasSpaces.py::TestLineTooLongRule::test_statement_negative" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-10-04 22:46:55+00:00
mit
5,264
roaldnefs__salt-lint-31
diff --git a/lib/saltlint/rules/YamlHasOctalValueRule.py b/lib/saltlint/rules/YamlHasOctalValueRule.py new file mode 100644 index 0000000..2be6e5f --- /dev/null +++ b/lib/saltlint/rules/YamlHasOctalValueRule.py @@ -0,0 +1,20 @@ +# Copyright (c) 2016, Will Thames and contributors +# Copyright (c) 2018, Ansible Project +# Modified work Copyright (c) 2019 Roald Nefs + +from saltlint import SaltLintRule +import re + + +class YamlHasOctalValueRule(SaltLintRule): + id = '210' + shortdesc = 'Numbers that start with `0` should always be encapsulated in quotation marks' + description = 'Numbers that start with `0` should always be encapsulated in quotation marks' + severity = 'HIGH' + tags = ['formatting'] + version_added = 'develop' + + bracket_regex = re.compile(r"(?<!['\"])0+[1-9]\d*(?!['\"])") + + def match(self, file, line): + return self.bracket_regex.search(line)
roaldnefs/salt-lint
6dd30a5d6959a68bf1f94844a386ba118773f970
diff --git a/tests/unit/TestYamlHasOctalValueRule.py b/tests/unit/TestYamlHasOctalValueRule.py new file mode 100644 index 0000000..996fa63 --- /dev/null +++ b/tests/unit/TestYamlHasOctalValueRule.py @@ -0,0 +1,48 @@ +# Copyright (c) 2013-2018 Will Thames <[email protected]> +# Copyright (c) 2018 Ansible by Red Hat +# Modified work Copyright (c) 2019 Roald Nefs + +import unittest + +from saltlint import RulesCollection +from saltlint.rules.YamlHasOctalValueRule import YamlHasOctalValueRule +from tests import RunFromText + + +GOOD_NUMBER_LINE = ''' +testdirectory: + file.recurse: + - name: /tmp/directory + - file_mode: 700 + - dir_mode: '0775' + +testdirectory2: + file.recurse: + - name: /tmp/directory2 + - file_mode: 0 + - dir_mode: "0775" +''' + +BAD_NUMBER_LINE = ''' +testdirectory: + file.recurse: + - name: /tmp/directory + - file_mode: 0775 + - dir_mode: 070 +''' + +class TestFileModeLeadingZeroRule(unittest.TestCase): + collection = RulesCollection() + + def setUp(self): + self.collection.register(YamlHasOctalValueRule()) + + def test_statement_positive(self): + runner = RunFromText(self.collection) + results = runner.run_state(GOOD_NUMBER_LINE) + self.assertEqual(0, len(results)) + + def test_statement_negative(self): + runner = RunFromText(self.collection) + results = runner.run_state(BAD_NUMBER_LINE) + self.assertEqual(2, len(results))
Suggested improvements/alternative to file mode implementation The underlying issue here is that _numbers beginning with zero_ are interpreted as octal in YAML. https://docs.saltstack.com/en/latest/ref/states/all/salt.states.file.html > **Warning** > > When using a mode that includes a leading zero you must wrap the value in single quotes. If the value is not wrapped in quotes it will be read by YAML as an integer and evaluated as an octal. A useful look is how `yamllint` handles these. https://yamllint.readthedocs.io/en/stable/rules.html#module-yamllint.rules.octal_values * Ultimately, this is about any numbers beginning with `0`, not just file/dir modes. I've done test runs on 45 formulas under the [SaltStack Formulas organisation](https://github.com/saltstack-formulas). Many of them fall afoul of both `207` and `208`. The problem is that most of these are _false positives_. The very common usage of 3-digit, unquoted modes (e.g. `755` and `644`) is completely legitimate. My suggestion is that these shouldn't be flagged as errors/warnings. There's a simple workaround for this for the time being: * Apply something similar to: https://github.com/myii/salt-lint/commit/177e3deffa17d47a4660e6096187f31fedbea908 * Add `208` to the ignored list A more comprehensive solution could be achieved under a new lint ID, which checks for _any_ number with a leading zero (not just file/dir modes), as shown on the `yamllint` docs. Then users could add both `207` and `208` to the ignore list and use the comprehensive _octal_ bug linter instead.
0.0
6dd30a5d6959a68bf1f94844a386ba118773f970
[ "tests/unit/TestYamlHasOctalValueRule.py::TestFileModeLeadingZeroRule::test_statement_negative", "tests/unit/TestYamlHasOctalValueRule.py::TestFileModeLeadingZeroRule::test_statement_positive" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-10-06 18:15:38+00:00
mit
5,265
roaldnefs__salt-lint-35
diff --git a/lib/saltlint/rules/YamlHasOctalValueRule.py b/lib/saltlint/rules/YamlHasOctalValueRule.py index 541a9b9..c91b4f8 100644 --- a/lib/saltlint/rules/YamlHasOctalValueRule.py +++ b/lib/saltlint/rules/YamlHasOctalValueRule.py @@ -14,7 +14,7 @@ class YamlHasOctalValueRule(SaltLintRule): tags = ['formatting'] version_added = 'v0.0.6' - bracket_regex = re.compile(r"(?<!['\"])0+[1-9]\d*(?!['\"])") + bracket_regex = re.compile(r": (?<!['\"])0+[1-9]\d*(?!['\"])") def match(self, file, line): return self.bracket_regex.search(line)
roaldnefs/salt-lint
9253a7aab3fa082b7063dfe47fd3bfe4fad461f0
diff --git a/tests/unit/TestYamlHasOctalValueRule.py b/tests/unit/TestYamlHasOctalValueRule.py index 996fa63..640aab8 100644 --- a/tests/unit/TestYamlHasOctalValueRule.py +++ b/tests/unit/TestYamlHasOctalValueRule.py @@ -16,9 +16,9 @@ testdirectory: - file_mode: 700 - dir_mode: '0775' -testdirectory2: +testdirectory02: file.recurse: - - name: /tmp/directory2 + - name: /tmp/directory02 - file_mode: 0 - dir_mode: "0775" '''
Check #210 triggers on more than filerights Currently, check `#210` (in [YamlHasOctalValueRule](https://github.com/roaldnefs/salt-lint/blob/master/lib/saltlint/rules/YamlHasOctalValueRule.py)) has a regex set too wide, and triggers on all numbers starting with a zero. Proposed solutions: * Match regex on leading colon + space (`: 0123`) * Match regex on `mode: 0123`
0.0
9253a7aab3fa082b7063dfe47fd3bfe4fad461f0
[ "tests/unit/TestYamlHasOctalValueRule.py::TestFileModeLeadingZeroRule::test_statement_positive" ]
[ "tests/unit/TestYamlHasOctalValueRule.py::TestFileModeLeadingZeroRule::test_statement_negative" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-10-07 10:32:28+00:00
mit
5,266
roaldnefs__salt-lint-6
diff --git a/lib/saltlint/rules/FileModeQuotationRule.py b/lib/saltlint/rules/FileModeQuotationRule.py new file mode 100644 index 0000000..e9f1d87 --- /dev/null +++ b/lib/saltlint/rules/FileModeQuotationRule.py @@ -0,0 +1,20 @@ +# Copyright (c) 2016, Will Thames and contributors +# Copyright (c) 2018, Ansible Project +# Modified work Copyright (c) 2019 Jeffrey Bouter + +from saltlint import SaltLintRule +import re + + +class FileModeQuotationRule(SaltLintRule): + id = '207' + shortdesc = 'File modes should always be encapsulated in quotation marks' + description = 'File modes should always be encapsulated in quotation marks' + severity = 'HIGH' + tags = ['formatting'] + version_added = 'v0.0.1' + + bracket_regex = re.compile(r"^\s+- ((dir_)|(file_))?mode: [0-9]{3,4}") + + def match(self, file, line): + return self.bracket_regex.search(line)
roaldnefs/salt-lint
d85cae0aeb44532ad1f3af43df29669e816992e8
diff --git a/tests/unit/TestFileModeQuotationRule.py b/tests/unit/TestFileModeQuotationRule.py new file mode 100644 index 0000000..4f7998e --- /dev/null +++ b/tests/unit/TestFileModeQuotationRule.py @@ -0,0 +1,45 @@ +# Copyright (c) 2013-2018 Will Thames <[email protected]> +# Copyright (c) 2018 Ansible by Red Hat +# Modified work Copyright (c) 2019 Jeffrey Bouter + +import unittest + +from saltlint import RulesCollection +from saltlint.rules.FileModeQuotationRule import FileModeQuotationRule +from tests import RunFromText + + +GOOD_MODE_QUOTATION_LINE = ''' +testfile: + file.managed: + - name: /tmp/testfile + - user: root + - group: root + - mode: '0700' +''' + +BAD_MODE_QUOTATION_LINE = ''' +testfile: + file.managed: + - name: /tmp/badfile + - user: root + - group: root + - mode: 0700 + - file_mode: 0660 + - dir_mode: 0775 +''' + +class TestLineTooLongRule(unittest.TestCase): + collection = RulesCollection() + + def setUp(self): + self.collection.register(FileModeQuotationRule()) + self.runner = RunFromText(self.collection) + + def test_statement_positive(self): + results = self.runner.run_state(GOOD_MODE_QUOTATION_LINE) + self.assertEqual(0, len(results)) + + def test_statement_negative(self): + results = self.runner.run_state(BAD_MODE_QUOTATION_LINE) + self.assertEqual(3, len(results))
Missing rule for leading zero in file mode Missing rule in to check for leading zero in file mode. When using a mode that includes a leading zero it must be wrapped in single quotes. If the value is not wrapped in quotes it will be read by YAML as an integer and evaluated as an octal. **Source:** https://docs.saltstack.com/en/latest/ref/states/all/salt.states.file.html#module-salt.states.file **Possible Solution** Create a regex to check if the mode has a leading zero and doesn't use quotes. Simple example for a regex rule: [lib/saltlint/rules/JinjaVariableHasSpacesRule.py](https://github.com/roaldnefs/salt-lint/blob/master/lib/saltlint/rules/JinjaVariableHasSpacesRule.py). Don't forget to add a test, e.g.: [tests/unit/TestJinjaVariableHasSpaces.py](https://github.com/roaldnefs/salt-lint/blob/master/tests/unit/TestJinjaVariableHasSpaces.py).
0.0
d85cae0aeb44532ad1f3af43df29669e816992e8
[ "tests/unit/TestFileModeQuotationRule.py::TestLineTooLongRule::test_statement_negative", "tests/unit/TestFileModeQuotationRule.py::TestLineTooLongRule::test_statement_positive" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2019-10-04 11:04:27+00:00
mit
5,267
robmarkcole__HASS-data-detective-71
diff --git a/detective/config.py b/detective/config.py index 1548e2b..346bff4 100644 --- a/detective/config.py +++ b/detective/config.py @@ -51,6 +51,7 @@ def _secret_yaml(loader, node): def _stub_dict(constructor, node): """Stub a constructor with a dictionary.""" + print("Unsupported YAML found: {} {}".format(node.tag, node.value)) return {} @@ -83,11 +84,18 @@ def load_hass_config(path): def db_url_from_hass_config(path): """Find the recorder database url from a HASS config dir.""" config = load_hass_config(path) - default = "sqlite:///{}".format(os.path.join(path, "home-assistant_v2.db")) + default_path = os.path.join(path, "home-assistant_v2.db") + default_url = "sqlite:///{}".format(default_path) recorder = config.get("recorder") - if not recorder: - return default + if recorder: + db_url = recorder.get("db_url") + if db_url is not None: + return db_url - return recorder.get("db_url", default) + if not os.path.isfile(default_path): + raise ValueError( + "Unable to determine DB url from hass config at {}".format(path)) + + return default_url diff --git a/detective/core.py b/detective/core.py index 9e2b5be..59fa189 100644 --- a/detective/core.py +++ b/detective/core.py @@ -41,6 +41,12 @@ class HassDatabase: if fetch_entities: self.fetch_entities() except Exception as exc: + if isinstance(exc, ImportError): + raise RuntimeError( + "The right dependency to connect to your database is " + "missing. Please make sure that it is installed." + ) + print(exc) raise
robmarkcole/HASS-data-detective
809ccf7467073dabfd6cd2eec039740a868031ed
diff --git a/tests/test_config.py b/tests/test_config.py index 2c64b64..5dd6beb 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -53,7 +53,18 @@ other_secret: test-other-secret def test_db_url_from_hass_config(): """Test extracting recorder url from config.""" - with patch('detective.config.load_hass_config', return_value={}): + with patch( + 'detective.config.load_hass_config', return_value={} + ), patch( + 'os.path.isfile', return_value=False + ), pytest.raises(ValueError): + config.db_url_from_hass_config('mock-path') + + with patch( + 'detective.config.load_hass_config', return_value={} + ), patch( + 'os.path.isfile', return_value=True + ): assert config.db_url_from_hass_config('mock-path') == \ 'sqlite:///mock-path/home-assistant_v2.db'
db_url_from_hass_config to error out when no recorder section found and DB file doesn't exist If we can't find a recorder section in `config.db_url_from_hass_config`, we return the SQLite DB. We should only return SQLLite if the file actually exists in the config dir. Else we should error out.
0.0
809ccf7467073dabfd6cd2eec039740a868031ed
[ "tests/test_config.py::test_db_url_from_hass_config" ]
[ "tests/test_config.py::test_find_hass_config" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-20 21:15:49+00:00
mit
5,268
robmarkcole__HASS-data-detective-72
diff --git a/detective/config.py b/detective/config.py index 1548e2b..346bff4 100644 --- a/detective/config.py +++ b/detective/config.py @@ -51,6 +51,7 @@ def _secret_yaml(loader, node): def _stub_dict(constructor, node): """Stub a constructor with a dictionary.""" + print("Unsupported YAML found: {} {}".format(node.tag, node.value)) return {} @@ -83,11 +84,18 @@ def load_hass_config(path): def db_url_from_hass_config(path): """Find the recorder database url from a HASS config dir.""" config = load_hass_config(path) - default = "sqlite:///{}".format(os.path.join(path, "home-assistant_v2.db")) + default_path = os.path.join(path, "home-assistant_v2.db") + default_url = "sqlite:///{}".format(default_path) recorder = config.get("recorder") - if not recorder: - return default + if recorder: + db_url = recorder.get("db_url") + if db_url is not None: + return db_url - return recorder.get("db_url", default) + if not os.path.isfile(default_path): + raise ValueError( + "Unable to determine DB url from hass config at {}".format(path)) + + return default_url diff --git a/detective/core.py b/detective/core.py index 9e2b5be..e3d228c 100644 --- a/detective/core.py +++ b/detective/core.py @@ -1,12 +1,14 @@ """ Classes and functions for parsing home-assistant data. """ +from urllib.parse import urlparse +from typing import List -from . import config, functions import matplotlib.pyplot as plt import pandas as pd from sqlalchemy import create_engine, text -from typing import List + +from . import config, functions def db_from_hass_config(path=None, **kwargs): @@ -18,6 +20,10 @@ def db_from_hass_config(path=None, **kwargs): return HassDatabase(url, **kwargs) +def get_db_type(url): + return urlparse(url).scheme.split('+')[0] + + class HassDatabase: """ Initializing the parser fetches all of the data from the database and @@ -31,7 +37,8 @@ class HassDatabase: url : str The URL to the database. """ - self._url = url + self.url = url + self._master_df = None self._domains = None self._entities = None @@ -41,9 +48,19 @@ class HassDatabase: if fetch_entities: self.fetch_entities() except Exception as exc: + if isinstance(exc, ImportError): + raise RuntimeError( + "The right dependency to connect to your database is " + "missing. Please make sure that it is installed." + ) + print(exc) raise + + self.db_type = get_db_type(url) + + def perform_query(self, query): """Perform a query, where query is a string.""" try:
robmarkcole/HASS-data-detective
809ccf7467073dabfd6cd2eec039740a868031ed
diff --git a/tests/test_config.py b/tests/test_config.py index 2c64b64..5dd6beb 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -53,7 +53,18 @@ other_secret: test-other-secret def test_db_url_from_hass_config(): """Test extracting recorder url from config.""" - with patch('detective.config.load_hass_config', return_value={}): + with patch( + 'detective.config.load_hass_config', return_value={} + ), patch( + 'os.path.isfile', return_value=False + ), pytest.raises(ValueError): + config.db_url_from_hass_config('mock-path') + + with patch( + 'detective.config.load_hass_config', return_value={} + ), patch( + 'os.path.isfile', return_value=True + ): assert config.db_url_from_hass_config('mock-path') == \ 'sqlite:///mock-path/home-assistant_v2.db' diff --git a/tests/test_core.py b/tests/test_core.py index 2139787..65002af 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,1 +1,6 @@ -# To do +from detective.core import get_db_type + + +def test_get_db_type(): + assert get_db_type('mysql://localhost') == 'mysql' + assert get_db_type('mysql+pymysql://localhost') == 'mysql'
Add db type as attribute As pointed out by @balloob 'Most DBAPIs have built in support for the datetime module, with the noted exception of SQLite. In the case of SQLite, date and time types are stored as strings which are then converted back to datetime objects when rows are returned.' Detective should have the db type as an attribute, allowing for db type specific behaviour if required.
0.0
809ccf7467073dabfd6cd2eec039740a868031ed
[ "tests/test_config.py::test_find_hass_config", "tests/test_config.py::test_db_url_from_hass_config", "tests/test_core.py::test_get_db_type" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-12-20 21:30:35+00:00
mit
5,269
robmarkcole__HASS-data-detective-77
diff --git a/detective/config.py b/detective/config.py index db49a89..a814384 100644 --- a/detective/config.py +++ b/detective/config.py @@ -49,25 +49,45 @@ def _secret_yaml(loader, node): raise ValueError("Secret {} not found".format(node.value)) from None -def _stub_dict(constructor, node): +def _include_yaml(loader, node): + """Load another YAML file and embeds it using the !include tag. + + Example: + device_tracker: !include device_tracker.yaml + """ + return load_yaml(os.path.join(os.path.dirname(loader.name), node.value)) + + +def _stub_tag(constructor, node): """Stub a constructor with a dictionary.""" - print("Unsupported YAML found: {} {}".format(node.tag, node.value)) + seen = getattr(constructor, '_stub_seen', None) + + if seen is None: + seen = constructor._stub_seen = set() + + if node.tag not in seen: + print("YAML tag {} is not supported".format(node.tag)) + seen.add(node.tag) + return {} -HassSafeConstructor.add_constructor("!include", _stub_dict) -HassSafeConstructor.add_constructor("!env_var", _stub_dict) +HassSafeConstructor.add_constructor("!include", _include_yaml) +HassSafeConstructor.add_constructor("!env_var", _stub_tag) HassSafeConstructor.add_constructor("!secret", _secret_yaml) -HassSafeConstructor.add_constructor("!include_dir_list", _stub_dict) -HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_dict) -HassSafeConstructor.add_constructor("!include_dir_named", _stub_dict) -HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_dict) +HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag) +HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag) +HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag) +HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag) def load_hass_config(path): """Load the HASS config.""" - fname = os.path.join(path, "configuration.yaml") + return load_yaml(os.path.join(path, "configuration.yaml")) + +def load_yaml(fname): + """Load a YAML file.""" yaml = YAML(typ="safe") # Compat with HASS yaml.allow_duplicate_keys = True diff --git a/detective/core.py b/detective/core.py index ac1148b..aa08b46 100644 --- a/detective/core.py +++ b/detective/core.py @@ -24,6 +24,18 @@ def get_db_type(url): return urlparse(url).scheme.split("+")[0] +def stripped_db_url(url): + """Return a version of the DB url with the password stripped out.""" + parsed = urlparse(url) + + if parsed.password is None: + return url + + return parsed._replace( + netloc="{}:***@{}".format(parsed.username, parsed.hostname) + ).geturl() + + class HassDatabase: """ Initializing the parser fetches all of the data from the database and @@ -44,7 +56,7 @@ class HassDatabase: self._entities = None try: self.engine = create_engine(url) - print("Successfully connected to database") + print("Successfully connected to database", stripped_db_url(url)) if fetch_entities: self.fetch_entities() except Exception as exc:
robmarkcole/HASS-data-detective
883ed9cd2a344e1bf3765ebc43eb8be70dcc6b00
diff --git a/tests/test_config.py b/tests/test_config.py index 5dd6beb..b460b26 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -31,6 +31,8 @@ def test_load_hass_config(): with open(os.path.join(tmpdir, 'configuration.yaml'), 'wt') as fp: fp.write(""" mock_secret: !secret some_secret +included: !include included.yaml +mock_env: !env_var MOCK_ENV mock_env: !env_var MOCK_ENV mock_dir_list: !include_dir_list ./zxc mock_dir_merge_list: !include_dir_merge_list ./zxc @@ -46,9 +48,15 @@ some_secret: test-some-secret other_secret: test-other-secret """) + with open(os.path.join(tmpdir, 'included.yaml'), 'wt') as fp: + fp.write(""" +some: value + """) + configuration = config.load_hass_config(tmpdir) assert configuration['mock_secret'] == 'test-other-secret' + assert configuration['included'] == {'some': 'value'} def test_db_url_from_hass_config(): diff --git a/tests/test_core.py b/tests/test_core.py index 65002af..4a0efdd 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,6 +1,14 @@ -from detective.core import get_db_type +from detective.core import get_db_type, stripped_db_url def test_get_db_type(): assert get_db_type('mysql://localhost') == 'mysql' assert get_db_type('mysql+pymysql://localhost') == 'mysql' + + +def test_stripped_db_url(): + assert stripped_db_url('mysql://localhost') == 'mysql://localhost' + assert stripped_db_url('mysql://paulus@localhost') == \ + 'mysql://paulus@localhost' + assert stripped_db_url('mysql://paulus:password@localhost') == \ + 'mysql://paulus:***@localhost'
Print some info about db on connection On connection to a db, print out some info (not any auth) to avoid confusion where a use might be connecting to a recorder db
0.0
883ed9cd2a344e1bf3765ebc43eb8be70dcc6b00
[ "tests/test_config.py::test_find_hass_config", "tests/test_config.py::test_db_url_from_hass_config", "tests/test_core.py::test_get_db_type", "tests/test_core.py::test_stripped_db_url" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-25 19:28:29+00:00
mit
5,270
roboflow__supervision-219
diff --git a/supervision/__init__.py b/supervision/__init__.py index 76cdde90..9c0252fb 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -1,6 +1,10 @@ import importlib.metadata as importlib_metadata -__version__ = importlib_metadata.version(__package__) +try: + # This will read version from pyproject.toml + __version__ = importlib_metadata.version(__package__ or __name__) +except importlib_metadata.PackageNotFoundError: + __version__ = "development" from supervision.classification.core import Classifications diff --git a/supervision/metrics/detection.py b/supervision/metrics/detection.py index d0e85e63..e7234973 100644 --- a/supervision/metrics/detection.py +++ b/supervision/metrics/detection.py @@ -84,8 +84,12 @@ class ConfusionMatrix: prediction_tensors = [] target_tensors = [] for prediction, target in zip(predictions, targets): - prediction_tensors.append(cls.convert_detections_to_tensor(prediction)) - target_tensors.append(cls.convert_detections_to_tensor(target)) + prediction_tensors.append( + cls.detections_to_tensor(prediction, with_confidence=True) + ) + target_tensors.append( + cls.detections_to_tensor(target, with_confidence=False) + ) return cls.from_tensors( predictions=prediction_tensors, targets=target_tensors, @@ -95,15 +99,24 @@ class ConfusionMatrix: ) @classmethod - def convert_detections_to_tensor(cls, detections: Detections) -> np.ndarray: + def detections_to_tensor( + cls, detections: Detections, with_confidence: bool = False + ) -> np.ndarray: + if detections.class_id is None: + raise ValueError( + "ConfusionMatrix can only be calculated for Detections with class_id" + ) + arrays_to_concat = [detections.xyxy, np.expand_dims(detections.class_id, 1)] - if detections.confidence is not None: + + if with_confidence: + if detections.confidence is None: + raise ValueError( + "ConfusionMatrix can only be calculated for Detections with confidence" + ) arrays_to_concat.append(np.expand_dims(detections.confidence, 1)) - return np.concatenate( - arrays_to_concat, - axis=1, - ) + return np.concatenate(arrays_to_concat, axis=1) @classmethod def from_tensors(
roboflow/supervision
d6883caadc44d854ea946c64849abe4430dcec3e
diff --git a/test/metrics/test_detection.py b/test/metrics/test_detection.py index 4bd72cf4..0ecab3f0 100644 --- a/test/metrics/test_detection.py +++ b/test/metrics/test_detection.py @@ -6,6 +6,7 @@ import pytest from supervision.detection.core import Detections from supervision.metrics.detection import ConfusionMatrix +from test.utils import mock_detections CLASSES = np.arange(80) NUM_CLASSES = len(CLASSES) @@ -119,26 +120,58 @@ BAD_CONF_MATRIX = worsen_ideal_conf_matrix( @pytest.mark.parametrize( - "detections, exception", + "detections, with_confidence, expected_result, exception", [ ( - DETECTIONS, + Detections.empty(), + False, + np.empty((0, 5), dtype=np.float32), DoesNotRaise(), - ) + ), # empty detections; no confidence + ( + Detections.empty(), + True, + np.empty((0, 6), dtype=np.float32), + DoesNotRaise(), + ), # empty detections; with confidence + ( + mock_detections(xyxy=[[0, 0, 10, 10]], class_id=[0], confidence=[0.5]), + False, + np.array([[0, 0, 10, 10, 0]], dtype=np.float32), + DoesNotRaise(), + ), # single detection; no confidence + ( + mock_detections(xyxy=[[0, 0, 10, 10]], class_id=[0], confidence=[0.5]), + True, + np.array([[0, 0, 10, 10, 0, 0.5]], dtype=np.float32), + DoesNotRaise(), + ), # single detection; with confidence + ( + mock_detections(xyxy=[[0, 0, 10, 10], [0, 0, 20, 20]], class_id=[0, 1], confidence=[0.5, 0.2]), + False, + np.array([[0, 0, 10, 10, 0], [0, 0, 20, 20, 1]], dtype=np.float32), + DoesNotRaise(), + ), # multiple detections; no confidence + ( + mock_detections(xyxy=[[0, 0, 10, 10], [0, 0, 20, 20]], class_id=[0, 1], confidence=[0.5, 0.2]), + True, + np.array([[0, 0, 10, 10, 0, 0.5], [0, 0, 20, 20, 1, 0.2]], dtype=np.float32), + DoesNotRaise(), + ), # multiple detections; with confidence ], ) -def test_convert_detections_to_tensor( - detections, - exception: Exception, +def test_detections_to_tensor( + detections: Detections, + with_confidence: bool, + expected_result: Optional[np.ndarray], + exception: Exception ): with exception: - result = ConfusionMatrix.convert_detections_to_tensor( + result = ConfusionMatrix.detections_to_tensor( detections=detections, + with_confidence=with_confidence ) - - assert np.array_equal(result[:, :4], detections.xyxy) - assert np.array_equal(result[:, 4], detections.class_id) - assert np.array_equal(result[:, 5], detections.confidence) + assert np.array_equal(result, expected_result) @pytest.mark.parametrize(
Developement - version issue ### Search before asking - [X] I have searched the Supervision [issues](https://github.com/roboflow/supervision/issues) and found no similar bug report. ### Bug I have not installed `supervision` but running directly for developement purpose. But I got an following error when I import supervision code: ``` raise PackageNotFoundError(name) importlib.metadata.PackageNotFoundError: supervision ``` After a quick investigation, it is found that `__init__.py` of `supervision` where version information used. It is creating an issue. If I comment this line and the bug is gone. @onuralpszr Can you take a look? I think it should be ignorable, if valid version is not found then use `development` version. Though, I do not have concret idea, how to tackle it. ### Environment _No response_ ### Minimal Reproducible Example _No response_ ### Additional _No response_ ### Are you willing to submit a PR? - [X] Yes I'd like to help by submitting a PR!
0.0
d6883caadc44d854ea946c64849abe4430dcec3e
[ "test/metrics/test_detection.py::test_detections_to_tensor[detections0-False-expected_result0-exception0]", "test/metrics/test_detection.py::test_detections_to_tensor[detections1-True-expected_result1-exception1]", "test/metrics/test_detection.py::test_detections_to_tensor[detections2-False-expected_result2-exception2]", "test/metrics/test_detection.py::test_detections_to_tensor[detections3-True-expected_result3-exception3]", "test/metrics/test_detection.py::test_detections_to_tensor[detections4-False-expected_result4-exception4]", "test/metrics/test_detection.py::test_detections_to_tensor[detections5-True-expected_result5-exception5]" ]
[ "test/metrics/test_detection.py::test_from_tensors[predictions0-targets0-classes0-0.2-0.5-expected_result0-exception0]", "test/metrics/test_detection.py::test_from_tensors[predictions1-targets1-classes1-0.2-0.5-expected_result1-exception1]", "test/metrics/test_detection.py::test_from_tensors[predictions2-targets2-classes2-0.3-0.5-expected_result2-exception2]", "test/metrics/test_detection.py::test_from_tensors[predictions3-targets3-classes3-0.6-0.5-expected_result3-exception3]", "test/metrics/test_detection.py::test_from_tensors[predictions4-targets4-classes4-0.6-0.5-expected_result4-exception4]", "test/metrics/test_detection.py::test_from_tensors[predictions5-targets5-classes5-0.6-1.0-expected_result5-exception5]", "test/metrics/test_detection.py::test_evaluate_detection_batch[predictions0-targets0-80-0.2-0.5-expected_result0-exception0]", "test/metrics/test_detection.py::test_drop_extra_matches[matches0-expected_result0-exception0]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-22 07:41:50+00:00
mit
5,271
robotframework__SeleniumLibrary-1428
diff --git a/docs/extending/extending.rst b/docs/extending/extending.rst index 9960ab02..d143e884 100644 --- a/docs/extending/extending.rst +++ b/docs/extending/extending.rst @@ -89,6 +89,15 @@ of the attributes are explained in the library `keyword documentation`_. please plugins may alter the functionality of the method or attributes and documentation applies only for the core SeleniumLibrary. +Initialisation order +==================== +When instance is created from the SeleniumLibrary, example when library is imported in the +test data, there is an order in the initialisation. At first all classes defining SeleniumLibrary +keywords are discovered. As a second event, discovery for the EventFiringWebDriver is done. +At third event, plugins are discovered. As a last event, keywords are found from SeleniumLibrary +classes and plugins. Because plugins are discovered last, they may example alter the +EventFiringWebDriver. Consult the plugin's documentation for more details. + Plugins ======= SeleniumLibrary offers plugins as a way to modify, add library keywords and modify some of the internal diff --git a/src/SeleniumLibrary/__init__.py b/src/SeleniumLibrary/__init__.py index 0a53d434..59bde1ca 100644 --- a/src/SeleniumLibrary/__init__.py +++ b/src/SeleniumLibrary/__init__.py @@ -460,17 +460,16 @@ class SeleniumLibrary(DynamicCore): WaitingKeywords(self), WindowKeywords(self) ] + self.ROBOT_LIBRARY_LISTENER = LibraryListener() + self._running_keyword = None + self.event_firing_webdriver = None + if is_truthy(event_firing_webdriver): + self.event_firing_webdriver = self._parse_listener(event_firing_webdriver) if is_truthy(plugins): plugin_libs = self._parse_plugins(plugins) libraries = libraries + plugin_libs self._drivers = WebDriverCache() DynamicCore.__init__(self, libraries) - self.ROBOT_LIBRARY_LISTENER = LibraryListener() - if is_truthy(event_firing_webdriver): - self.event_firing_webdriver = self._parse_listener(event_firing_webdriver) - else: - self.event_firing_webdriver = None - self._running_keyword = None def run_keyword(self, name, args, kwargs): self._running_keyword = name
robotframework/SeleniumLibrary
3d049d508f0f31bf003795f58848cc9d54d5e354
diff --git a/utest/test/api/plugin_tester.py b/utest/test/api/plugin_tester.py new file mode 100644 index 00000000..af90e679 --- /dev/null +++ b/utest/test/api/plugin_tester.py @@ -0,0 +1,16 @@ +from SeleniumLibrary.base import LibraryComponent, keyword + + +class plugin_tester(LibraryComponent): + + def __init__(self, ctx): + LibraryComponent.__init__(self, ctx) + ctx.event_firing_webdriver = 'should be last' + + @keyword + def foo(self): + self.info('foo') + + @keyword + def bar(self, arg): + self.info(arg) diff --git a/utest/test/api/test_plugins.py b/utest/test/api/test_plugins.py index b594866c..d84a8d16 100644 --- a/utest/test/api/test_plugins.py +++ b/utest/test/api/test_plugins.py @@ -103,3 +103,9 @@ class ExtendingSeleniumLibrary(unittest.TestCase): no_inherit = os.path.join(self.root_dir, 'my_lib_not_inherit.py') with self.assertRaises(PluginError): SeleniumLibrary(plugins=no_inherit) + + def test_plugin_as_last_in_init(self): + plugin_file = os.path.join(self.root_dir, 'plugin_tester.py') + event_firing_wd = os.path.join(self.root_dir, 'MyListener.py') + sl = SeleniumLibrary(plugins=plugin_file, event_firing_webdriver=event_firing_wd) + self.assertEqual(sl.event_firing_webdriver, 'should be last')
Plugins should be last thing loaded in the SeleniumLibrary __init__ In the library init, plugins are loaded after the Event Firing WebDriver. There was discussion in the slack that user wants to plugin to also add a Event Firing WebDriver class to the library. But this is not currently possible because plugins are loaded before the Event Firing WebDriver and it overwrites what plugin is doing. To overcome this problem, add plugins as last in the SeleniumLibrary [__init__](https://github.com/robotframework/SeleniumLibrary/blob/master/src/SeleniumLibrary/__init__.py#L348).
0.0
3d049d508f0f31bf003795f58848cc9d54d5e354
[ "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_as_last_in_init" ]
[ "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_comma_and_space", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_comma_and_space_with_arg", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_no_libraries", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_no_library_component_inherit", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_libraries", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_library", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_library_with_args", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_plugin_with_kw_args", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_does_not_exist", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_wrong_import_with_path", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_sl_with_kw_args_plugin" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-08-16 23:16:37+00:00
apache-2.0
5,272
robotframework__SeleniumLibrary-1431
diff --git a/docs/extending/extending.rst b/docs/extending/extending.rst index d143e884..9b521229 100644 --- a/docs/extending/extending.rst +++ b/docs/extending/extending.rst @@ -217,15 +217,16 @@ log Wrapper to ``robot.api.logger.write`` method. Also following attributes are available from the ``LibraryComponent`` class: -============== ===================================================================== - Attribute Description -============== ===================================================================== -driver Currently active browser/WebDriver instance in the SeleniumLibrary. -drivers `Cache`_ for the opened browsers/WebDriver instances. -element_finder Read/write attribute for the `ElementFinder`_ instance. -ctx Instance of the SeleniumLibrary. -log_dir Folder where output files are written. -============== ===================================================================== +====================== ============================================================================== + Attribute Description +====================== ============================================================================== +driver Currently active browser/WebDriver instance in the SeleniumLibrary. +drivers `Cache`_ for the opened browsers/WebDriver instances. +element_finder Read/write attribute for the `ElementFinder`_ instance. +ctx Instance of the SeleniumLibrary. +log_dir Folder where output files are written. +event_firing_webdriver Read/write attribute for the SeleniumLibrary `EventFiringWebDriver`_ instance. +====================== ============================================================================== See the `SeleniumLibrary init`_, the `LibraryComponent`_ and the `ContextAware`_ classes for further implementation details. diff --git a/src/SeleniumLibrary/base/context.py b/src/SeleniumLibrary/base/context.py index d215441d..47f9ab6d 100644 --- a/src/SeleniumLibrary/base/context.py +++ b/src/SeleniumLibrary/base/context.py @@ -43,6 +43,14 @@ class ContextAware(object): def element_finder(self, value): self.ctx._element_finder = value + @property + def event_firing_webdriver(self): + return self.ctx.event_firing_webdriver + + @event_firing_webdriver.setter + def event_firing_webdriver(self, event_firing_webdriver): + self.ctx.event_firing_webdriver = event_firing_webdriver + def find_element(self, locator, tag=None, required=True, parent=None): """Find element matching `locator`.
robotframework/SeleniumLibrary
405786bd59f0c02c8d3595b2c8b52b926b41596c
diff --git a/utest/test/api/plugin_with_event_firing_webdriver.py b/utest/test/api/plugin_with_event_firing_webdriver.py new file mode 100644 index 00000000..8dbf13c7 --- /dev/null +++ b/utest/test/api/plugin_with_event_firing_webdriver.py @@ -0,0 +1,12 @@ +from SeleniumLibrary.base import LibraryComponent, keyword + + +class plugin_with_event_firing_webdriver(LibraryComponent): + + def __init__(self, ctx): + LibraryComponent.__init__(self, ctx) + self.event_firing_webdriver = 'event_firing_webdriver' + + @keyword + def tidii(self): + self.info('foo') diff --git a/utest/test/api/test_plugins.py b/utest/test/api/test_plugins.py index d84a8d16..b9aa4cb4 100644 --- a/utest/test/api/test_plugins.py +++ b/utest/test/api/test_plugins.py @@ -109,3 +109,9 @@ class ExtendingSeleniumLibrary(unittest.TestCase): event_firing_wd = os.path.join(self.root_dir, 'MyListener.py') sl = SeleniumLibrary(plugins=plugin_file, event_firing_webdriver=event_firing_wd) self.assertEqual(sl.event_firing_webdriver, 'should be last') + + def test_easier_event_firing_webdriver_from_plugin(self): + plugin_file = os.path.join(self.root_dir, 'plugin_with_event_firing_webdriver.py') + sl = SeleniumLibrary(plugins=plugin_file) + self.assertEqual(sl._plugin_keywords, ['tidii']) + self.assertEqual(sl.event_firing_webdriver, 'event_firing_webdriver')
Add better support for plugin to add event firing WebDriver For plugins, it would be easier to do something like this: ``` class MyPlugin(LibraryComponent): def __init__(self, ctx): LibraryComponent.__init__(self, ctx) self.event_firing_webdriver = WhatEverYouWant ```
0.0
405786bd59f0c02c8d3595b2c8b52b926b41596c
[ "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_easier_event_firing_webdriver_from_plugin" ]
[ "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_comma_and_space", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_comma_and_space_with_arg", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_no_libraries", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_no_library_component_inherit", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_libraries", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_library", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_library_with_args", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_parse_plugin_with_kw_args", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_as_last_in_init", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_does_not_exist", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_plugin_wrong_import_with_path", "utest/test/api/test_plugins.py::ExtendingSeleniumLibrary::test_sl_with_kw_args_plugin" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-08-20 19:48:53+00:00
apache-2.0
5,273
robotpy__robotpy-cppheaderparser-20
diff --git a/CppHeaderParser/CppHeaderParser.py b/CppHeaderParser/CppHeaderParser.py index 6bcd961..9de8d6a 100644 --- a/CppHeaderParser/CppHeaderParser.py +++ b/CppHeaderParser/CppHeaderParser.py @@ -377,6 +377,48 @@ def filter_out_attribute_keyword(stack): return stack +_nhack = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +def _split_namespace(namestack): + """ + Given a list of name elements, find the namespace portion + and return that as a string + + :rtype: Tuple[str, list] + """ + last_colon = None + for i, n in enumerate(namestack): + if n == ":": + last_colon = i + if i and n != ":" and not _nhack.match(n): + break + + if last_colon: + ns, namestack = ( + "".join(namestack[: last_colon + 1]), + namestack[last_colon + 1 :], + ) + else: + ns = "" + + return ns, namestack + + +def _iter_ns_str_reversed(namespace): + """ + Take a namespace string, and yield successively smaller portions + of it (ex foo::bar::baz::, foo::bar::, foo::). The last item yielded + will always be an empty string + """ + if namespace: + parts = namespace.split("::") + for i in range(len(parts) - 1, 0, -1): + yield "::".join(parts[:i]) + "::" + + yield "" + + class TagStr(str): """Wrapper for a string that allows us to store the line number associated with it""" @@ -1577,6 +1619,19 @@ class Resolver(object): result["fundamental"] = False result["class"] = klass result["unresolved"] = False + elif self.using: + # search for type in all enclosing namespaces + for ns in _iter_ns_str_reversed(result.get("namespace", "")): + nsalias = ns + alias + used = self.using.get(nsalias) + if used: + for i in ("type", "namespace", "ctypes_type", "raw_type"): + if i in used: + result[i] = used[i] + result["unresolved"] = False + break + else: + result["unresolved"] = True else: result["unresolved"] = True else: @@ -2567,6 +2622,10 @@ class CppHeader(_CppHeader): self.anon_union_counter = [-1, 0] self.templateRegistry = [] + #: Using directives in this header: key is full name for lookup, value + #: is :class:`.CppVariable` + self.using = {} + if len(self.headerFileName): fd = io.open(self.headerFileName, "r", encoding=encoding) headerFileStr = "".join(fd.readlines()) @@ -3035,12 +3094,25 @@ class CppHeader(_CppHeader): len(self.nameStack) == 2 and self.nameStack[0] == "friend" ): # friend class declaration pass - elif ( - len(self.nameStack) >= 2 - and self.nameStack[0] == "using" - and self.nameStack[1] == "namespace" - ): - pass # TODO + elif len(self.nameStack) >= 2 and self.nameStack[0] == "using": + if self.nameStack[1] == "namespace": + pass + else: + if len(self.nameStack) > 3 and self.nameStack[2] == "=": + # using foo = ns::bar + alias = self.nameStack[1] + ns, stack = _split_namespace(self.nameStack[3:]) + atype = CppVariable(stack) + else: + # using foo::bar + ns, stack = _split_namespace(self.nameStack[1:]) + atype = CppVariable(stack) + alias = atype["type"] + + atype["namespace"] = ns + atype["raw_type"] = ns + atype["type"] + alias = self.current_namespace() + alias + self.using[alias] = atype elif is_enum_namestack(self.nameStack): debug_print("trace")
robotpy/robotpy-cppheaderparser
1300fb522ebe154d4b523d391f970252ff3144e8
diff --git a/CppHeaderParser/test/test_CppHeaderParser.py b/CppHeaderParser/test/test_CppHeaderParser.py index c877c85..2769419 100644 --- a/CppHeaderParser/test/test_CppHeaderParser.py +++ b/CppHeaderParser/test/test_CppHeaderParser.py @@ -5,11 +5,14 @@ import sys import CppHeaderParser as CppHeaderParser -def filter_pameters(p): +def filter_pameters(p, extra=[]): "Reduce a list of dictionaries to the desired keys for function parameter testing" rtn = [] for d in p: - rtn.append({"name": d["name"], "desc": d["desc"], "type": d["type"]}) + rd = {} + for k in ["name", "desc", "type"] + extra: + rd[k] = d.get(k) + rtn.append(rd) return rtn @@ -2759,5 +2762,58 @@ class VarargFunc_TestCase(unittest.TestCase): self.assertEqual(len(vf["parameters"]), len(nvf["parameters"])) +class UsingNamespace_TestCase(unittest.TestCase): + def setUp(self): + self.cppHeader = CppHeaderParser.CppHeader( + """ +using std::thing; +namespace a { + using std::string; + using VoidFunction = std::function<void()>; + + void fn(string &s, VoidFunction fn, thing * t); +} +""", + "string", + ) + + def test_using(self): + self.assertIn("a::string", self.cppHeader.using) + self.assertIn("a::VoidFunction", self.cppHeader.using) + self.assertIn("thing", self.cppHeader.using) + + def test_fn(self): + self.maxDiff = None + self.assertEqual(len(self.cppHeader.functions), 1) + fn = self.cppHeader.functions[0] + self.assertEqual(fn["name"], "fn") + self.assertEqual( + filter_pameters(fn["parameters"], ["namespace", "raw_type"]), + [ + { + "type": "string", + "name": "s", + "desc": None, + "namespace": "std::", + "raw_type": "std::string", + }, + { + "type": "function<void ( )>", + "name": "fn", + "desc": None, + "namespace": "std::", + "raw_type": "std::function<void ( )>", + }, + { + "type": "thing", + "name": "t", + "desc": None, + "namespace": "std::", + "raw_type": "std::thing", + }, + ], + ) + + if __name__ == "__main__": unittest.main()
Doesn't resolve namespaces for types imported via `using` ``` #include <string> namespace a { using std::string; using VoidFunction = std::function<void()>; void fn(string &s, VoidFunction fn); } ``` It needs to tack on the namespace to the string/VoidFunction types. This does not cover `using namespace foo`, as that isn't doable using the information available to CppHeaderParser.
0.0
1300fb522ebe154d4b523d391f970252ff3144e8
[ "CppHeaderParser/test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_fn", "CppHeaderParser/test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_using" ]
[ "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_function_name_1", "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_function_name_2", "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_num_functions", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_1", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_2", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_num_functions", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_includes", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas0", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas1", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas2", "CppHeaderParser/test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_line_num_is_correct", "CppHeaderParser/test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_method_exists", "CppHeaderParser/test/test_CppHeaderParser.py::JSON_TestCase::test_hasLemon", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_classes", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_functions", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_num_typedefs", "CppHeaderParser/test/test_CppHeaderParser.py::CommentEOF_TestCase::test_comment" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-27 06:18:14+00:00
bsd-3-clause
5,274
robotpy__robotpy-cppheaderparser-28
diff --git a/CppHeaderParser/CppHeaderParser.py b/CppHeaderParser/CppHeaderParser.py index 2c16043..ee0082b 100644 --- a/CppHeaderParser/CppHeaderParser.py +++ b/CppHeaderParser/CppHeaderParser.py @@ -334,6 +334,262 @@ class CppParseError(Exception): pass +class CppTemplateParam(dict): + """ + Dictionary that contains the following: + + - ``decltype`` - If True, this is a decltype + - ``param`` - Parameter value or typename + - ``params`` - Only present if a template specialization. Is a list of + :class:`.CppTemplateParam` + - ``...`` - If True, indicates a parameter pack + """ + + def __init__(self): + self["param"] = "" + self["decltype"] = False + self["..."] = False + + def __str__(self): + s = [] + if self["decltype"]: + s.append("decltype") + + s.append(self["param"]) + + params = self.get("params") + if params is not None: + s.append("<%s>" % ",".join(str(p) for p in params)) + + if self["..."]: + if s: + s[-1] = s[-1] + "..." + else: + s.append("...") + + return "".join(s) + + +class CppBaseDecl(dict): + """ + Dictionary that contains the following + + - ``access`` - Anything in supportedAccessSpecifier + - ``class`` - Name of the type, along with template specializations + - ``decl_name`` - Name of the type only + - ``decl_params`` - Only present if a template specialization (Foo<int>). + Is a list of :class:`.CppTemplateParam`. + - ``decltype`` - True/False indicates a decltype, the contents are in + ``decl_name`` + - ``virtual`` - True/False indicates virtual inheritance + - ``...`` - True/False indicates a parameter pack + + """ + + def __init__(self): + self["access"] = "private" + self["class"] = "" + self["decl_name"] = "" + self["decltype"] = False + self["virtual"] = False + self["..."] = False + + def _fix_classname(self): + # set class to the full decl for legacy reasons + params = self.get("decl_params") + + if self["decltype"]: + s = "decltype" + else: + s = "" + + s += self["decl_name"] + if params: + s += "<%s>" % (",".join(str(p) for p in params)) + + if self["..."]: + s += "..." + + self["class"] = s + + +def _consume_parens(stack): + i = 0 + sl = len(stack) + nested = 1 + while i < sl: + t = stack[i] + i += 1 + if t == ")": + nested -= 1 + if nested == 0: + return i + elif t == "(": + nested += 1 + + raise CppParseError("Unmatched (") + + +def _parse_template_decl(stack): + debug_print("_parse_template_decl: %s" % stack) + params = [] + param = CppTemplateParam() + i = 0 + sl = len(stack) + init = True + require_ending = False + while i < sl: + t = stack[i] + i += 1 + if init: + init = False + if t == "decltype": + param["decltype"] = True + continue + + if t == ",": + params.append(param) + init = True + require_ending = False + param = CppTemplateParam() + + continue + elif t == ">": + params.append(param) + return params, i - 1 + + if require_ending: + raise CppParseError("expected comma, found %s" % t) + + if t == "...": + param["..."] = True + require_ending = True + elif t == "(": + s = stack[i:] + n = _consume_parens(s) + i += n + param["param"] = param["param"] + "".join(s[:n]) + else: + if t and t[0] == "<": + param["params"], n = _parse_template_decl([t[1:]] + stack[i:]) + i += n + else: + param["param"] = param["param"] + t + + raise CppParseError("Unmatched <") + + +def _parse_cppclass_name(c, stack): + # ignore first thing + i = 1 + sl = len(stack) + name = "" + require_ending = False + while i < sl: + t = stack[i] + i += 1 + + if t == ":": + if i >= sl: + raise CppParseError("class decl ended with ':'") + t = stack[i] + if t != ":": + # reached the base declaration + break + + i += 1 + name += "::" + continue + elif t == "final": + c["final"] = True + continue + + if require_ending: + raise CppParseError("Unexpected '%s' in class" % ("".join(stack[i - 1 :]))) + + if t and t[0] == "<": + c["class_params"], n = _parse_template_decl([t[1:]] + stack[i:]) + i += n + require_ending = True + else: + name += t + + c["namespace"] = "" + + # backwards compat + if name.startswith("anon-struct-"): + name = "<" + name + ">" + c["name"] = name + c["bare_name"] = name + + # backwards compat + classParams = c.get("class_params") + if classParams is not None: + c["name"] = c["name"] + "<%s>" % ",".join(str(p) for p in classParams) + + return i + + +def _parse_cpp_base(stack): + debug_print("Parsing base: %s" % stack) + inherits = [] + i = 0 + sl = len(stack) + init = True + base = CppBaseDecl() + require_ending = False + while i < sl: + t = stack[i] + i += 1 + + if init: + if t in supportedAccessSpecifier: + base["access"] = t + continue + elif t == "virtual": + base["virtual"] = True + continue + + init = False + + if t == "decltype": + base["decltype"] = True + continue + + if t == ",": + inherits.append(base) + base = CppBaseDecl() + init = True + require_ending = False + continue + + if require_ending: + raise CppParseError("expected comma, found '%s'" % t) + + if t == "(": + s = stack[i:] + n = _consume_parens(s) + i += n + base["decl_name"] = base["decl_name"] + "".join(s[:n]) + elif t == "...": + base["..."] = True + require_ending = True + else: + if t[0] == "<": + base["decl_params"], n = _parse_template_decl([t[1:]] + stack[i:]) + i += n + require_ending = True + else: + base["decl_name"] = base["decl_name"] + t + + # backwards compat + inherits.append(base) + for base in inherits: + base._fix_classname() + + return inherits + + class CppClass(dict): """ Dictionary that contains at least the following keys: @@ -341,11 +597,7 @@ class CppClass(dict): * ``name`` - Name of the class * ``doxygen`` - Doxygen comments associated with the class if they exist * ``inherits`` - List of Classes that this one inherits. Values are - dictionaries with the following key/values: - - - ``access`` - Anything in supportedAccessSpecifier - - ``class`` - Name of the class - + :class:`.CppBaseDecl` * ``methods`` - Dictionary where keys are from supportedAccessSpecifier and values are a lists of :class:`.CppMethod` * ``namespace`` - Namespace of class @@ -413,10 +665,10 @@ class CppClass(dict): return r def __init__(self, nameStack, curTemplate, doxygen, location): - #: hm self["nested_classes"] = [] self["parent"] = None self["abstract"] = False + self["final"] = False self._public_enums = {} self._public_structs = {} self._public_typedefs = {} @@ -431,145 +683,18 @@ class CppClass(dict): if doxygen: self["doxygen"] = doxygen - if "::" in "".join(nameStack): - # Re-Join class paths (ex ['class', 'Bar', ':', ':', 'Foo'] -> ['class', 'Bar::Foo'] - try: - new_nameStack = [] - for name in nameStack: - if len(new_nameStack) == 0: - new_nameStack.append(name) - elif name == ":" and new_nameStack[-1].endswith(":"): - new_nameStack[-1] += name - elif new_nameStack[-1].endswith("::"): - new_nameStack[-2] += new_nameStack[-1] + name - del new_nameStack[-1] - else: - new_nameStack.append(name) - trace_print( - "Convert from namestack\n %s\nto\n%s" % (nameStack, new_nameStack) - ) - nameStack = new_nameStack - except: - pass + # consume name of class, with any namespaces or templates + n = _parse_cppclass_name(self, nameStack) - # Handle final specifier - self["final"] = False - try: - final_index = nameStack.index("final") - # Dont trip up the rest of the logic - del nameStack[final_index] - self["final"] = True - trace_print("final") - except: - pass + # consume bases + baseStack = nameStack[n:] + if baseStack: + self["inherits"] = _parse_cpp_base(baseStack) + else: + self["inherits"] = [] - self["name"] = nameStack[1] set_location_info(self, location) - # Handle template classes - if len(nameStack) > 3 and nameStack[2].startswith("<"): - open_template_count = 0 - param_separator = 0 - found_first = False - i = 0 - for elm in nameStack: - if "<" in elm: - open_template_count += 1 - found_first = True - elif ">" in elm: - open_template_count -= 1 - if found_first and open_template_count == 0: - self["name"] = "".join(nameStack[1 : i + 1]) - break - i += 1 - elif ":" in nameStack: - self["name"] = nameStack[nameStack.index(":") - 1] - - inheritList = [] - - if nameStack.count(":") == 1: - nameStack = nameStack[nameStack.index(":") + 1 :] - while len(nameStack): - tmpStack = [] - tmpInheritClass = {"access": "private", "virtual": False} - if "," in nameStack: - tmpStack = nameStack[: nameStack.index(",")] - nameStack = nameStack[nameStack.index(",") + 1 :] - else: - tmpStack = nameStack - nameStack = [] - - # Convert template classes to one name in the last index - for i in range(0, len(tmpStack)): - if "<" in tmpStack[i]: - tmpStack2 = tmpStack[: i - 1] - tmpStack2.append("".join(tmpStack[i - 1 :])) - tmpStack = tmpStack2 - break - if len(tmpStack) == 0: - break - elif len(tmpStack) == 1: - tmpInheritClass["class"] = tmpStack[0] - elif len(tmpStack) == 2: - tmpInheritClass["access"] = tmpStack[0] - tmpInheritClass["class"] = tmpStack[1] - elif len(tmpStack) == 3 and "virtual" in tmpStack: - tmpInheritClass["access"] = ( - tmpStack[1] if tmpStack[1] != "virtual" else tmpStack[0] - ) - tmpInheritClass["class"] = tmpStack[2] - tmpInheritClass["virtual"] = True - else: - warning_print( - "Warning: can not parse inheriting class %s" - % (" ".join(tmpStack)) - ) - if ">" in tmpStack: - pass # allow skip templates for now - else: - raise NotImplementedError - - if "class" in tmpInheritClass: - inheritList.append(tmpInheritClass) - - elif nameStack.count(":") == 2: - self["parent"] = self["name"] - self["name"] = nameStack[-1] - - elif nameStack.count(":") > 2 and nameStack[0] in ("class", "struct"): - tmpStack = nameStack[nameStack.index(":") + 1 :] - - superTmpStack = [[]] - for tok in tmpStack: - if tok == ",": - superTmpStack.append([]) - else: - superTmpStack[-1].append(tok) - - for tmpStack in superTmpStack: - tmpInheritClass = {"access": "private"} - - if len(tmpStack) and tmpStack[0] in supportedAccessSpecifier: - tmpInheritClass["access"] = tmpStack[0] - tmpStack = tmpStack[1:] - - inheritNSStack = [] - while len(tmpStack) > 3: - if tmpStack[0] == ":": - break - if tmpStack[1] != ":": - break - if tmpStack[2] != ":": - break - inheritNSStack.append(tmpStack[0]) - tmpStack = tmpStack[3:] - if len(tmpStack) == 1 and tmpStack[0] != ":": - inheritNSStack.append(tmpStack[0]) - tmpInheritClass["class"] = "::".join(inheritNSStack) - inheritList.append(tmpInheritClass) - - self["inherits"] = inheritList - if curTemplate: self["template"] = curTemplate trace_print("Setting template to '%s'" % self["template"]) @@ -2375,7 +2500,7 @@ class _CppHeader(Resolver): if len(self.nameStack) == 1: self.anon_struct_counter += 1 # We cant handle more than 1 anonymous struct, so name them uniquely - self.nameStack.append("<anon-struct-%d>" % self.anon_struct_counter) + self.nameStack.append("anon-struct-%d" % self.anon_struct_counter) if self.nameStack[0] == "class": self.curAccessSpecifier = "private" @@ -2406,12 +2531,14 @@ class _CppHeader(Resolver): newClass["declaration_method"] = self.nameStack[0] self.classes_order.append(newClass) # good idea to save ordering self.stack = [] # fixes if class declared with ';' in closing brace + classKey = newClass["name"] + if parent: newClass["namespace"] = self.classes[parent]["namespace"] + "::" + parent newClass["parent"] = parent self.classes[parent]["nested_classes"].append(newClass) ## supports nested classes with the same name ## - self.curClass = key = parent + "::" + newClass["name"] + self.curClass = key = parent + "::" + classKey self._classes_brace_level[key] = self.braceDepth elif newClass["parent"]: # nested class defined outside of parent. A::B {...} @@ -2419,14 +2546,13 @@ class _CppHeader(Resolver): newClass["namespace"] = self.classes[parent]["namespace"] + "::" + parent self.classes[parent]["nested_classes"].append(newClass) ## supports nested classes with the same name ## - self.curClass = key = parent + "::" + newClass["name"] + self.curClass = key = parent + "::" + classKey self._classes_brace_level[key] = self.braceDepth else: newClass["namespace"] = self.cur_namespace() - key = newClass["name"] - self.curClass = newClass["name"] - self._classes_brace_level[newClass["name"]] = self.braceDepth + self.curClass = key = classKey + self._classes_brace_level[classKey] = self.braceDepth if not key.endswith("::") and not key.endswith(" ") and len(key) != 0: if key in self.classes: diff --git a/docs/api.rst b/docs/api.rst index c689857..50a10b8 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -24,8 +24,8 @@ CppHeaderParser --------------- .. automodule:: CppHeaderParser.CppHeaderParser - :members: CppClass, CppEnum, CppHeader, CppMethod, CppParseError, - CppStruct, CppUnion, CppVariable, TagStr, + :members: CppBaseDecl, CppClass, CppEnum, CppHeader, CppMethod, CppParseError, + CppStruct, CppTemplateParam, CppUnion, CppVariable, TagStr, ignoreSymbols :undoc-members: :show-inheritance:
robotpy/robotpy-cppheaderparser
4ff8ab258b134725a3469926d264252a6c977dfc
diff --git a/CppHeaderParser/test/test_CppHeaderParser.py b/CppHeaderParser/test/test_CppHeaderParser.py index 9ab0bbf..b316555 100644 --- a/CppHeaderParser/test/test_CppHeaderParser.py +++ b/CppHeaderParser/test/test_CppHeaderParser.py @@ -573,18 +573,37 @@ class Bug3488360_TestCase(unittest.TestCase): def test_Bananna_inherits(self): self.assertEqual( self.cppHeader.classes["Bananna"]["inherits"], - [{"access": "public", "class": "Citrus::BloodOrange", "virtual": False}], + [ + { + "access": "public", + "class": "Citrus::BloodOrange", + "decl_name": "Citrus::BloodOrange", + "decltype": False, + "virtual": False, + "...": False, + } + ], ) def test_ExcellentCake_inherits(self): self.assertEqual( self.cppHeader.classes["ExcellentCake"]["inherits"], [ - {"access": "private", "class": "Citrus::BloodOrange", "virtual": False}, + { + "access": "private", + "class": "Citrus::BloodOrange", + "decl_name": "Citrus::BloodOrange", + "decltype": False, + "virtual": False, + "...": False, + }, { "access": "private", "class": "Convoluted::Nested::Mixin", + "decl_name": "Convoluted::Nested::Mixin", + "decltype": False, "virtual": False, + "...": False, }, ], ) @@ -2955,5 +2974,194 @@ public: self.assertLocation(child, "child.h", 9) +class TemplateMadness_TestCase(unittest.TestCase): + def setUp(self): + self.cppHeader = CppHeaderParser.CppHeader( + """ +template <typename Type> +class XYZ : public MyBaseClass<Type, int> +{ + public: + XYZ(); +}; + +template <typename ValueT, typename... IterTs> +class concat_iterator + : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, + std::forward_iterator_tag, ValueT> { +}; + +template <std::size_t N, std::size_t... I> +struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; + +template <std::size_t... I> +struct build_index_impl<0, I...> : index_sequence<I...> {}; + +//template <typename F, typename P, typename... T> +//struct is_callable<F, P, typelist<T...>, +// void_t<decltype(((*std::declval<P>()).*std::declval<F>())(std::declval<T>()...))>> +// : std::true_type {}; + +template <typename T...> +struct S : public T... {}; + +""", + "string", + ) + + def testXYZ(self): + c = self.cppHeader.classes["XYZ"] + self.assertEqual("XYZ", c["name"]) + self.assertEqual( + [ + { + "access": "public", + "class": "MyBaseClass<Type,int>", + "decltype": False, + "decl_name": "MyBaseClass", + "decl_params": [ + {"param": "Type", "...": False, "decltype": False}, + {"param": "int", "...": False, "decltype": False}, + ], + "virtual": False, + "...": False, + } + ], + c["inherits"], + ) + + def testConcatIterator(self): + c = self.cppHeader.classes["concat_iterator"] + self.assertEqual("concat_iterator", c["name"]) + self.assertEqual( + [ + { + "access": "public", + "class": "iterator_facade_base<concat_iterator<ValueT,IterTs...>,std::forward_iterator_tag,ValueT>", + "decltype": False, + "decl_name": "iterator_facade_base", + "decl_params": [ + { + "decltype": False, + "param": "concat_iterator", + "params": [ + {"param": "ValueT", "...": False, "decltype": False}, + {"param": "IterTs", "...": True, "decltype": False}, + ], + "...": False, + }, + { + "decltype": False, + "param": "std::forward_iterator_tag", + "...": False, + }, + {"decltype": False, "param": "ValueT", "...": False}, + ], + "virtual": False, + "...": False, + } + ], + c["inherits"], + ) + + def testBuildIndexImpl1(self): + c = self.cppHeader.classes["build_index_impl"] + self.assertEqual("build_index_impl", c["name"]) + self.assertEqual( + [ + { + "access": "private", + "class": "build_index_impl<N-1,N-1,I...>", + "decltype": False, + "decl_name": "build_index_impl", + "decl_params": [ + {"param": "N-1", "...": False, "decltype": False}, + {"param": "N-1", "...": False, "decltype": False}, + {"param": "I", "...": True, "decltype": False}, + ], + "virtual": False, + "...": False, + } + ], + c["inherits"], + ) + + def testBuildIndexImpl2(self): + c = self.cppHeader.classes["build_index_impl<0,I...>"] + self.assertEqual("build_index_impl", c["bare_name"]) + self.assertEqual("build_index_impl<0,I...>", c["name"]) + self.assertEqual( + [ + {"decltype": False, "param": "0", "...": False}, + {"decltype": False, "param": "I", "...": True}, + ], + c["class_params"], + ) + self.assertEqual( + [ + { + "access": "private", + "class": "index_sequence<I...>", + "decltype": False, + "decl_name": "index_sequence", + "decl_params": [{"decltype": False, "param": "I", "...": True}], + "virtual": False, + "...": False, + } + ], + c["inherits"], + ) + + # def testIsCallable(self): + # c = self.cppHeader.classes["is_callable"] + # self.assertEqual("is_callable", c["name"]) + # self.assertEqual( + # [ + # {"param": "F", "...": False, "decltype": False}, + # {"param": "P", "...": False, "decltype": False}, + # { + # "param": "typelist", + # "...": False, + # "decltype": False, + # "params": [{"param": "T", "...": True, "decltype": False},], + # }, + # { + # "param": "void_t", + # "...": False, + # "decltype": False, + # "params": [ + # { + # "param": "(((*std::declval<P>()).*std::declval<F>())(std::declval<T>()...))", + # "...": False, + # "decltype": True, + # }, + # ], + # }, + # ], + # c["class_params"], + # ) + # self.assertEqual( + # [{"access": "private", "class": "std::true_type", "virtual": False,}], + # c["inherits"], + # ) + + def testS(self): + c = self.cppHeader.classes["S"] + self.assertEqual("S", c["name"]) + self.assertEqual( + [ + { + "access": "public", + "class": "T...", + "decl_name": "T", + "virtual": False, + "...": True, + "decltype": False, + } + ], + c["inherits"], + ) + + if __name__ == "__main__": unittest.main()
Incorrectly parsing inheritance with multiple template arguments The following header is not parsed correctly ```C++ template <typename Type> class XYZ : public MyBaseClass<Type, int> { public: XYZ(); }; ``` CppHeaderParser detects two base classes ( 1.: MyBaseClass<Type, 2: int>) instead of one templated base class.
0.0
4ff8ab258b134725a3469926d264252a6c977dfc
[ "CppHeaderParser/test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl1", "CppHeaderParser/test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl2", "CppHeaderParser/test/test_CppHeaderParser.py::TemplateMadness_TestCase::testConcatIterator", "CppHeaderParser/test/test_CppHeaderParser.py::TemplateMadness_TestCase::testS", "CppHeaderParser/test/test_CppHeaderParser.py::TemplateMadness_TestCase::testXYZ" ]
[ "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_function_name_1", "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_function_name_2", "CppHeaderParser/test/test_CppHeaderParser.py::functions_TestCase::test_num_functions", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_1", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_2", "CppHeaderParser/test/test_CppHeaderParser.py::functions2_TestCase::test_num_functions", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_includes", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas0", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas1", "CppHeaderParser/test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas2", "CppHeaderParser/test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_line_num_is_correct", "CppHeaderParser/test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_method_exists", "CppHeaderParser/test/test_CppHeaderParser.py::JSON_TestCase::test_hasLemon", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_classes", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_functions", "CppHeaderParser/test/test_CppHeaderParser.py::HALControlWord_TestCase::test_num_typedefs", "CppHeaderParser/test/test_CppHeaderParser.py::CommentEOF_TestCase::test_comment", "CppHeaderParser/test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_fn", "CppHeaderParser/test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_using", "CppHeaderParser/test/test_CppHeaderParser.py::StaticFn_TestCase::test_fn", "CppHeaderParser/test/test_CppHeaderParser.py::ConstExpr_TestCase::test_fn", "CppHeaderParser/test/test_CppHeaderParser.py::DefaultEnum_TestCase::test_fn", "CppHeaderParser/test/test_CppHeaderParser.py::MultiFile_TestCase::test_fn" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-11-19 05:34:25+00:00
bsd-3-clause
5,275
robotpy__robotpy-cppheaderparser-40
diff --git a/CppHeaderParser/CppHeaderParser.py b/CppHeaderParser/CppHeaderParser.py index 9686d4e..56739b0 100644 --- a/CppHeaderParser/CppHeaderParser.py +++ b/CppHeaderParser/CppHeaderParser.py @@ -408,7 +408,7 @@ class CppBaseDecl(dict): if self["..."]: s += "..." - self["class"] = s + return s def _consume_parens(stack): @@ -564,7 +564,14 @@ def _parse_cpp_base(stack, default_access): continue if require_ending: - raise CppParseError("expected comma, found '%s'" % t) + if t == "::": + if "decl_params" in base: + base["decl_name"] = base._fix_classname() + del base["decl_params"] + base["..."] + require_ending = False + else: + raise CppParseError("expected comma, found '%s'" % t) if t == "(": s = stack[i:] @@ -585,7 +592,7 @@ def _parse_cpp_base(stack, default_access): # backwards compat inherits.append(base) for base in inherits: - base._fix_classname() + base["class"] = base._fix_classname() return inherits
robotpy/robotpy-cppheaderparser
561449c9a2f5dc0b41ae4e4128bde9db27c83989
diff --git a/test/test_CppHeaderParser.py b/test/test_CppHeaderParser.py index f61acc2..d23cb23 100644 --- a/test/test_CppHeaderParser.py +++ b/test/test_CppHeaderParser.py @@ -3792,6 +3792,7 @@ struct Outer { self.assertEqual(props[0]["name"], "x") self.assertEqual(props[1]["name"], "y") + class Deleted_TestCase(unittest.TestCase): def setUp(self): self.cppHeader = CppHeaderParser.CppHeader( @@ -3809,5 +3810,33 @@ public: self.assertEqual(m["constructor"], True) self.assertEqual(m["deleted"], True) + +class BaseTemplateNs_TestCase(unittest.TestCase): + def setUp(self): + self.cppHeader = CppHeaderParser.CppHeader( + """ +class A : public B<int, int>::C {}; +""", + "string", + ) + + def test_fn(self): + c = self.cppHeader.classes["A"] + self.assertEqual("A", c["name"]) + self.assertEqual( + [ + { + "access": "public", + "class": "B<int,int>::C", + "decl_name": "B<int,int>::C", + "virtual": False, + "...": False, + "decltype": False, + } + ], + c["inherits"], + ) + + if __name__ == "__main__": unittest.main()
Regression in 3.3.0 I use to work with 3.2.0 release, but I have a regression when trying to update to latest revision. It seems a regression was introduced in the 3.3.0 release. Indeed, let ```header.hxx``` be the following header file: ```cpp class A { public: A(); private: class A : public B<int,int>::C { }; }; ``` Trying to parse with CppHeaderParser 3.3.0, I get the following issue: ```bash $ python ess.py Traceback (most recent call last): File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 2859, in __init__ self._evaluate_stack() File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 3329, in _evaluate_stack self._evaluate_class_stack() File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 2488, in _evaluate_class_stack self.curAccessSpecifier, File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 709, in __init__ self["inherits"] = _parse_cpp_base(baseStack, defaultAccess) File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 567, in _parse_cpp_base raise CppParseError("expected comma, found '%s'" % t) CppHeaderParser.CppHeaderParser.CppParseError: expected comma, found '::' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "ess.py", line 3, in <module> CppHeaderParser.CppHeader('test.hxx') File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 2994, in __init__ CppParseError(msg), e, File "<string>", line 1, in raise_exc CppHeaderParser.CppHeaderParser.CppParseError: Not able to parse test.hxx on line 8 evaluating '{': expected comma, found '::' Error around: class A : public B < int , int > :: C ``` With 3.2.0, I have no exception raised, the output dict is: ```python {'classes': {'A': {'nested_classes': [{'nested_classes': [], 'parent': 'A', 'abstract': False, 'namespace': '::A', 'final': False, 'name': 'A', 'filename': 'test.hxx', 'line_number': 7, 'inherits': [{'access': 'public', 'virtual': False, 'class': 'B<int'}, {'access': 'int', 'virtual': False, 'class': '>::C'}], 'methods': {'public': [], 'protected': [], 'private': []}, 'properties': {'public': [], 'protected': [], 'private': []}, 'enums': {'public': [], 'protected': [], 'private': []}, 'structs': {'public': [], 'protected': [], 'private': []}, 'typedefs': {'public': [], 'protected': [], 'private': []}, 'forward_declares': {'public': [], 'protected': [], 'private': []}, 'declaration_method': 'class'}], 'parent': None, 'abstract': False, 'namespace': '', 'final': False, 'name': 'A', 'filename': 'test.hxx', 'line_number': 1, 'inherits': [], 'methods': {'public': [{'rtnType': 'void', 'name': 'A', 'noexcept': None, 'const': False, 'final': False, 'override': False, 'debug': 'A ( ) ;', 'class': None, 'namespace': '', 'defined': False, 'pure_virtual': False, 'operator': False, 'constructor': True, 'destructor': False, 'extern': False, 'template': False, 'virtual': False, 'static': False, 'explicit': False, 'inline': False, 'friend': False, 'returns': '', 'returns_pointer': 0, 'returns_fundamental': True, 'returns_class': False, 'default': False, 'returns_reference': False, 'filename': 'test.hxx', 'line_number': 4, 'vararg': False, 'parameters': [], 'parent': {...}, 'path': 'A'}], 'protected': [], 'private': []}, 'properties': {'public': [], 'protected': [], 'private': []}, 'enums': {'public': [], 'protected': [], 'private': []}, 'structs': {'public': [], 'protected': [], 'private': []}, 'typedefs': {'public': [], 'protected': [], 'private': []}, 'forward_declares': {'public': [], 'protected': [], 'private': []}, 'declaration_method': 'class'}, 'A::A': {'nested_classes': [], 'parent': 'A', 'abstract': False, 'namespace': '::A', 'final': False, 'name': 'A', 'filename': 'test.hxx', 'line_number': 7, 'inherits': [{'access': 'public', 'virtual': False, 'class': 'B<int'}, {'access': 'int', 'virtual': False, 'class': '>::C'}], 'methods': {'public': [], 'protected': [], 'private': []}, 'properties': {'public': [], 'protected': [], 'private': []}, 'enums': {'public': [], 'protected': [], 'private': []}, 'structs': {'public': [], 'protected': [], 'private': []}, 'typedefs': {'public': [], 'protected': [], 'private': []}, 'forward_declares': {'public': [], 'protected': [], 'private': []}, 'declaration_method': 'class'}}, 'functions': [], 'enums': [], 'variables': []} ``` ping @rainman110
0.0
561449c9a2f5dc0b41ae4e4128bde9db27c83989
[ "test/test_CppHeaderParser.py::BaseTemplateNs_TestCase::test_fn" ]
[ "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions_TestCase::test_num_functions", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions2_TestCase::test_num_functions", "test/test_CppHeaderParser.py::Macro_TestCase::test_includes", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas0", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas1", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas2", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_line_num_is_correct", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_method_exists", "test/test_CppHeaderParser.py::LineNumAfterDivide_TestCase::test_line_num", "test/test_CppHeaderParser.py::JSON_TestCase::test_hasLemon", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_classes", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_functions", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_num_typedefs", "test/test_CppHeaderParser.py::CommentEOF_TestCase::test_comment", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_class", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_fn", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_using", "test/test_CppHeaderParser.py::StaticFn_TestCase::test_fn", "test/test_CppHeaderParser.py::ConstExpr_TestCase::test_fn", "test/test_CppHeaderParser.py::DefaultEnum_TestCase::test_fn", "test/test_CppHeaderParser.py::MultiFile_TestCase::test_fn", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl1", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl2", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testConcatIterator", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testS", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testXYZ", "test/test_CppHeaderParser.py::Attributes_TestCase::test_existance", "test/test_CppHeaderParser.py::EnumWithTemplates_TestCase::test_values", "test/test_CppHeaderParser.py::FreeTemplates_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls2", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var1", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var2", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_param", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_retval", "test/test_CppHeaderParser.py::StaticAssert_TestCase::test_nothing", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_cls_props", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_future", "test/test_CppHeaderParser.py::EnumClass_TestCase::test_enum", "test/test_CppHeaderParser.py::NestedResolving_TestCase::test_nothing", "test/test_CppHeaderParser.py::EnumCrash_TestCase::test_nothing", "test/test_CppHeaderParser.py::ExternInline_TestCase::test_fn", "test/test_CppHeaderParser.py::PointerTemplate_TestCase::test_fn", "test/test_CppHeaderParser.py::ParamWithInitializer_TestCase::test_fn", "test/test_CppHeaderParser.py::NestedClassAccess_TestCase::test_fn", "test/test_CppHeaderParser.py::AnonUnion_TestCase::test_fn", "test/test_CppHeaderParser.py::Deleted_TestCase::test_fn" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-03-03 17:02:33+00:00
bsd-3-clause
5,276
robotpy__robotpy-cppheaderparser-42
diff --git a/CppHeaderParser/CppHeaderParser.py b/CppHeaderParser/CppHeaderParser.py index 56739b0..7b07900 100644 --- a/CppHeaderParser/CppHeaderParser.py +++ b/CppHeaderParser/CppHeaderParser.py @@ -1685,7 +1685,7 @@ class Resolver(object): elif nestedTypedef: var["fundamental"] = is_fundamental(nestedTypedef) - if not var["fundamental"]: + if not var["fundamental"] and "method" in var: var["raw_type"] = var["method"]["path"] + "::" + tag else:
robotpy/robotpy-cppheaderparser
dd564dda795c3b78fc4843a80a5906577533521d
diff --git a/test/test_CppHeaderParser.py b/test/test_CppHeaderParser.py index d23cb23..a876d87 100644 --- a/test/test_CppHeaderParser.py +++ b/test/test_CppHeaderParser.py @@ -3838,5 +3838,35 @@ class A : public B<int, int>::C {}; ) +class NestedTypedef(unittest.TestCase): + def setUp(self): + self.cppHeader = CppHeaderParser.CppHeader( + """ +template <class SomeType> class A { + public: + typedef B <SomeType> C; + + A(); + + protected: + C aCInstance; +}; +""", + "string", + ) + + def test_fn(self): + c = self.cppHeader.classes["A"] + self.assertEqual("A", c["name"]) + + self.assertEqual(0, len(c["properties"]["public"])) + self.assertEqual(1, len(c["properties"]["protected"])) + self.assertEqual(0, len(c["properties"]["private"])) + + c = c["properties"]["protected"][0] + self.assertEqual(c["name"], "aCInstance") + self.assertEqual(c["type"], "C") + + if __name__ == "__main__": unittest.main()
Regression in 4.0.0 The following code works on 3.3.0 release but fails from 4.0.0 and later: ```python import CppHeaderParser h = """ template <class SomeType> class A { public: typedef B <SomeType> C; A(); protected: C aCInstance; }; """ a = CppHeaderParser.CppHeader(h, "string") print(a) ``` The error message is the following: ```bash Traceback (most recent call last): File "ess.py", line 15, in <module> a = CppHeaderParser.CppHeader(h, "string") File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 2981, in __init__ self.finalize() File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 1918, in finalize self.finalize_vars() File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 1664, in finalize_vars var["raw_type"] = var["method"]["path"] + "::" + tag KeyError: 'method' ``` Note that the issue comes from the last line ```C aCInstance;```. If type is changed to something else but C, string is parse correctly. ping @rainman110
0.0
dd564dda795c3b78fc4843a80a5906577533521d
[ "test/test_CppHeaderParser.py::NestedTypedef::test_fn" ]
[ "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions_TestCase::test_num_functions", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions2_TestCase::test_num_functions", "test/test_CppHeaderParser.py::Macro_TestCase::test_includes", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas0", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas1", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas2", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_line_num_is_correct", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_method_exists", "test/test_CppHeaderParser.py::LineNumAfterDivide_TestCase::test_line_num", "test/test_CppHeaderParser.py::JSON_TestCase::test_hasLemon", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_classes", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_functions", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_num_typedefs", "test/test_CppHeaderParser.py::CommentEOF_TestCase::test_comment", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_class", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_fn", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_using", "test/test_CppHeaderParser.py::StaticFn_TestCase::test_fn", "test/test_CppHeaderParser.py::ConstExpr_TestCase::test_fn", "test/test_CppHeaderParser.py::DefaultEnum_TestCase::test_fn", "test/test_CppHeaderParser.py::MultiFile_TestCase::test_fn", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl1", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl2", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testConcatIterator", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testS", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testXYZ", "test/test_CppHeaderParser.py::Attributes_TestCase::test_existance", "test/test_CppHeaderParser.py::EnumWithTemplates_TestCase::test_values", "test/test_CppHeaderParser.py::FreeTemplates_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls2", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var1", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var2", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_param", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_retval", "test/test_CppHeaderParser.py::StaticAssert_TestCase::test_nothing", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_cls_props", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_future", "test/test_CppHeaderParser.py::EnumClass_TestCase::test_enum", "test/test_CppHeaderParser.py::NestedResolving_TestCase::test_nothing", "test/test_CppHeaderParser.py::EnumCrash_TestCase::test_nothing", "test/test_CppHeaderParser.py::ExternInline_TestCase::test_fn", "test/test_CppHeaderParser.py::PointerTemplate_TestCase::test_fn", "test/test_CppHeaderParser.py::ParamWithInitializer_TestCase::test_fn", "test/test_CppHeaderParser.py::NestedClassAccess_TestCase::test_fn", "test/test_CppHeaderParser.py::AnonUnion_TestCase::test_fn", "test/test_CppHeaderParser.py::Deleted_TestCase::test_fn", "test/test_CppHeaderParser.py::BaseTemplateNs_TestCase::test_fn" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-03-04 07:01:57+00:00
bsd-3-clause
5,277
robotpy__robotpy-cppheaderparser-44
diff --git a/CppHeaderParser/CppHeaderParser.py b/CppHeaderParser/CppHeaderParser.py index 7b07900..cb8fda2 100644 --- a/CppHeaderParser/CppHeaderParser.py +++ b/CppHeaderParser/CppHeaderParser.py @@ -1957,6 +1957,7 @@ class _CppHeader(Resolver): "static": 0, "pointer": 0, "reference": 0, + "typedefs": 0, } self.resolve_type(meth["rtnType"], rtnType) if not rtnType["unresolved"]:
robotpy/robotpy-cppheaderparser
9a6a36e17c90f7d0bf3a68bb597a03372b649ac7
diff --git a/test/test_CppHeaderParser.py b/test/test_CppHeaderParser.py index a876d87..d3f54e7 100644 --- a/test/test_CppHeaderParser.py +++ b/test/test_CppHeaderParser.py @@ -3868,5 +3868,30 @@ template <class SomeType> class A { self.assertEqual(c["type"], "C") +class MoreTypedef(unittest.TestCase): + def setUp(self): + self.cppHeader = CppHeaderParser.CppHeader( + """ +typedef C A; + +class B { +public: + A aMethod(); +}; +""", + "string", + ) + + def test_fn(self): + c = self.cppHeader.classes["B"] + self.assertEqual("B", c["name"]) + + m = c["methods"]["public"][0] + self.assertEqual(m["name"], "aMethod") + self.assertEqual(m["rtnType"], "A") + + self.assertEqual(self.cppHeader.typedefs["A"], "C") + + if __name__ == "__main__": unittest.main()
Another regression in 4.0.0 Following example fails using 4.0.0 and newer (but not with 3.3.0 and older): ```python import CppHeaderParser h = """ typedef C A; class B { public: A aMethod(); } """ CppHeaderParser.CppHeader(h, "string") ``` Following exception is raised: ```bash Traceback (most recent call last): File "ess.py", line 12, in <module> CppHeaderParser.CppHeader(h, "string") File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 2981, in __init__ self.finalize() File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 1936, in finalize self.resolve_type(meth["rtnType"], rtnType) File "/home/thomas/miniconda3/envs/bindgen/lib/python3.7/site-packages/CppHeaderParser/CppHeaderParser.py", line 1551, in resolve_type result["typedefs"] += 1 KeyError: 'typedefs' ```
0.0
9a6a36e17c90f7d0bf3a68bb597a03372b649ac7
[ "test/test_CppHeaderParser.py::MoreTypedef::test_fn" ]
[ "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions_TestCase::test_num_functions", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_1", "test/test_CppHeaderParser.py::functions2_TestCase::test_function_name_2", "test/test_CppHeaderParser.py::functions2_TestCase::test_num_functions", "test/test_CppHeaderParser.py::Macro_TestCase::test_includes", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas0", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas1", "test/test_CppHeaderParser.py::Macro_TestCase::test_pragmas2", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_line_num_is_correct", "test/test_CppHeaderParser.py::FilterMagicMacro_TestCase::test_method_exists", "test/test_CppHeaderParser.py::LineNumAfterDivide_TestCase::test_line_num", "test/test_CppHeaderParser.py::JSON_TestCase::test_hasLemon", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_classes", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_functions", "test/test_CppHeaderParser.py::HALControlWord_TestCase::test_num_typedefs", "test/test_CppHeaderParser.py::CommentEOF_TestCase::test_comment", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_class", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_fn", "test/test_CppHeaderParser.py::UsingNamespace_TestCase::test_using", "test/test_CppHeaderParser.py::StaticFn_TestCase::test_fn", "test/test_CppHeaderParser.py::ConstExpr_TestCase::test_fn", "test/test_CppHeaderParser.py::DefaultEnum_TestCase::test_fn", "test/test_CppHeaderParser.py::MultiFile_TestCase::test_fn", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl1", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testBuildIndexImpl2", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testConcatIterator", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testS", "test/test_CppHeaderParser.py::TemplateMadness_TestCase::testXYZ", "test/test_CppHeaderParser.py::Attributes_TestCase::test_existance", "test/test_CppHeaderParser.py::EnumWithTemplates_TestCase::test_values", "test/test_CppHeaderParser.py::FreeTemplates_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_cls2", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_fn", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var1", "test/test_CppHeaderParser.py::MessedUpDoxygen_TestCase::test_var2", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_param", "test/test_CppHeaderParser.py::EnumParameter_TestCase::test_enum_retval", "test/test_CppHeaderParser.py::StaticAssert_TestCase::test_nothing", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_cls_props", "test/test_CppHeaderParser.py::InitializerWithInitializerList_TestCase::test_future", "test/test_CppHeaderParser.py::EnumClass_TestCase::test_enum", "test/test_CppHeaderParser.py::NestedResolving_TestCase::test_nothing", "test/test_CppHeaderParser.py::EnumCrash_TestCase::test_nothing", "test/test_CppHeaderParser.py::ExternInline_TestCase::test_fn", "test/test_CppHeaderParser.py::PointerTemplate_TestCase::test_fn", "test/test_CppHeaderParser.py::ParamWithInitializer_TestCase::test_fn", "test/test_CppHeaderParser.py::NestedClassAccess_TestCase::test_fn", "test/test_CppHeaderParser.py::AnonUnion_TestCase::test_fn", "test/test_CppHeaderParser.py::Deleted_TestCase::test_fn", "test/test_CppHeaderParser.py::BaseTemplateNs_TestCase::test_fn", "test/test_CppHeaderParser.py::NestedTypedef::test_fn" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-03-04 15:44:11+00:00
bsd-3-clause
5,278
robotpy__robotpy-wpilib-utilities-189
diff --git a/robotpy_ext/common_drivers/distance_sensors.py b/robotpy_ext/common_drivers/distance_sensors.py index 2255a6a..071e5b4 100644 --- a/robotpy_ext/common_drivers/distance_sensors.py +++ b/robotpy_ext/common_drivers/distance_sensors.py @@ -70,7 +70,7 @@ class SharpIR2Y0A21: return max(min(d, 80.0), 10.0) -class SharpIRGP2Y0A41SK0F: +class SharpIR2Y0A41: """ Sharp GP2Y0A41SK0F is an analog IR sensor capable of measuring distances from 4cm to 40cm. Output distance is measured in @@ -102,3 +102,7 @@ class SharpIRGP2Y0A41SK0F: # Constrain output return max(min(d, 35.0), 4.5) + + +# backwards compat +SharpIRGP2Y0A41SK0F = SharpIR2Y0A41 diff --git a/robotpy_ext/common_drivers/distance_sensors_sim.py b/robotpy_ext/common_drivers/distance_sensors_sim.py new file mode 100644 index 0000000..1102736 --- /dev/null +++ b/robotpy_ext/common_drivers/distance_sensors_sim.py @@ -0,0 +1,72 @@ +import math +import wpilib + +from wpilib.simulation import AnalogInputSim + +from .distance_sensors import SharpIR2Y0A02, SharpIR2Y0A21, SharpIR2Y0A41 + + +class SharpIR2Y0A02Sim: + """ + An easy to use simulation interface for a Sharp GP2Y0A02YK0F + """ + + def __init__(self, sensor: SharpIR2Y0A02) -> None: + assert isinstance(sensor, SharpIR2Y0A02) + self._sim = AnalogInputSim(sensor.distance) + self._distance = 0 + + def getDistance(self) -> float: + """Get set distance (not distance sensor sees) in centimeters""" + return self._distance + + def setDistance(self, d) -> None: + """Set distance in centimeters""" + self._distance = d + d = max(min(d, 145.0), 22.5) + v = math.pow(d / 62.28, 1 / -1.092) + self._sim.setVoltage(v) + + +class SharpIR2Y0A21Sim: + """ + An easy to use simulation interface for a Sharp GP2Y0A21YK0F + """ + + def __init__(self, sensor: SharpIR2Y0A21) -> None: + assert isinstance(sensor, SharpIR2Y0A21) + self._sim = AnalogInputSim(sensor.distance) + self._distance = 0 + + def getDistance(self) -> float: + """Get set distance (not distance sensor sees) in centimeters""" + return self._distance + + def setDistance(self, d) -> None: + """Set distance in centimeters""" + self._distance = d + d = max(min(d, 80.0), 10.0) + v = math.pow(d / 26.449, 1 / -1.226) + self._sim.setVoltage(v) + + +class SharpIR2Y0A41Sim: + """ + An easy to use simulation interface for a Sharp GP2Y0A41SK0F + """ + + def __init__(self, sensor: SharpIR2Y0A41) -> None: + assert isinstance(sensor, SharpIR2Y0A41) + self._sim = AnalogInputSim(sensor.distance) + self._distance = 0 + + def getDistance(self) -> float: + """Get set distance (not distance sensor sees) in centimeters""" + return self._distance + + def setDistance(self, d) -> None: + """Set distance in centimeters""" + self._distance = d + d = max(min(d, 35.0), 4.5) + v = math.pow(d / 12.84, 1 / -0.9824) + self._sim.setVoltage(v)
robotpy/robotpy-wpilib-utilities
2e627fe0ac923c42a652f49bd01f2fd255aa9f1d
diff --git a/tests/conftest.py b/tests/conftest.py index 7532386..d5d3b94 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -36,3 +36,16 @@ def wpitime(): yield FakeTime() hal.simulation.resumeTiming() + + [email protected](scope="function") +def hal(wpitime): + import hal.simulation + + yield + + # Reset the HAL handles + hal.simulation.resetGlobalHandles() + + # Reset the HAL data + hal.simulation.resetAllData() diff --git a/tests/test_distance_sensors.py b/tests/test_distance_sensors.py new file mode 100644 index 0000000..72dc2bf --- /dev/null +++ b/tests/test_distance_sensors.py @@ -0,0 +1,79 @@ +from robotpy_ext.common_drivers.distance_sensors import ( + SharpIR2Y0A02, + SharpIR2Y0A21, + SharpIR2Y0A41, +) + +from robotpy_ext.common_drivers.distance_sensors_sim import ( + SharpIR2Y0A02Sim, + SharpIR2Y0A21Sim, + SharpIR2Y0A41Sim, +) + +import pytest + + +def test_2Y0A02(hal): + sensor = SharpIR2Y0A02(0) + sim = SharpIR2Y0A02Sim(sensor) + + # 22 to 145cm + + # min + sim.setDistance(10) + assert sensor.getDistance() == pytest.approx(22.5) + + # max + sim.setDistance(200) + assert sensor.getDistance() == pytest.approx(145) + + # middle + sim.setDistance(50) + assert sensor.getDistance() == pytest.approx(50) + + sim.setDistance(100) + assert sensor.getDistance() == pytest.approx(100) + + +def test_2Y0A021(hal): + sensor = SharpIR2Y0A21(0) + sim = SharpIR2Y0A21Sim(sensor) + + # 10 to 80cm + + # min + sim.setDistance(5) + assert sensor.getDistance() == pytest.approx(10) + + # max + sim.setDistance(100) + assert sensor.getDistance() == pytest.approx(80) + + # middle + sim.setDistance(30) + assert sensor.getDistance() == pytest.approx(30) + + sim.setDistance(60) + assert sensor.getDistance() == pytest.approx(60) + + +def test_2Y0A041(hal): + sensor = SharpIR2Y0A41(0) + sim = SharpIR2Y0A41Sim(sensor) + + # 4.5 to 35 cm + + # min + sim.setDistance(2) + assert sensor.getDistance() == pytest.approx(4.5) + + # max + sim.setDistance(50) + assert sensor.getDistance() == pytest.approx(35) + + # middle + sim.setDistance(10) + assert sensor.getDistance() == pytest.approx(10) + + sim.setDistance(25) + assert sensor.getDistance() == pytest.approx(25)
Add simulation support for distance sensors Instead of just displaying an analog input, use a sim device.
0.0
2e627fe0ac923c42a652f49bd01f2fd255aa9f1d
[ "tests/test_distance_sensors.py::test_2Y0A02", "tests/test_distance_sensors.py::test_2Y0A021", "tests/test_distance_sensors.py::test_2Y0A041" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-03-11 14:07:50+00:00
bsd-3-clause
5,279
rohitsanj__doex-16
diff --git a/doex/latin_square.py b/doex/latin_square.py index ee3453b..7209dc5 100644 --- a/doex/latin_square.py +++ b/doex/latin_square.py @@ -65,7 +65,9 @@ class LatinSquare: self.dof_columns = n_cols - 1 self.dof_treatments = len(self.treatments) - 1 self.dof_total = N - 1 - self.dof_error = self.dof_total - (self.dof_rows + self.dof_columns + self.dof_treatments) + self.dof_error = self.dof_total - ( + self.dof_rows + self.dof_columns + self.dof_treatments + num_missing + ) # Calculate Mean Sum of Squares self.mss_rows = self.ss_rows / self.dof_rows diff --git a/doex/rcbd.py b/doex/rcbd.py index ff83010..f7ff63d 100644 --- a/doex/rcbd.py +++ b/doex/rcbd.py @@ -9,6 +9,11 @@ class RandomizedCompleteBlockDesign: n_treatments, n_blocks = self.data.shape + if hasattr(self, "num_missing"): + num_missing = self.num_missing + else: + num_missing = 0 + N = 0 for entry in self.data: N += len(entry) @@ -32,7 +37,7 @@ class RandomizedCompleteBlockDesign: self.dof_treatments = n_treatments - 1 self.dof_blocks = n_blocks - 1 self.dof_total = N - 1 - self.dof_error = self.dof_total - (self.dof_treatments + self.dof_blocks) + self.dof_error = self.dof_total - (self.dof_treatments + self.dof_blocks + num_missing) # Calculate Mean Sum of Squares self.mss_treatments = self.ss_treatments / self.dof_treatments @@ -101,11 +106,11 @@ class RandomizedCompleteBlockDesign_MissingValues(RandomizedCompleteBlockDesign) n_treatments, n_blocks = self.data.shape - num_missing = np.count_nonzero(np.isnan(self.data)) + self.num_missing = np.count_nonzero(np.isnan(self.data)) missing_locations = np.argwhere(np.isnan(self.data)) self.handle_missing(self.data, missing_locations) - print("Data after adjusting for {} missing value(s)".format(num_missing)) + print("Data after adjusting for {} missing value(s)".format(self.num_missing)) print(self.data) # Continue with RCBD analysis
rohitsanj/doex
1ad6b4d894ffc57a5e8fda66548d4806bdc314b9
diff --git a/doex/tests/test_latin_square.py b/doex/tests/test_latin_square.py index ae0d36d..4a2daa2 100644 --- a/doex/tests/test_latin_square.py +++ b/doex/tests/test_latin_square.py @@ -84,9 +84,9 @@ class TestLatinSquare: ) abs_tol = 10 ** -3 - assert math.isclose(exp.f_treatments, 15.0143, abs_tol=abs_tol) - assert math.isclose(exp.f_rows, 2.5857, abs_tol=abs_tol) - assert math.isclose(exp.f_columns, 1.3714, abs_tol=abs_tol) + assert math.isclose(exp.f_treatments, 12.5119, abs_tol=abs_tol) + assert math.isclose(exp.f_rows, 2.1548, abs_tol=abs_tol) + assert math.isclose(exp.f_columns, 1.1429, abs_tol=abs_tol) def test_latin_square_multiple_comparisons(self): exp = LatinSquare( diff --git a/doex/tests/test_rcbd.py b/doex/tests/test_rcbd.py index c6ceb4f..134fe49 100644 --- a/doex/tests/test_rcbd.py +++ b/doex/tests/test_rcbd.py @@ -48,16 +48,30 @@ class TestRCBDMissing: ] ) abs_tol = 10 ** -3 - assert math.isclose(exp.f_treatments, 0.8102, abs_tol=abs_tol) - assert math.isclose(exp.f_blocks, 2.2349, abs_tol=abs_tol) + assert math.isclose(exp.f_treatments, 0.7561, abs_tol=abs_tol) + assert math.isclose(exp.f_blocks, 2.0859, abs_tol=abs_tol) def test_rcbd_missing_2(self): exp = RandomizedCompleteBlockDesign_MissingValues( [[12, 14, 12], [10, float("nan"), 8], [float("nan"), 15, 10]] ) - assert math.isclose(exp.f_treatments, 9.5, abs_tol=10 ** -3) - assert math.isclose(exp.f_blocks, 15.5, abs_tol=10 ** -3) + assert math.isclose(exp.f_treatments, 4.7500, abs_tol=10 ** -3) + assert math.isclose(exp.f_blocks, 7.7500, abs_tol=10 ** -3) + + def test_rcbd_missing_3(self): + exp = RandomizedCompleteBlockDesign_MissingValues( + [ + [90.3, 89.2, 98.2, 93.9, 87.4, 97.9], + [92.5, 89.5, 90.6, float("nan"), 87, 95.8], + [85.5, 90.8, 89.6, 86.2, 88, 93.4], + [82.5, 89.5, 85.6, 87.4, 78.9, 90.7], + ] + ) + + abs_tol = 10 ** -3 + assert math.isclose(exp.f_treatments, 7.6241, abs_tol=abs_tol) + assert math.isclose(exp.f_blocks, 5.2181, abs_tol=abs_tol) def test_rcbd_missing_throw_error(self): with pytest.raises(Exception):
BUG: reduce degree of freedom of error with the number of missing values Reported by @nitin-kamath
0.0
1ad6b4d894ffc57a5e8fda66548d4806bdc314b9
[ "doex/tests/test_latin_square.py::TestLatinSquare::test_latin_square_missing_1", "doex/tests/test_rcbd.py::TestRCBDMissing::test_rcbd_missing_1", "doex/tests/test_rcbd.py::TestRCBDMissing::test_rcbd_missing_2", "doex/tests/test_rcbd.py::TestRCBDMissing::test_rcbd_missing_3" ]
[ "doex/tests/test_latin_square.py::TestLatinSquare::test_latin_square", "doex/tests/test_latin_square.py::TestLatinSquare::test_latin_square_raises_error_shape_mismatch", "doex/tests/test_latin_square.py::TestLatinSquare::test_latin_square_raises_error_treatments", "doex/tests/test_latin_square.py::TestLatinSquare::test_latin_square_multiple_comparisons", "doex/tests/test_rcbd.py::TestRCBD::test_rcbd_1", "doex/tests/test_rcbd.py::TestRCBD::test_rcbd_2", "doex/tests/test_rcbd.py::TestRCBDMissing::test_rcbd_missing_throw_error", "doex/tests/test_rcbd.py::TestRCBDMissing::test_rcbd_multiple_comparisons" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-20 09:53:01+00:00
bsd-3-clause
5,280
rolepoint__pyseeyou-14
diff --git a/pyseeyou/node_visitor.py b/pyseeyou/node_visitor.py index 6f80021..de6259e 100644 --- a/pyseeyou/node_visitor.py +++ b/pyseeyou/node_visitor.py @@ -168,7 +168,7 @@ class ICUNodeVisitor(NodeVisitor): def _get_key_value(self, items): key, value = None, None for item in items: - if not item: + if item is None: continue elif isinstance(item, str):
rolepoint/pyseeyou
6ee169d32d9449f12fc76032f6060bba687a9155
diff --git a/test/test_format.py b/test/test_format.py index 6951813..254071b 100644 --- a/test/test_format.py +++ b/test/test_format.py @@ -66,3 +66,11 @@ def test_format_tree(): plural = format_tree(ast, {'NUM_TICKETS': 43}, 'en') assert plural == '42 ticketerinos.' + + +def test_format_empty_string(): + template = '{number, plural, =1 {} other {#}}' + + result = format(template, {'number': 1}, 'en') + + assert result == '' diff --git a/test/test_locales.py b/test/test_locales.py index 40233b6..33d9d33 100644 --- a/test/test_locales.py +++ b/test/test_locales.py @@ -2,6 +2,7 @@ import pytest from pyseeyou.locales import get_parts_of_num, lookup_closest_locale, get_cardinal_category + def test_get_parts_of_num(): assert get_parts_of_num('1') == (1, 1, 0, 0, 0, 0) assert get_parts_of_num('1.0') == (1.0, 1, 1, 0, 0, 0) @@ -11,12 +12,14 @@ def test_get_parts_of_num(): assert get_parts_of_num('1.03') == (1.03, 1, 2, 2, 3, 3) assert get_parts_of_num('1.230') == (1.230, 1, 3, 2, 230, 23) + def test_lookup_closest_locale(): - dummy_dict = { 'uk': 'Ukrainian', 'fr': 'French' } + dummy_dict = {'uk': 'Ukrainian', 'fr': 'French'} assert lookup_closest_locale('fr_FR', dummy_dict) == 'fr' assert not lookup_closest_locale('be-BY', dummy_dict) + def test_get_cardinal_category(): assert get_cardinal_category('2.0', 'ar') == 'two' assert get_cardinal_category('13', 'ar') == 'many' diff --git a/test/test_node_visitor.py b/test/test_node_visitor.py index 998db42..1f98ffd 100644 --- a/test/test_node_visitor.py +++ b/test/test_node_visitor.py @@ -113,3 +113,10 @@ def test_msg_with_unicode_chars(): i = ICUNodeVisitor({}) assert i.visit(msg) == '☹' + + +def test_empty_msg(): + msg = ICUMessageFormat.parse('{number, plural, =1 {} other {#}}') + i = ICUNodeVisitor({'number': 1}) + + assert i.visit(msg) == ''
Using empty string in conditional formatting return None Empty strings are incorrectly formatted, example: `>> s = '{number, plural, =1 {} other {#}}'` `>> format(s, {'number': 1},' en')` `'None'` Expected result is ''
0.0
6ee169d32d9449f12fc76032f6060bba687a9155
[ "test/test_format.py::test_format_empty_string", "test/test_node_visitor.py::test_empty_msg" ]
[ "test/test_format.py::test_format", "test/test_format.py::test_format_tree", "test/test_locales.py::test_get_parts_of_num", "test/test_locales.py::test_lookup_closest_locale", "test/test_locales.py::test_get_cardinal_category", "test/test_node_visitor.py::test_process_select_statement", "test/test_node_visitor.py::test_use_other_statement_if_no_select_arg", "test/test_node_visitor.py::test_process_plural_statement", "test/test_node_visitor.py::test_plural_statement_with_offset", "test/test_node_visitor.py::test_plural_dict_uses_string", "test/test_node_visitor.py::test_plural_dict_with_decimals", "test/test_node_visitor.py::test_msg_with_basic_replace", "test/test_node_visitor.py::test_msg_with_unicode_chars" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-11-04 17:51:51+00:00
mit
5,281
rollbar__pyrollbar-448
diff --git a/rollbar/lib/transforms/shortener.py b/rollbar/lib/transforms/shortener.py index f039291..d3040a3 100644 --- a/rollbar/lib/transforms/shortener.py +++ b/rollbar/lib/transforms/shortener.py @@ -47,6 +47,8 @@ class ShortenerTransform(Transform): return self._repr.maxother + def _get_max_level(self): + return getattr(self._repr, 'maxlevel') def _shorten_sequence(self, obj, max_keys): _len = len(obj) if _len <= max_keys: @@ -77,14 +79,44 @@ class ShortenerTransform(Transform): return self._repr.repr(obj) + def traverse_obj(self, obj, level=1): + def seq_iter(o): + return o if isinstance(o, dict) else range(len(o)) + + for k in seq_iter(obj): + max_size = self._get_max_size(obj[k]) + if isinstance(obj[k], dict): + obj[k] = self._shorten_mapping(obj[k], max_size) + if level == self._get_max_level(): + del obj[k] + return + self.traverse_obj(obj[k], level + 1) + elif isinstance(obj[k], sequence_types): + obj[k] = self._shorten_sequence(obj[k], max_size) + if level == self._get_max_level(): + del obj[k] + return + self.traverse_obj(obj[k], level + 1) + else: + obj[k] = self._shorten(obj[k]) + return obj + def _shorten(self, val): max_size = self._get_max_size(val) if isinstance(val, dict): - return self._shorten_mapping(val, max_size) - if isinstance(val, (string_types, sequence_types)): + val = self._shorten_mapping(val, max_size) + return self.traverse_obj(val) + + if isinstance(val, string_types): return self._shorten_sequence(val, max_size) + if isinstance(val, sequence_types): + val = self._shorten_sequence(val, max_size) + if isinstance(val, string_types): + return val + return self.traverse_obj(val) + if isinstance(val, number_types): return self._shorten_basic(val, self._repr.maxlong)
rollbar/pyrollbar
dab08cde638cf619bb6d00a7e87f592b9d9603d1
diff --git a/rollbar/test/test_shortener_transform.py b/rollbar/test/test_shortener_transform.py index 55180c3..3dfe47d 100644 --- a/rollbar/test/test_shortener_transform.py +++ b/rollbar/test/test_shortener_transform.py @@ -37,7 +37,10 @@ class ShortenerTransformTest(BaseTest): 'frozenset': frozenset([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), 'array': array('l', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), 'deque': deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 15), - 'other': TestClassWithAVeryVeryVeryVeryVeryVeryVeryLongName() + 'other': TestClassWithAVeryVeryVeryVeryVeryVeryVeryLongName(), + 'list_max_level': [1, [2, [3, [4, ["good_5", ["bad_6", ["bad_7"]]]]]]], + 'dict_max_level': {1: 1, 2: {3: {4: {"level4": "good", "level5": {"toplevel": "ok", 6: {7: {}}}}}}}, + 'list_multi_level': [1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]] } def _assert_shortened(self, key, expected): @@ -45,14 +48,16 @@ class ShortenerTransformTest(BaseTest): result = transforms.transform(self.data, shortener) if key == 'dict': - self.assertEqual(expected, len(result)) + self.assertEqual(expected, len(result[key])) + elif key in ('list_max_level', 'dict_max_level', 'list_multi_level'): + self.assertEqual(expected, result[key]) else: # the repr output can vary between Python versions stripped_result_key = result[key].strip("'\"u") if key == 'other': self.assertIn(expected, stripped_result_key) - elif key != 'dict': + elif key not in ('dict', 'list_max_level', 'dict_max_level', 'list_multi_level'): self.assertEqual(expected, stripped_result_key) # make sure nothing else was shortened @@ -82,6 +87,18 @@ class ShortenerTransformTest(BaseTest): expected = '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]' self._assert_shortened('list', expected) + def test_shorten_list_max_level(self): + expected = [1, [2, [3, [4, ['good_5']]]]] + self._assert_shortened('list_max_level', expected) + + def test_shorten_list_multi_level(self): + expected = [1, '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]'] + self._assert_shortened('list_multi_level', expected) + + def test_shorten_dict_max_level(self): + expected = {1: 1, 2: {3: {4: {'level4': 'good', 'level5': {'toplevel': 'ok'}}}}} + self._assert_shortened('dict_max_level', expected) + def test_shorten_tuple(self): expected = '(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...)' self._assert_shortened('tuple', expected)
notifier isn't sending a "platform" param... should it be "python"?
0.0
dab08cde638cf619bb6d00a7e87f592b9d9603d1
[ "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_dict_max_level", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_list_max_level", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_list_multi_level" ]
[ "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_no_shorten", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_array", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_deque", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_frozenset", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_list", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_long", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_mapping", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_object", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_other", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_set", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_string", "rollbar/test/test_shortener_transform.py::ShortenerTransformTest::test_shorten_tuple" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2024-04-16 06:03:16+00:00
mit
5,282
rollbar__rollbar-agent-60
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7f35aa1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: Rollbar-Agent CI + +on: + push: + branches: [ master ] + tags: [ v* ] + pull_request: + branches: [ master ] + +jobs: + build: + runs-on: ubuntu-18.04 + strategy: + matrix: + python-version: [2.7, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9] + steps: + - uses: actions/checkout@v2 + + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install --upgrade --force-reinstall setuptools + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + + - name: Run tests + run: python setup.py test diff --git a/README.rst b/README.rst index fd1a6ae..d3dde4f 100644 --- a/README.rst +++ b/README.rst @@ -36,7 +36,7 @@ Requirements rollbar-agent requires: - A unix-like system (tested on Fedora and Ubuntu Linux and Mac OS X) -- Python 2.6+ +- Python 3 or 2.6+ - requests 0.13.1+ (will be installed by pip or setup.py, below) - a Rollbar_ account diff --git a/rollbar-agent b/rollbar-agent index c014b67..79d1f73 100755 --- a/rollbar-agent +++ b/rollbar-agent @@ -4,9 +4,7 @@ rollbar-agent: agent to monitor log files and send notices to Rollbar """ import ast import codecs -import ConfigParser import copy -import dbm import fnmatch import hashlib import json @@ -22,6 +20,16 @@ import sys import threading import time +try: + import configparser +except ImportError: + import ConfigParser as configparser + +try: + import dbm.ndbm as dbm +except ImportError: + import dbm + import requests log = logging.getLogger(__name__) @@ -51,11 +59,21 @@ LOG_LEVEL = { terminal_character_attribute_pattern = re.compile(r'\x1b\[[0-9;]*m') + +def iteritems(_dict): + return _dict.items() if not hasattr(_dict, 'iteritems') else _dict.iteritems() + + +def itervalues(_dict): + return _dict.values() if not hasattr(_dict, 'itervalues') else _dict.itervalues() + + def clean_line(app_config, line): if app_config.get('filter_chr_attr_sequences'): return terminal_character_attribute_pattern.sub("", line) return line + def parse_timestamp(format, s): try: ts = time.mktime(time.strptime(s, format)) @@ -140,7 +158,7 @@ def build_python_log_format_parser(format, datefmt): } regex_str = '^' + re.escape(format) + '$' - for key, val in known_keys.iteritems(): + for key, val in iteritems(known_keys): search = re.escape(key) replacement = "(?P<%s>%s)" % val regex_str = regex_str.replace(search, replacement) @@ -177,7 +195,7 @@ def datefmt_to_regex(datefmt): '%Z': r'[A-Z]{3}', # time zone name } - for key, val in replacements.iteritems(): + for key, val in iteritems(replacements): datefmt = datefmt.replace(key, val) # last: replace %% with % @@ -211,7 +229,11 @@ class Processor(object): # do immediate http post # in the future, will do this with batches and single separate thread - if isinstance(payload, basestring): + if sys.version_info[0] >= 3: + payload_is_str = isinstance(payload, str) + else: + payload_is_str = isinstance(payload, basestring) + if payload_is_str: payload = payload.encode('utf8') if options.dry_run: @@ -318,7 +340,7 @@ class LogFileProcessor(Processor): try: scrub_regexes.append(re.compile(pattern)) - except Exception, e: + except Exception as e: log.warning("Could not compile regex pattern: %s" % pattern) for line in fp: @@ -342,7 +364,7 @@ class LogFileProcessor(Processor): for regex in scrub_regexes: try: line = regex.sub('******', line) - except Exception, e: + except Exception as e: log.warning("Could not use regex %s on line %s" % (regex, line)) current_message['data'].append(line) @@ -429,7 +451,7 @@ class ScannerThread(threading.Thread): self.config = config self.apps = {} - for app_name, app_config in config.iteritems(): + for app_name, app_config in iteritems(config): if app_name.startswith('_'): continue self.apps[app_name] = { @@ -468,7 +490,7 @@ class ScannerThread(threading.Thread): self.save_state(state) try: - for app in self.apps.itervalues(): + for app in itervalues(self.apps): self.scan_app(app, apps_state) except: log.exception("Caught exception in ScannerThread.scan_all() loop") @@ -486,7 +508,8 @@ class ScannerThread(threading.Thread): # the 'c' flag will only create the file if it doesn't exist # https://docs.python.org/2/library/anydbm.html#anydbm.open return shelve.open(self.config['_global']['statefile'], - flag='n' if recreate else 'c') + flag='n' if recreate else 'c', + protocol=self.config['_global']['state_proto']) except dbm.error: log.error("Could not open statefile for writing. " "Perhaps the directory doesn't exist? " @@ -575,7 +598,7 @@ def main_loop(): # sleep until the thread is killed # have to sleep in a loop, instead of worker.join(), otherwise we'll never get the signals - while scanner.isAlive(): + while scanner.is_alive(): time.sleep(1) log.info("Shutdown complete") @@ -613,6 +636,7 @@ def parse_config(filename): defaults = { 'statefile': '/var/cache/rollbar-agent.state', + 'state_proto': '0', 'sleep_time': '10', 'endpoint': DEFAULT_ENDPOINT, 'timeout': str(DEFAULT_TIMEOUT), @@ -642,6 +666,7 @@ def parse_config(filename): return val.lower() == 'true' parsers = { + 'state_proto': to_int, 'sleep_time': to_int, 'timeout': to_int, 'ext_whitelist': to_list, @@ -655,7 +680,10 @@ def parse_config(filename): 'filter_chr_attr_sequences': to_bool, } - cp = ConfigParser.SafeConfigParser(defaults) + if sys.version_info >= (3, 2): + cp = configparser.ConfigParser(defaults) + else: + cp = configparser.SafeConfigParser(defaults) cp.read([filename]) config = {'_formats': {}} @@ -676,10 +704,10 @@ def parse_config(filename): format = {'name': format_name} format_type = cp.get(section_name, 'type') - format_spec = cp.get(section_name, 'format', True) + format_spec = cp.get(section_name, 'format', raw=True) try: - format_datefmt = cp.get(section_name, 'datefmt', True) - except ConfigParser.NoOptionError: + format_datefmt = cp.get(section_name, 'datefmt', raw=True) + except configparser.NoOptionError: format_datefmt = DEFAULT_DATEFMT if format_type != 'python': @@ -693,7 +721,7 @@ def parse_config(filename): global_config = cp.defaults() config['_global'] = {} - for option_name, raw_value in global_config.iteritems(): + for option_name, raw_value in iteritems(global_config): if option_name in parsers: value = parsers[option_name](raw_value) else: @@ -706,17 +734,17 @@ def parse_config(filename): def validate_config(config): errors = [] required_vars = ['params.access_token', 'targets'] - for app_name, app_config in config.iteritems(): + for app_name, app_config in iteritems(config): if app_name.startswith('_'): continue for var_name in required_vars: if not app_config.get('params.access_token'): errors.append("app:%s is missing required var %s" % (app_name, var_name)) if errors: - print "CONFIGURATION ERRORS" + print("CONFIGURATION ERRORS") for error in errors: - print error - print + print(error) + print() sys.exit(1) diff --git a/rollbar-agent.conf b/rollbar-agent.conf index 9d62602..e9ad861 100644 --- a/rollbar-agent.conf +++ b/rollbar-agent.conf @@ -1,6 +1,14 @@ [DEFAULT] # global option - where the state is kept. statefile = /var/cache/rollbar-agent.state + +# state protocol version (based on pickle protocols) +# +# defaults to 0 for backward compatibility with state files generated by Python2 +# note that for different versions of Python3 use different default values, +# however you don't need to change the default 0 +state_proto = 0 + # target time how long to sleep between runs (in seconds). will never be longer than this. sleep_time = 10
rollbar/rollbar-agent
81bdf73de0f8b995a69915eff6796984e539879b
diff --git a/test.py b/test.py index b9fa076..a34217f 100644 --- a/test.py +++ b/test.py @@ -1,7 +1,15 @@ +import sys +import types import unittest -import imp -rollbar_agent = imp.load_source('rollbar-agent', './rollbar-agent') +if sys.version_info >= (3, 4): + from importlib.machinery import SourceFileLoader + loader = SourceFileLoader('rollbar-agent', './rollbar-agent') + rollbar_agent = types.ModuleType(loader.name) + loader.exec_module(rollbar_agent) +else: + import imp + rollbar_agent = imp.load_source('rollbar-agent', './rollbar-agent') class FakeScanner:
Support running agent on Python 3 The rollbar-agent does not run on Python 3 (see https://github.com/rollbar/rollbar-agent/issues/53). Python 2 has been officially sunsetted and is no longer supported, does not receive security patches, etc (see https://www.python.org/doc/sunset-python-2/)
0.0
81bdf73de0f8b995a69915eff6796984e539879b
[ "test.py::TestDefaultMessageStartParserUsage::test_process_log_debug_with_format_name", "test.py::TestDefaultMessageStartParserUsage::test_process_log_debug_without_format_name" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-05-25 14:02:59+00:00
mit
5,283
ronaldoussoren__macholib-38
diff --git a/macholib/MachO.py b/macholib/MachO.py index 3db9520..d4d85f1 100644 --- a/macholib/MachO.py +++ b/macholib/MachO.py @@ -92,7 +92,10 @@ def lc_str_value(offset, cmd_info): class MachO(object): """ - Provides reading/writing the Mach-O header of a specific existing file + Provides reading/writing the Mach-O header of a specific existing file. + + If allow_unknown_load_commands is True, allows unknown load commands. + Otherwise, raises ValueError if the file contains an unknown load command. """ # filename - the original filename of this mach-o @@ -104,7 +107,7 @@ class MachO(object): # low_offset - essentially, the maximum mach-o header size # id_cmd - the index of my id command, or None - def __init__(self, filename): + def __init__(self, filename, allow_unknown_load_commands=False): # supports the ObjectGraph protocol self.graphident = filename @@ -114,6 +117,7 @@ class MachO(object): # initialized by load self.fat = None self.headers = [] + self.allow_unknown_load_commands = allow_unknown_load_commands with open(filename, "rb") as fp: self.load(fp) @@ -165,7 +169,7 @@ class MachO(object): magic, hdr, endian = MH_CIGAM_64, mach_header_64, "<" else: raise ValueError("Unknown Mach-O header: 0x%08x in %r" % (header, fh)) - hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian) + hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian, self.allow_unknown_load_commands) self.headers.append(hdr) def write(self, f): @@ -175,7 +179,10 @@ class MachO(object): class MachOHeader(object): """ - Provides reading/writing the Mach-O header of a specific existing file + Provides reading/writing the Mach-O header of a specific existing file. + + If allow_unknown_load_commands is True, allows unknown load commands. + Otherwise, raises ValueError if the file contains an unknown load command. """ # filename - the original filename of this mach-o @@ -187,7 +194,7 @@ class MachOHeader(object): # low_offset - essentially, the maximum mach-o header size # id_cmd - the index of my id command, or None - def __init__(self, parent, fh, offset, size, magic, hdr, endian): + def __init__(self, parent, fh, offset, size, magic, hdr, endian, allow_unknown_load_commands=False): self.MH_MAGIC = magic self.mach_header = hdr @@ -206,6 +213,8 @@ class MachOHeader(object): self.filetype = None self.headers = [] + self.allow_unknown_load_commands = allow_unknown_load_commands + self.load(fh) def __repr__(self): @@ -242,7 +251,16 @@ class MachOHeader(object): # read the specific command klass = LC_REGISTRY.get(cmd_load.cmd, None) if klass is None: - raise ValueError("Unknown load command: %d" % (cmd_load.cmd,)) + if not self.allow_unknown_load_commands: + raise ValueError("Unknown load command: %d" % (cmd_load.cmd,)) + # No load command in the registry, so append the load command itself + # instead of trying to deserialize the data after the header. + data_size = cmd_load.cmdsize - sizeof(load_command) + cmd_data = fh.read(data_size) + cmd.append((cmd_load, cmd_load, cmd_data)) + read_bytes += cmd_load.cmdsize + continue + cmd_cmd = klass.from_fileobj(fh, **kw) if cmd_load.cmd == LC_ID_DYLIB:
ronaldoussoren/macholib
53d9c7a4056af795990a8db2af71e17f05f59460
diff --git a/macholib_tests/test_MachO.py b/macholib_tests/test_MachO.py index c32ea70..ed3d808 100644 --- a/macholib_tests/test_MachO.py +++ b/macholib_tests/test_MachO.py @@ -1,17 +1,92 @@ +import contextlib +import os +import struct import sys +import tempfile +import uuid -from macholib import MachO +from macholib import MachO, mach_o if sys.version_info[:2] <= (2, 6): import unittest2 as unittest else: import unittest [email protected] +def temporary_macho_file(load_commands): + struct_mach_header_64_format = '>IIIIIIII' + cpu_type_arm64 = 0x100000C + cpu_subtype_arm_all = 0x0 + mh_filetype_execute = 0x2 + ncmds = len(load_commands) + sizeofcmds = sum([len(lc) for lc in load_commands]) + mach_header = struct.pack(struct_mach_header_64_format, mach_o.MH_MAGIC_64, + cpu_type_arm64, cpu_subtype_arm_all, + mh_filetype_execute, ncmds, sizeofcmds, 0, 0) + with tempfile.NamedTemporaryFile(delete=False) as macho_file: + macho_file.write(mach_header) + for lc in load_commands: + macho_file.write(lc) + # Close the file so it can be re-opened on Windows. + macho_file.close() + yield macho_file.name + os.unlink(macho_file.name) + + +def lc_uuid(macho_uuid): + lc_uuid_format = '>II16s' + lc_uuid_size = struct.calcsize(lc_uuid_format) + return struct.pack(lc_uuid_format, mach_o.LC_UUID, lc_uuid_size, macho_uuid.bytes) + + +def lc_unknown(): + lc_unknown_format = '>III' + lc_unknown = 0x707A11ED # Made-up load command. Hopefully never used. + lc_unknown_size = struct.calcsize(lc_unknown_format) + lc_unknown_value = 42 # Random value + return struct.pack(lc_unknown_format, lc_unknown, lc_unknown_size, lc_unknown_value) + class TestMachO(unittest.TestCase): - @unittest.expectedFailure - def test_missing(self): - self.fail("tests are missing") + def test_known_load_command_should_succeed(self): + macho_uuid = uuid.UUID('6894C0AE-C8B7-4E0B-A529-30BBEBA3703B') + with temporary_macho_file([lc_uuid(macho_uuid)]) as macho_filename: + macho = MachO.MachO(macho_filename, allow_unknown_load_commands=True) + self.assertEqual(len(macho.headers), 1) + self.assertEqual(len(macho.headers[0].commands), 1) + load_command, command, _ = macho.headers[0].commands[0] + self.assertEqual(load_command.cmd, mach_o.LC_UUID) + self.assertEqual(uuid.UUID(bytes=command.uuid), macho_uuid) + + def test_unknown_load_command_should_fail(self): + with temporary_macho_file([lc_unknown()]) as macho_filename: + with self.assertRaises(ValueError) as assert_context: + MachO.MachO(macho_filename) + + def test_unknown_load_command_should_succeed_with_flag(self): + with temporary_macho_file([lc_unknown()]) as macho_filename: + macho = MachO.MachO(macho_filename, allow_unknown_load_commands=True) + self.assertEqual(len(macho.headers), 1) + self.assertEqual(len(macho.headers[0].commands), 1) + load_command, command, data = macho.headers[0].commands[0] + self.assertEqual(load_command.cmd, 0x707A11ED) + self.assertIsInstance(command, mach_o.load_command) + self.assertEqual(struct.unpack('>I', data), (42,)) + + + def test_mix_of_known_and_unknown_load_commands_should_allow_unknown_with_flag(self): + macho_uuid = uuid.UUID('6894C0AE-C8B7-4E0B-A529-30BBEBA3703B') + with temporary_macho_file([lc_unknown(), lc_uuid(macho_uuid)]) as macho_filename: + macho = MachO.MachO(macho_filename, allow_unknown_load_commands=True) + self.assertEqual(len(macho.headers), 1) + self.assertEqual(len(macho.headers[0].commands), 2) + load_command, command, data = macho.headers[0].commands[0] + self.assertEqual(load_command.cmd, 0x707A11ED) + self.assertIsInstance(command, mach_o.load_command) + self.assertEqual(struct.unpack('>I', data), (42,)) + load_command, command, _ = macho.headers[0].commands[1] + self.assertEqual(load_command.cmd, mach_o.LC_UUID) + self.assertEqual(uuid.UUID(bytes=command.uuid), macho_uuid) if __name__ == "__main__":
Feature: Option for ignoring unknown load commands **[Original report](https://bitbucket.org/ronaldoussoren/macholib/issue/26) by Mikkel Kamstrup Erlandsen (Bitbucket: [kamikkel](https://bitbucket.org/kamikkel), GitHub: [kamikkel](https://github.com/kamikkel)).** ---------------------------------------- First of all - thanks for a great library! <3 We were hit by the unknown load commands 0x31 and 0x32 that were just recently implemented in macholib. Updating fixed this, of course, but it would be nice to guard against similar issues with an option for the parser to just skip (or print a warning on) unknown load commands. Background: We use macholib for some simple validation of user-submitted iOS apps. We would like to be able to process newly built apps without redeployment of our toolchain (just recording any warnings it may produce) - disregarding what Apple may come up with in the future.
0.0
53d9c7a4056af795990a8db2af71e17f05f59460
[ "macholib_tests/test_MachO.py::TestMachO::test_known_load_command_should_succeed", "macholib_tests/test_MachO.py::TestMachO::test_mix_of_known_and_unknown_load_commands_should_allow_unknown_with_flag", "macholib_tests/test_MachO.py::TestMachO::test_unknown_load_command_should_succeed_with_flag" ]
[ "macholib_tests/test_MachO.py::TestMachO::test_unknown_load_command_should_fail" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-03-03 20:45:23+00:00
mit
5,284
root-11__graph-theory-8
diff --git a/graph/__init__.py b/graph/__init__.py index cc3bb35..5ffc7a0 100644 --- a/graph/__init__.py +++ b/graph/__init__.py @@ -298,19 +298,20 @@ class BasicGraph(object): @lru_cache(maxsize=128) def is_connected(self, n1, n2): """ helper determining if two nodes are connected using BFS. """ - q = [n1] - visited = set() - while q: - n = q.pop(0) - if n not in visited: - visited.add(n) - for c in self._edges[n]: - if c == n2: - return True # <-- Exit if connected. - if c in visited: - continue - else: - q.append(c) + if n1 in self._edges: + q = [n1] + visited = set() + while q: + n = q.pop(0) + if n not in visited: + visited.add(n) + for c in self._edges[n]: + if c == n2: + return True # <-- Exit if connected. + if c in visited: + continue + else: + q.append(c) return False # <-- Exit if not connected.
root-11/graph-theory
c46ebd333f4996b48aebaba325076e55df053e43
diff --git a/tests/test_basics.py b/tests/test_basics.py index bc743c0..cd10dae 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -270,4 +270,24 @@ def test_is_not_cyclic(): def test_is_really_cyclic(): g = Graph(from_list=[(1, 1, 1), (2, 2, 1)]) # two loops onto themselves. - assert g.has_cycles() \ No newline at end of file + assert g.has_cycles() + + +def test_no_edge_connected(): + g = Graph() + g.add_node(4) + g.add_node(5) + assert g.is_connected(4, 5) == False + + +def test_edge_connected(): + g = Graph() + g.add_edge(4, 5) + assert g.is_connected(4, 5) == True + + +def test_edge_not_connected(): + g = Graph() + g.add_edge(3, 4) + g.add_edge(5, 4) + assert g.is_connected(3, 5) == False
is_connected errors if n1 has no edges It gives a key error at https://github.com/root-11/graph-theory/blob/c46ebd333f4996b48aebaba325076e55df053e43/graph/__init__.py#L307
0.0
c46ebd333f4996b48aebaba325076e55df053e43
[ "tests/test_basics.py::test_no_edge_connected" ]
[ "tests/test_basics.py::test_to_from_dict", "tests/test_basics.py::test_setitem", "tests/test_basics.py::test_add_node_attr", "tests/test_basics.py::test_add_edge_attr", "tests/test_basics.py::test_to_list", "tests/test_basics.py::test_bidirectional_link", "tests/test_basics.py::test_edges_with_node", "tests/test_basics.py::test_nodes_from_node", "tests/test_basics.py::test01", "tests/test_basics.py::test02", "tests/test_basics.py::test03", "tests/test_basics.py::test_subgraph", "tests/test_basics.py::test_copy", "tests/test_basics.py::test_errors", "tests/test_basics.py::test_delitem", "tests/test_basics.py::test_is_partite", "tests/test_basics.py::test_is_cyclic", "tests/test_basics.py::test_is_not_cyclic", "tests/test_basics.py::test_is_really_cyclic", "tests/test_basics.py::test_edge_connected", "tests/test_basics.py::test_edge_not_connected" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-09-21 20:26:55+00:00
mit
5,285
rorodata__firefly-12
diff --git a/firefly/main.py b/firefly/main.py index bb06d97..37eb583 100644 --- a/firefly/main.py +++ b/firefly/main.py @@ -7,7 +7,7 @@ from .server import FireflyServer def parse_args(): p = argparse.ArgumentParser() p.add_argument("-b", "--bind", dest="ADDRESS", default="127.0.0.1:8000") - p.add_argument("function", help="function to serve") + p.add_argument("functions", nargs='+', help="functions to serve") return p.parse_args() def load_function(function_spec): @@ -17,7 +17,14 @@ def load_function(function_spec): mod_name, func_name = function_spec.rsplit(".", 1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) - return func + return (func_name, func) + +def load_functions(function_specs): + return [load_function(function_spec) for function_spec in function_specs] + +def add_routes(app, functions): + for name, function in functions: + app.add_route('/'+name, function) def main(): # ensure current directory is added to sys.path @@ -25,10 +32,10 @@ def main(): sys.path.insert(0, "") args = parse_args() - function = load_function(args.function) + functions = load_functions(args.functions) app = Firefly() - app.add_route("/", function) + add_routes(app, functions) server = FireflyServer(app, {"bind": args.ADDRESS}) server.run()
rorodata/firefly
8f85f769b450eb45d9b4e3a338e988a042bf7459
diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..7ecfbf2 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,8 @@ +import os +from firefly.main import load_function + +def test_load_functions(): + os.path.exists2 = os.path.exists + name, func = load_function("os.path.exists2") + assert name == "exists2" + assert func == os.path.exists
Allow firefly to support multiple functions It should take multiple functions as command line arguments and expose all of them. ``` $ firefly myfile.square myfile.cube ``` And use: ``` $ curl -d '{"x": 5}' http://localhost:8000/square 25 $ curl -d '{"x": 5}' http://localhost:8000/cube 125 ```
0.0
8f85f769b450eb45d9b4e3a338e988a042bf7459
[ "tests/test_main.py::test_load_functions" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2017-06-15 06:05:45+00:00
apache-2.0
5,286
rorodata__firefly-13
diff --git a/firefly/app.py b/firefly/app.py index c317648..d3c0da8 100644 --- a/firefly/app.py +++ b/firefly/app.py @@ -3,13 +3,28 @@ from webob.exc import HTTPNotFound import json from .validator import validate_args, ValidationError from .utils import json_encode +from .version import __version__ class Firefly(object): def __init__(self): self.mapping = {} + self.add_route('/', self.generate_index,internal=True) - def add_route(self, path, function, **kwargs): - self.mapping[path] = FireflyFunction(function, **kwargs) + def add_route(self, path, function, function_name=None, **kwargs): + self.mapping[path] = FireflyFunction(function, function_name, **kwargs) + + def generate_function_list(self): + return {f.name: {"path": path, "doc": f.doc} + for path, f in self.mapping.items() + if f.options.get("internal") != True} + + def generate_index(self): + help_dict = { + "app": "firefly", + "version": __version__, + "functions": self.generate_function_list() + } + return help_dict def __call__(self, environ, start_response): request = Request(environ) @@ -25,10 +40,16 @@ class Firefly(object): class FireflyFunction(object): - def __init__(self, function, **kwargs): + def __init__(self, function, function_name=None, **options): self.function = function + self.options = options + self.name = function_name or function.__name__ + self.doc = function.__doc__ or "" def __call__(self, request): + if self.options.get("internal", False): + return self.make_response(self.function()) + kwargs = self.get_inputs(request) try: validate_args(self.function, kwargs) diff --git a/firefly/main.py b/firefly/main.py index 37eb583..dd4a4fb 100644 --- a/firefly/main.py +++ b/firefly/main.py @@ -24,7 +24,7 @@ def load_functions(function_specs): def add_routes(app, functions): for name, function in functions: - app.add_route('/'+name, function) + app.add_route('/'+name, function, name) def main(): # ensure current directory is added to sys.path
rorodata/firefly
6f199213a35bf87d17c594c023bf6ed4360f70a0
diff --git a/tests/test_app.py b/tests/test_app.py index edad1b9..183c914 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -1,13 +1,41 @@ from webob import Request, Response -from firefly.app import FireflyFunction +from firefly.app import Firefly, FireflyFunction def square(a): + '''Computes square''' return a**2 +class TestFirefly: + def test_generate_function_list(self): + firefly = Firefly() + assert firefly.generate_function_list() == {} + + firefly.add_route("/square", square, "square") + returned_dict = { + "square": { + "path": "/square", + "doc": "Computes square" + } + } + assert firefly.generate_function_list() == returned_dict + + def test_generate_function_list_for_func_name(self): + firefly = Firefly() + firefly.add_route("/sq2", square, "sq") + returned_dict = { + "sq": { + "path": "/sq2", + "doc": "Computes square" + } + } + assert firefly.generate_function_list() == returned_dict + + + class TestFireflyFunction: def test_call(self): func = FireflyFunction(square) - request = Request.blank("/", POST='{"a": 3}') + request = Request.blank("/square", POST='{"a": 3}') response = func(request) assert response.status == '200 OK' assert response.text == '9'
Add the ability to find all the available functions served by a firefly service The user should be able to find the functions available in a firefly service. Right now a server supports only one function, but that is going to change soon. So, we need to identify the right way to expose the list of functions. It could either be on `/` or some other endpoint like `/_list`. Look at the other RPC implementations and see how they work. We don't have to follow them, but that would give a good idea. It would be better to provide the docstring and argument names along with the function listing. Please discuss the plan here before implementing.
0.0
6f199213a35bf87d17c594c023bf6ed4360f70a0
[ "tests/test_app.py::TestFirefly::test_generate_function_list", "tests/test_app.py::TestFirefly::test_generate_function_list_for_func_name" ]
[ "tests/test_app.py::TestFireflyFunction::test_call" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-06-15 09:17:43+00:00
apache-2.0
5,287
ros-infrastructure__rosdep-721
diff --git a/src/rosdep2/main.py b/src/rosdep2/main.py index 1b6b816..764ddad 100644 --- a/src/rosdep2/main.py +++ b/src/rosdep2/main.py @@ -402,7 +402,7 @@ def _rosdep_main(args): if 'ROS_PYTHON_VERSION' not in os.environ and 'ROS_DISTRO' in os.environ: # Set python version to version used by ROS distro - python_versions = MetaDatabase().get('ROS_PYTHON_VERSION') + python_versions = MetaDatabase().get('ROS_PYTHON_VERSION', default=[]) if os.environ['ROS_DISTRO'] in python_versions: os.environ['ROS_PYTHON_VERSION'] = str(python_versions[os.environ['ROS_DISTRO']]) diff --git a/src/rosdep2/meta.py b/src/rosdep2/meta.py index 29bd317..b8cd900 100644 --- a/src/rosdep2/meta.py +++ b/src/rosdep2/meta.py @@ -102,7 +102,7 @@ class MetaDatabase: write_cache_file(self._cache_dir, category, wrapper) self._loaded[category] = wrapper - def get(self, category): + def get(self, category, default=None): """Return metadata in the cache, or None if there is no cache entry.""" if category not in self._loaded: self._load_from_cache(category, self._cache_dir) @@ -110,6 +110,8 @@ class MetaDatabase: if category in self._loaded: return self._loaded[category].data + return default + def _load_from_cache(self, category, cache_dir): filename = compute_filename_hash(category) + PICKLE_CACHE_EXT try:
ros-infrastructure/rosdep
d812436fd7c0716280818f5ca8ae7d2a7166ae3f
diff --git a/test/test_metadata.py b/test/test_metadata.py index 0caf844..424a5ac 100644 --- a/test/test_metadata.py +++ b/test/test_metadata.py @@ -65,6 +65,14 @@ def test_metadatabase_get_none(): assert db.get('fruit') is None +def test_metadatabase_get_default(): + with TemporaryDirectory() as tmpdir: + db = MetaDatabase(cache_dir=tmpdir) + assert db.get('fruit', default='foo') == 'foo' + db.set('fruit', 'tomato') + assert db.get('fruit', default='foo') != 'foo' + + def test_metadatabase_get_mutate_get(): with TemporaryDirectory() as tmpdir: db = MetaDatabase(cache_dir=tmpdir)
`rosdep resolve` on version 0.16.2 yields `TypeError` I installed `rosdep` from PyPI. `rosdep resolve` yields the failing the stack trace below: ``` acarrillo ~ $ rosdep resolve ERROR: Rosdep experienced an error: argument of type 'NoneType' is not iterable Please go to the rosdep page [1] and file a bug report with the stack trace below. [1] : http://www.ros.org/wiki/rosdep rosdep version: 0.16.2 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/rosdep2/main.py", line 144, in rosdep_main exit_code = _rosdep_main(args) File "/usr/local/lib/python2.7/dist-packages/rosdep2/main.py", line 406, in _rosdep_main if os.environ['ROS_DISTRO'] in python_versions: TypeError: argument of type 'NoneType' is not iterable ```
0.0
d812436fd7c0716280818f5ca8ae7d2a7166ae3f
[ "test/test_metadata.py::test_metadatabase_get_default" ]
[ "test/test_metadata.py::test_metadatabase_set_get", "test/test_metadata.py::test_metadatabase_get_none", "test/test_metadata.py::test_metadatabase_get_mutate_get", "test/test_metadata.py::test_metadatabase_set_set_get", "test/test_metadata.py::test_metadatabase_set_load_from_disk_get" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-10-18 23:44:25+00:00
bsd-3-clause
5,288
ros-infrastructure__rosdistro-89
diff --git a/src/rosdistro/manifest_provider/git.py b/src/rosdistro/manifest_provider/git.py index 8951983..3eca46f 100644 --- a/src/rosdistro/manifest_provider/git.py +++ b/src/rosdistro/manifest_provider/git.py @@ -65,14 +65,16 @@ def git_source_manifest_provider(repo): cache = { '_ref': result['output'] } # Find package.xml files inside the repo. - for package_path in catkin_pkg.packages.find_package_paths(git_repo_path): + for package_path in find_package_paths(git_repo_path): + if package_path == '.': + package_path = '' with open(os.path.join(git_repo_path, package_path, 'package.xml'), 'r') as f: package_xml = f.read() try: name = parse_package_string(package_xml).name except InvalidPackage: raise RuntimeError('Unable to parse package.xml file found in %s' % repo.url) - cache[name] = [ path[len(git_repo_path)+1:], package_xml ] + cache[name] = [ package_path, package_xml ] except Exception as e: raise RuntimeError('Unable to fetch source package.xml files: %s' % e) diff --git a/src/rosdistro/manifest_provider/github.py b/src/rosdistro/manifest_provider/github.py index 7960c3d..6305d47 100644 --- a/src/rosdistro/manifest_provider/github.py +++ b/src/rosdistro/manifest_provider/github.py @@ -83,7 +83,7 @@ def github_source_manifest_provider(repo): authheader = 'Basic %s' % base64.b64encode('%s:%s' % (GITHUB_USER, GITHUB_PASSWORD)) req.add_header('Authorization', authheader) try: - tree_json = json.load(urlopen(req)) + tree_json = json.loads(urlopen(req).read().decode('utf-8')) logger.debug('- load repo tree from %s' % tree_url) except URLError as e: raise RuntimeError('Unable to fetch JSON tree from %s: %s' % (tree_url, e)) @@ -107,14 +107,14 @@ def github_source_manifest_provider(repo): return False if parent == '': return True - package_xml_paths = filter(package_xml_in_parent, package_xml_paths) + package_xml_paths = list(filter(package_xml_in_parent, package_xml_paths)) cache = { '_ref': tree_json['sha'] } for package_xml_path in package_xml_paths: url = 'https://raw.githubusercontent.com/%s/%s/%s' % \ (path, cache['_ref'], package_xml_path + '/package.xml' if package_xml_path else 'package.xml') logger.debug('- load package.xml from %s' % url) - package_xml = urlopen(url).read() + package_xml = urlopen(url).read().decode('utf-8') name = parse_package_string(package_xml).name cache[name] = [ package_xml_path, package_xml ]
ros-infrastructure/rosdistro
2bb8505ec0bdfcc57d7b2a1033235eb3ce21f9f2
diff --git a/test/test_manifest_providers.py b/test/test_manifest_providers.py index 73c3336..3bce35e 100644 --- a/test/test_manifest_providers.py +++ b/test/test_manifest_providers.py @@ -4,15 +4,16 @@ import os from rosdistro.manifest_provider.bitbucket import bitbucket_manifest_provider from rosdistro.manifest_provider.cache import CachedManifestProvider, sanitize_xml -from rosdistro.manifest_provider.git import git_manifest_provider -from rosdistro.manifest_provider.github import github_manifest_provider +from rosdistro.manifest_provider.git import git_manifest_provider, git_source_manifest_provider +from rosdistro.manifest_provider.github import github_manifest_provider, github_source_manifest_provider from rosdistro.release_repository_specification import ReleaseRepositorySpecification +from rosdistro.source_repository_specification import SourceRepositorySpecification import rosdistro.vcs def test_bitbucket(): - assert '</package>' in bitbucket_manifest_provider('indigo', _rospeex_repo(), 'rospeex_msgs') + assert '</package>' in bitbucket_manifest_provider('indigo', _rospeex_release_repo(), 'rospeex_msgs') def test_cached(): @@ -21,21 +22,57 @@ def test_cached(): self.release_package_xmls = {} dc = FakeDistributionCache() cache = CachedManifestProvider(dc, [github_manifest_provider]) - assert '</package>' in cache('kinetic', _genmsg_repo(), 'genmsg') + assert '</package>' in cache('kinetic', _genmsg_release_repo(), 'genmsg') def test_git(): - assert '</package>' in git_manifest_provider('kinetic', _genmsg_repo(), 'genmsg') + assert '</package>' in git_manifest_provider('kinetic', _genmsg_release_repo(), 'genmsg') def test_git_legacy(): rosdistro.vcs.Git._client_version = '1.7.0' - assert '</package>' in git_manifest_provider('kinetic', _genmsg_repo(), 'genmsg') + assert '</package>' in git_manifest_provider('kinetic', _genmsg_release_repo(), 'genmsg') rosdistro.vcs.Git._client_version = None def test_github(): - assert '</package>' in github_manifest_provider('kinetic', _genmsg_repo(), 'genmsg') + assert '</package>' in github_manifest_provider('kinetic', _genmsg_release_repo(), 'genmsg') + + +def test_git_source(): + repo_cache = git_source_manifest_provider(_genmsg_source_repo()) + + # This hash corresponds to the 0.5.7 tag. + assert repo_cache['_ref'] == '81b66fe5eb00043c43894ddeee07e738d9b9712f' + + package_path, package_xml = repo_cache['genmsg'] + assert '' == package_path + assert '<version>0.5.7</version>' in package_xml + + +def test_github_source(): + repo_cache = github_source_manifest_provider(_genmsg_source_repo()) + + # This hash corresponds to the 0.5.7 tag. + assert repo_cache['_ref'] == '81b66fe5eb00043c43894ddeee07e738d9b9712f' + + package_path, package_xml = repo_cache['genmsg'] + assert '' == package_path + assert '<version>0.5.7</version>' in package_xml + + +def test_git_source_multi(): + repo_cache = git_source_manifest_provider(_ros_source_repo()) + assert repo_cache['_ref'] + package_path, package_xml = repo_cache['roslib'] + assert package_path == 'core/roslib' + + +def test_github_source_multi(): + repo_cache = github_source_manifest_provider(_ros_source_repo()) + assert repo_cache['_ref'] + package_path, package_xml = repo_cache['roslib'] + assert package_path == 'core/roslib' def test_sanitize(): @@ -46,15 +83,26 @@ def test_sanitize(): assert '<a>français</a>' in sanitize_xml('<a> français </a>') -def _genmsg_repo(): +def _genmsg_release_repo(): return ReleaseRepositorySpecification('genmsg', { 'url': 'https://github.com/ros-gbp/genmsg-release.git', 'tags': {'release': 'release/kinetic/{package}/{version}'}, 'version': '0.5.7-1' }) +def _genmsg_source_repo(): + return SourceRepositorySpecification('genmsg', { + 'url': 'https://github.com/ros/genmsg.git', + 'version': '0.5.7' + }) + +def _ros_source_repo(): + return SourceRepositorySpecification('ros', { + 'url': 'https://github.com/ros/ros.git', + 'version': 'kinetic-devel' + }) -def _rospeex_repo(): +def _rospeex_release_repo(): return ReleaseRepositorySpecification('rospeex', { 'packages': ['rospeex', 'rospeex_msgs'], 'tags': {'release': 'release/indigo/{package}/{version}'},
KeyError with SourceDependencyWalker Seeing these in our builds since updating to the current source master: ``` File "env/local/lib/python2.7/site-packages/rosinstall_generator/distro.py", line 87, in get_recursive_dependencies dependencies |= walker.get_recursive_depends(pkg_name, ['buildtool', 'build', 'run', 'test'], ros_packages_only=True, ignore_pkgs=dependencies | excludes, limit_depth=limit_depth) File "env/local/lib/python2.7/site-packages/rosdistro/dependency_walker.py", line 78, in get_recursive_depends deps = self.get_depends(next_pkg_to_check, depend_type, ros_packages_only=ros_packages_only) File "env/local/lib/python2.7/site-packages/rosdistro/dependency_walker.py", line 61, in get_depends deps = self._get_dependencies(pkg_name, depend_type) File "env/local/lib/python2.7/site-packages/rosdistro/dependency_walker.py", line 120, in _get_dependencies pkg = self._get_package(pkg_name) File "env/local/lib/python2.7/site-packages/rosdistro/dependency_walker.py", line 133, in _get_package repo = self._distribution_instance.repositories[self._distribution_instance.source_packages[pkg_name].repository_name].source_repository KeyError: 'package_which_definitely_does_exist' ``` @dirk-thomas I should have a patch for you shortly; just going through the delta between https://github.com/mikepurvis/rosdistro-1/releases/tag/0.4.7%2Bmpu1 and the current master to figure out where things went wrong. (To clarify, there's no regression from current functionality, since `SourceDependencyWalker` is only used with a rosdistro which has a source cache...)
0.0
2bb8505ec0bdfcc57d7b2a1033235eb3ce21f9f2
[ "test/test_manifest_providers.py::test_git_source", "test/test_manifest_providers.py::test_github_source", "test/test_manifest_providers.py::test_git_source_multi", "test/test_manifest_providers.py::test_github_source_multi" ]
[ "test/test_manifest_providers.py::test_bitbucket", "test/test_manifest_providers.py::test_cached", "test/test_manifest_providers.py::test_git", "test/test_manifest_providers.py::test_git_legacy", "test/test_manifest_providers.py::test_github", "test/test_manifest_providers.py::test_sanitize" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-10-02 04:10:53+00:00
bsd-2-clause
5,289
ros-tooling__cross_compile-116
diff --git a/README.md b/README.md index 95947f3..84c4b22 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,21 @@ ![License](https://img.shields.io/github/license/ros-tooling/cross_compile) [![Documentation Status](https://readthedocs.org/projects/cross_compile/badge/?version=latest)](https://cross_compile.readthedocs.io/en/latest/?badge=latest) -A tool to automate ROS2 packages compilation to non-native architectures. +A tool to automate compiling ROS and ROS2 workspaces to non-native architectures. :construction: `cross_compile` relies on running emulated builds using QEmu, #69 tracks progress toward enabling cross-compilation. +## Supported targets + +This tool supports compiling a workspace for all combinations of the following: + +* Architecture: `armhf`, `aarch64` +* ROS Distro + * ROS: `kinetic`, `melodic` + * ROS 2: `dashing`, `eloquent` +* OS: `Ubuntu`, `Debian` + ## Installation ### Prerequisites diff --git a/cross_compile/ros2_cross_compile.py b/cross_compile/ros2_cross_compile.py index 7f032bb..2a8e303 100644 --- a/cross_compile/ros2_cross_compile.py +++ b/cross_compile/ros2_cross_compile.py @@ -38,14 +38,8 @@ def parse_args(args: List[str]) -> argparse.Namespace: '-a', '--arch', required=True, type=str, - choices=['armhf', 'aarch64'], + choices=Platform.SUPPORTED_ARCHITECTURES.keys(), help='Target architecture') - parser.add_argument( - '-o', '--os', - required=True, - type=str, - choices=['ubuntu', 'debian'], - help='Target OS') parser.add_argument( '-d', '--rosdistro', required=False, @@ -53,6 +47,12 @@ def parse_args(args: List[str]) -> argparse.Namespace: default='dashing', choices=Platform.SUPPORTED_ROS_DISTROS + Platform.SUPPORTED_ROS2_DISTROS, help='Target ROS distribution') + parser.add_argument( + '-o', '--os', + required=True, + type=str, + # NOTE: not specifying choices here, as different distros may support different lists + help='Target OS') parser.add_argument( '-r', '--rmw', required=False, @@ -64,7 +64,8 @@ def parse_args(args: List[str]) -> argparse.Namespace: '--sysroot-base-image', required=False, type=str, - help='Base Docker image to use for building the sysroot. Ex. arm64v8/ubuntu:bionic') + help='Override the default base Docker image to use for building the sysroot. ' + 'Ex. "arm64v8/ubuntu:bionic"') parser.add_argument( '--docker-network-mode', required=False, @@ -85,7 +86,6 @@ def parse_args(args: List[str]) -> argparse.Namespace: help="The subdirectory of 'sysroot' that contains your 'src' to be built." 'The output of the cross compilation will be placed in this directory. ' "Defaults to 'ros_ws'.") - parser.add_argument( '--sysroot-path', required=False, @@ -120,11 +120,12 @@ def main(): """Start the cross-compilation workflow.""" # Configuration args = parse_args(sys.argv[1:]) - platform = Platform( - args.arch, args.os, args.rosdistro, args.rmw) + platform = Platform(args.arch, args.os, args.rosdistro, args.rmw) docker_args = DockerConfig( - args.arch, args.os, args.rosdistro, args.sysroot_base_image, - args.docker_network_mode, args.sysroot_nocache) + platform, + args.sysroot_base_image, + args.docker_network_mode, + args.sysroot_nocache) # Main pipeline sysroot_create = SysrootCompiler(cc_root_dir=args.sysroot_path, diff --git a/cross_compile/sysroot_compiler.py b/cross_compile/sysroot_compiler.py index 5f6b660..cba75b2 100755 --- a/cross_compile/sysroot_compiler.py +++ b/cross_compile/sysroot_compiler.py @@ -22,6 +22,7 @@ import shutil from string import Template import tarfile import tempfile +from typing import NamedTuple from typing import Optional import docker @@ -59,7 +60,14 @@ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) -def replace_tree(src: Path, dest: Path) -> None: +class ArchMapping(NamedTuple): + """Pair the toolchain and base Docker image for a target architecture as named members.""" + + toolchain: str + docker_base: str + + +def _replace_tree(src: Path, dest: Path) -> None: """Delete dest and copy the directory src to that location.""" shutil.rmtree(str(dest), ignore_errors=True) # it may or may not exist already shutil.copytree(str(src), str(dest)) @@ -76,29 +84,91 @@ class Platform: 4. RMW implementation used """ + # NOTE: when changing any following values, update README.md Supported Targets section + SUPPORTED_ARCHITECTURES = { + 'armhf': ArchMapping( + toolchain='arm-linux-gnueabihf', + docker_base='arm32v7', + ), + 'aarch64': ArchMapping( + toolchain='aarch64-linux-gnu', + docker_base='arm64v8', + ) + } + SUPPORTED_ROS2_DISTROS = ['dashing', 'eloquent'] SUPPORTED_ROS_DISTROS = ['kinetic', 'melodic'] - def __init__(self, arch: str, os: str, rosdistro: str, rmw: str): + ROSDISTRO_OS_MAPPING = { + 'kinetic': { + 'ubuntu': 'xenial', + 'debian': 'jessie', + }, + 'melodic': { + 'ubuntu': 'bionic', + 'debian': 'stretch', + }, + 'dashing': { + 'ubuntu': 'bionic', + 'debian': 'stretch', + }, + 'eloquent': { + 'ubuntu': 'bionic', + 'debian': 'buster', + }, + } + # NOTE: when changing any preceding values, update README.md Supported Targets section + + def __init__(self, arch: str, os_name: str, rosdistro: str, rmw: str): """Initialize platform parameters.""" - self.arch = arch - self.os = os - self.rosdistro = rosdistro - self.rmw = rmw + self._arch = arch + self._rosdistro = rosdistro + self._os_name = os_name + self._rmw = rmw - if self.arch == 'armhf': - self.cc_toolchain = 'arm-linux-gnueabihf' - elif self.arch == 'aarch64': - self.cc_toolchain = 'aarch64-linux-gnu' + try: + self._cc_toolchain = self.SUPPORTED_ARCHITECTURES[arch].toolchain + except KeyError: + raise ValueError('Unknown target architecture "{}" specified'.format(arch)) if self.rosdistro in self.SUPPORTED_ROS2_DISTROS: - self.ros_version = 'ros2' + self._ros_version = 'ros2' elif self.rosdistro in self.SUPPORTED_ROS_DISTROS: - self.ros_version = 'ros' + self._ros_version = 'ros' + else: + raise ValueError('Unknown ROS distribution "{}" specified'.format(rosdistro)) + + if self.os_name not in self.ROSDISTRO_OS_MAPPING[self.rosdistro]: + raise ValueError( + 'OS "{}" not supported for ROS distro "{}"'.format(os_name, rosdistro)) + + @property + def arch(self): + return self._arch + + @property + def rosdistro(self): + return self._rosdistro + + @property + def os_name(self): + return self._os_name + + @property + def rmw(self): + return self._rmw + + @property + def cc_toolchain(self): + return self._cc_toolchain + + @property + def ros_version(self): + return self._ros_version def __str__(self): """Return string representation of platform parameters.""" - return '-'.join((self.arch, self.os, self.rosdistro)) + return '-'.join((self.arch, self.os_name, self.rosdistro)) def get_workspace_image_tag(self) -> str: """Generate docker image name and tag.""" @@ -116,38 +186,18 @@ class DockerConfig: """ def __init__( - self, arch: str, os: str, rosdistro: str, sysroot_base_image: str, + self, platform: Platform, override_base_image: Optional[str], docker_network_mode: str, sysroot_nocache: bool ): - base_image = { - 'armhf': 'arm32v7', - 'aarch64': 'arm64v8', - } - image_tag = { - 'kinetic': { - 'ubuntu': 'xenial', - 'debian': 'jessie', - }, - 'melodic': { - 'ubuntu': 'bionic', - 'debian': 'stretch', - }, - 'dashing': { - 'ubuntu': 'bionic', - 'debian': 'stretch', - }, - 'eloquent': { - 'ubuntu': 'bionic', - 'debian': 'buster', - } - } - """Initialize docker configuration.""" - if sysroot_base_image is None: - self.base_image = \ - self.base_image = '{}/{}:{}'.format(base_image[arch], os, image_tag[rosdistro][os]) + if override_base_image: + self.base_image = override_base_image else: - self.base_image = sysroot_base_image + # Platform constructor has already performed validation on these values + docker_base = Platform.SUPPORTED_ARCHITECTURES[platform.arch].docker_base + distro_os = Platform.ROSDISTRO_OS_MAPPING[platform.rosdistro] + image_tag = distro_os[platform.os_name] + self.base_image = '{}/{}:{}'.format(docker_base, platform.os_name, image_tag) self.network_mode = docker_network_mode self.nocache = sysroot_nocache @@ -266,7 +316,7 @@ class SysrootCompiler: mixins_src = package_path / 'mixins' mixins_dest = self._target_sysroot / 'mixins' - replace_tree(mixins_src, mixins_dest) + _replace_tree(mixins_src, mixins_dest) if not mixins_dest.exists(): raise FileNotFoundError('Mixins not properly copied to build context') logger.debug('Copied mixins')
ros-tooling/cross_compile
5461a52cb970dd0ee4318e1de733cb7351dc53f8
diff --git a/test/test_sysroot_compiler.py b/test/test_sysroot_compiler.py index 2727e3f..ab1d9ea 100644 --- a/test/test_sysroot_compiler.py +++ b/test/test_sysroot_compiler.py @@ -32,27 +32,24 @@ import pytest THIS_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -def _default_docker_kwargs() -> dict: - return { - 'arch': 'aarch64', - 'os': 'ubuntu', - 'rosdistro': 'dashing', - 'sysroot_base_image': '035662560449.dkr.ecr.us-east-2.amazonaws.com/cc-tool:' - 'aarch64-bionic-dashing-fastrtps-prebuilt', - 'docker_network_mode': 'host', - 'sysroot_nocache': False, - } - - @pytest.fixture def platform_config() -> Platform: return Platform( arch='aarch64', - os='ubuntu', + os_name='ubuntu', rosdistro='dashing', rmw='fastrtps') +def _default_docker_kwargs() -> dict: + return { + 'platform': Platform('aarch64', 'ubuntu', 'dashing', 'fastrtps'), + 'override_base_image': 'arm64v8/gcc:9.2.0', + 'docker_network_mode': 'host', + 'sysroot_nocache': False, + } + + @pytest.fixture def docker_config() -> DockerConfig: return DockerConfig(**_default_docker_kwargs()) @@ -71,6 +68,24 @@ def setup_mock_sysroot(path: Path) -> Tuple[Path, Path]: return sysroot_dir, ros_workspace_dir +def test_platform_argument_validation(): + rmw = 'fastrtps' + p = Platform('armhf', 'ubuntu', 'dashing', rmw) + assert p + + with pytest.raises(ValueError): + # invalid arch + p = Platform('mips', 'ubuntu', 'dashing', rmw) + + with pytest.raises(ValueError): + # invalid distro + p = Platform('armhf', 'ubuntu', 'ardent', rmw) + + with pytest.raises(ValueError): + # invalid OS + p = Platform('armhf', 'rhel', 'dashing', rmw) + + def test_get_workspace_image_tag(platform_config): """Make sure the image tag is created correctly.""" image_tag = platform_config.get_workspace_image_tag() @@ -87,7 +102,7 @@ def test_docker_config_args(docker_config): 'Network Mode: {}\n' 'Caching: {}' ).format( - args['sysroot_base_image'], args['docker_network_mode'], args['sysroot_nocache'] + args['override_base_image'], args['docker_network_mode'], args['sysroot_nocache'] ) config_string = str(docker_config) assert isinstance(config_string, str) @@ -179,11 +194,12 @@ def test_sysroot_compiler_tree_additions(platform_config, docker_config, tmpdir) def verify_base_docker_images(arch, os, rosdistro, image_name): """Assert correct base image is generated.""" - sysroot_base_image = None + override_base_image = None docker_network_mode = 'host' sysroot_nocache = 'False' + platform = Platform(arch, os, rosdistro, 'fastrtps') assert DockerConfig( - arch, os, rosdistro, sysroot_base_image, + platform, override_base_image, docker_network_mode, sysroot_nocache).base_image == image_name
Add supported cross compile targets to README ### Description Supported target platforms should be easily located in the README doc so users of Cross Compile can quickly know what is supported. ### Test Plan * N/A ### Documentation * Update `README.md` to display supported cross compile targets ### Release Plan * check in PR ### Acceptance Criteria * [ ] `README.md` is updated * [ ] Release plan has been completed Once all above items are checked, this story can be moved to done. ### Resources
0.0
5461a52cb970dd0ee4318e1de733cb7351dc53f8
[ "test/test_sysroot_compiler.py::test_platform_argument_validation", "test/test_sysroot_compiler.py::test_get_workspace_image_tag", "test/test_sysroot_compiler.py::test_docker_config_args", "test/test_sysroot_compiler.py::test_sysroot_compiler_constructor", "test/test_sysroot_compiler.py::test_custom_setup_script", "test/test_sysroot_compiler.py::test_custom_data_dir", "test/test_sysroot_compiler.py::test_sysroot_compiler_tree_validation", "test/test_sysroot_compiler.py::test_sysroot_compiler_tree_additions", "test/test_sysroot_compiler.py::test_get_docker_base_image", "test/test_sysroot_compiler.py::test_parse_docker_build_output" ]
[ "test/test_sysroot_compiler.py::test_docker_py_version" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-13 23:30:07+00:00
apache-2.0
5,290
ros-tooling__cross_compile-177
diff --git a/ros_cross_compile/dependencies.py b/ros_cross_compile/dependencies.py index 2c738ba..8e57edc 100644 --- a/ros_cross_compile/dependencies.py +++ b/ros_cross_compile/dependencies.py @@ -80,3 +80,15 @@ def gather_rosdeps( }, volumes=volumes, ) + + +def assert_install_rosdep_script_exists( + ros_workspace_dir: Path, + platform: Platform +) -> bool: + install_rosdep_script_path = ros_workspace_dir / rosdep_install_script(platform) + if not install_rosdep_script_path.is_file(): + raise RuntimeError('Rosdep installation script has never been created,' + 'you need to run this without skipping rosdep collection' + 'at least once.') + return True diff --git a/ros_cross_compile/ros_cross_compile.py b/ros_cross_compile/ros_cross_compile.py index 60bc710..1da143d 100644 --- a/ros_cross_compile/ros_cross_compile.py +++ b/ros_cross_compile/ros_cross_compile.py @@ -24,6 +24,7 @@ from typing import List from typing import Optional from ros_cross_compile.builders import run_emulated_docker_build +from ros_cross_compile.dependencies import assert_install_rosdep_script_exists from ros_cross_compile.dependencies import gather_rosdeps from ros_cross_compile.docker_client import DEFAULT_COLCON_DEFAULTS_FILE from ros_cross_compile.docker_client import DockerClient @@ -116,6 +117,15 @@ def parse_args(args: List[str]) -> argparse.Namespace: help='Relative path within the workspace to a file that provides colcon arguments. ' 'See "Package Selection and Build Customization" in README.md for more details.') + parser.add_argument( + '--skip-rosdep-collection', + action='store_true', + required=False, + help='Skip querying rosdep for dependencies. This is intended to save time' + 'when running repeatedly during development, but has undefined behavior if' + "the workspace's dependencies have changed since the last time" + 'collection was run.') + return parser.parse_args(args) @@ -139,12 +149,14 @@ def cross_compile_pipeline( default_docker_dir=sysroot_build_context, colcon_defaults_file=args.colcon_defaults) - gather_rosdeps( - docker_client=docker_client, - platform=platform, - workspace=ros_workspace_dir, - custom_script=custom_rosdep_script, - custom_data_dir=custom_data_dir) + if not args.skip_rosdep_collection: + gather_rosdeps( + docker_client=docker_client, + platform=platform, + workspace=ros_workspace_dir, + custom_script=custom_rosdep_script, + custom_data_dir=custom_data_dir) + assert_install_rosdep_script_exists(ros_workspace_dir, platform) create_workspace_sysroot_image(docker_client, platform) run_emulated_docker_build(docker_client, platform, ros_workspace_dir)
ros-tooling/cross_compile
9fc6c4d8148a8a8967082802c42a1e897e0d3ae7
diff --git a/test/test_entrypoint.py b/test/test_entrypoint.py index 0412da0..9058cb2 100644 --- a/test/test_entrypoint.py +++ b/test/test_entrypoint.py @@ -12,10 +12,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +from pathlib import Path from unittest.mock import Mock from unittest.mock import patch +import pytest + # from ros_cross_compile.docker_client import DockerClient +from ros_cross_compile.dependencies import assert_install_rosdep_script_exists +from ros_cross_compile.dependencies import rosdep_install_script +from ros_cross_compile.platform import Platform from ros_cross_compile.ros_cross_compile import cross_compile_pipeline from ros_cross_compile.ros_cross_compile import parse_args @@ -27,8 +33,32 @@ def test_trivial_argparse(): def test_mocked_cc_pipeline(tmpdir): args = parse_args([str(tmpdir), '-a', 'aarch64', '-o', 'ubuntu']) - with patch('ros_cross_compile.ros_cross_compile.DockerClient', Mock()) as docker_mock: + with patch( + 'ros_cross_compile.ros_cross_compile.DockerClient', Mock() + ) as docker_mock, patch( + 'ros_cross_compile.ros_cross_compile.assert_install_rosdep_script_exists' + ) as script_mock: cross_compile_pipeline(args) + assert script_mock.called assert docker_mock.called assert docker_mock().build_image.call_count == 2 assert docker_mock().run_container.call_count == 2 + + +def test_install_rosdep_script_exist(tmpdir): + ws = Path(str(tmpdir)) + platform = Platform('aarch64', 'ubuntu', 'dashing') + data_file = ws / rosdep_install_script(platform) + data_file.parent.mkdir(parents=True) + data_file.touch() + check_script = assert_install_rosdep_script_exists(ws, platform) + assert check_script + + +def test_install_rosdep_script_doesnot_exist(tmpdir): + ws = Path(str(tmpdir)) + platform = Platform('aarch64', 'ubuntu', 'dashing') + data_file = ws / rosdep_install_script(platform) + data_file.parent.mkdir(parents=True) + with pytest.raises(RuntimeError): + assert_install_rosdep_script_exists(ws, platform)
Allow user to skip rosdep collection ## Description As a time optimization in the build process, allow the user to skip collecting rosdeps. It can take about 10s to run `rosdep update` and when working on code without changing dependencies, it is not necessary every time. This would be a "power-user feature" ## Related Issues Depends on #139 ## Completion Criteria * [x] User can explicitly skip collecting rosdeps via a CLI flag * [x] If the `cc_internals/install_rosdeps.sh` script doesn't exist already, raise an exception * [x] Appropriate documentation exists on the flag to warn about the problems it can cause when used incorrectly. Something like "NOTE: This is an optimization feature for incremental builds to save time running `rosdep update` - you must have run without this flag at least once to collect the initial dependencies. It has undefined behavior if you change the dependencies of your workspace." ## Implementation Notes / Suggestions Just need a bool CLI flag to pass to the cross_compile pipeline and put the rosdep step in an if-block ## Testing Notes / Suggestions Add a unit test!
0.0
9fc6c4d8148a8a8967082802c42a1e897e0d3ae7
[ "test/test_entrypoint.py::test_trivial_argparse", "test/test_entrypoint.py::test_install_rosdep_script_exist", "test/test_entrypoint.py::test_install_rosdep_script_doesnot_exist" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-27 01:57:05+00:00
apache-2.0
5,291
ros-tooling__cross_compile-216
diff --git a/ros_cross_compile/ros_cross_compile.py b/ros_cross_compile/ros_cross_compile.py index 38fb475..b37fd01 100644 --- a/ros_cross_compile/ros_cross_compile.py +++ b/ros_cross_compile/ros_cross_compile.py @@ -137,7 +137,12 @@ def cross_compile_pipeline( ): platform = Platform(args.arch, args.os, args.rosdistro, args.sysroot_base_image) - ros_workspace_dir = Path(args.ros_workspace) + ros_workspace_dir = Path(args.ros_workspace).resolve() + if not (ros_workspace_dir / 'src').is_dir(): + raise ValueError( + 'Specified workspace "{}" does not look like a colcon workspace ' + '(there is no "src/" directory). Cannot continue'.format(ros_workspace_dir)) + skip_rosdep_keys = args.skip_rosdep_keys custom_data_dir = _path_if(args.custom_data_dir) custom_rosdep_script = _path_if(args.custom_rosdep_script)
ros-tooling/cross_compile
2a05d1815ad4d13d7e96039fd15bb54b99f3841d
diff --git a/test/test_entrypoint.py b/test/test_entrypoint.py index 9058cb2..07dde78 100644 --- a/test/test_entrypoint.py +++ b/test/test_entrypoint.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import contextlib +import os from pathlib import Path from unittest.mock import Mock from unittest.mock import patch @@ -26,12 +28,47 @@ from ros_cross_compile.ros_cross_compile import cross_compile_pipeline from ros_cross_compile.ros_cross_compile import parse_args [email protected] +def chdir(dirname: str): + """Provide a "with" statement for changing the working directory.""" + curdir = os.getcwd() + try: + os.chdir(dirname) + yield + finally: + os.chdir(curdir) + + def test_trivial_argparse(): args = parse_args(['somepath', '-a', 'aarch64', '-o', 'ubuntu']) assert args +def test_bad_workspace(tmpdir): + args = parse_args([str(tmpdir), '-a', 'aarch64', '-o', 'ubuntu', '-d', 'foxy']) + with pytest.raises(ValueError): + cross_compile_pipeline(args) + + +def test_relative_workspace(tmpdir): + # Change directory to the tmp dir and invoke using '.' as the + # workspace to check if relative paths work + tmp = Path(str(tmpdir)) + (tmp / 'src').mkdir() + relative_dir = '.' + args = parse_args([relative_dir, '-a', 'aarch64', '-o', 'ubuntu', '-d', 'foxy']) + with chdir(str(tmp)), patch( + 'ros_cross_compile.ros_cross_compile.DockerClient', Mock() + ), patch( + 'ros_cross_compile.ros_cross_compile.assert_install_rosdep_script_exists' + ): + # should not raise an exception + cross_compile_pipeline(args) + + def test_mocked_cc_pipeline(tmpdir): + tmp = Path(str(tmpdir)) + (tmp / 'src').mkdir() args = parse_args([str(tmpdir), '-a', 'aarch64', '-o', 'ubuntu']) with patch( 'ros_cross_compile.ros_cross_compile.DockerClient', Mock()
cross compile script fails on OSX ## Description I am trying to follow the tutorial and build the [demos](https://github.com/ros2/demos.git) for AARCH64 under OSX. The script unfortunately does not go through and fails with a stacktrace. ### Expected Behavior Script exits correctly and `build_aarch64` is created. ### Actual Behavior i am running `ros_cross_compile --arch aarch64 --os ubuntu --rosdistro foxy .`, where `.` is the current workspace. ``` INFO:Rosdep Gatherer:Running rosdep collector image on workspace . Traceback (most recent call last): File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/api/client.py", line 222, in _raise_for_status response.raise_for_status() File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http+docker://localunixsocket/v1.30/containers/create During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/karsten/.pyenv/versions/3.7.4/bin/ros_cross_compile", line 8, in <module> sys.exit(main()) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ros_cross_compile/ros_cross_compile.py", line 172, in main cross_compile_pipeline(args) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ros_cross_compile/ros_cross_compile.py", line 163, in cross_compile_pipeline custom_data_dir=custom_data_dir) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ros_cross_compile/dependencies.py", line 84, in gather_rosdeps volumes=volumes, File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/ros_cross_compile/docker_client.py", line 128, in run_container network_mode='host', File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/models/containers.py", line 719, in run detach=detach, **kwargs) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/models/containers.py", line 777, in create resp = self.client.api.create_container(**create_kwargs) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/api/container.py", line 450, in create_container return self.create_container_from_config(config, name) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/api/container.py", line 461, in create_container_from_config return self._result(res, True) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/api/client.py", line 228, in _result self._raise_for_status(response) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/api/client.py", line 224, in _raise_for_status raise create_api_error_from_http_exception(e) File "/Users/karsten/.pyenv/versions/3.7.4/Python.framework/Versions/3.7/lib/python3.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception raise cls(e, response=response, explanation=explanation) docker.errors.APIError: 400 Client Error: Bad Request ("create .: volume name is too short, names should be at least two alphanumeric characters") ``` ## System (please complete the following information) - OSX - ROS 2 Distro: Foxy
0.0
2a05d1815ad4d13d7e96039fd15bb54b99f3841d
[ "test/test_entrypoint.py::test_bad_workspace" ]
[ "test/test_entrypoint.py::test_trivial_argparse", "test/test_entrypoint.py::test_install_rosdep_script_exist", "test/test_entrypoint.py::test_install_rosdep_script_doesnot_exist" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-06-23 00:13:46+00:00
apache-2.0
5,292
ros-tooling__cross_compile-235
diff --git a/ros_cross_compile/builders.py b/ros_cross_compile/builders.py index 92e029f..b3c72e7 100644 --- a/ros_cross_compile/builders.py +++ b/ros_cross_compile/builders.py @@ -15,6 +15,7 @@ import logging import os from pathlib import Path +from ros_cross_compile.data_collector import DataCollector from ros_cross_compile.docker_client import DockerClient from ros_cross_compile.pipeline_stages import PipelineStage from ros_cross_compile.pipeline_stages import PipelineStageConfigOptions @@ -60,5 +61,6 @@ class DockerBuildStage(PipelineStage): super().__init__('run_emulated_docker_build') def __call__(self, platform: Platform, docker_client: DockerClient, ros_workspace_dir: Path, - pipeline_stage_config_options: PipelineStageConfigOptions): + pipeline_stage_config_options: PipelineStageConfigOptions, + data_collector: DataCollector): run_emulated_docker_build(docker_client, platform, ros_workspace_dir) diff --git a/ros_cross_compile/data_collector.py b/ros_cross_compile/data_collector.py index 4732419..1589656 100644 --- a/ros_cross_compile/data_collector.py +++ b/ros_cross_compile/data_collector.py @@ -21,7 +21,8 @@ from pathlib import Path import time from typing import Dict, List, NamedTuple, Union -from ros_cross_compile.sysroot_creator import INTERNALS_DIR + +INTERNALS_DIR = 'cc_internals' Datum = NamedTuple('Datum', [('name', str), @@ -58,10 +59,16 @@ class DataCollector: complete = True finally: elapsed = time.monotonic() - start - time_metric = Datum(name + '-time', elapsed, + time_metric = Datum('{}-time'.format(name), elapsed, Units.Seconds.value, time.monotonic(), complete) self.add_datum(time_metric) + def add_size(self, name: str, size: int): + """Provide an interface to add collected Docker image sizes.""" + size_metric = Datum('{}-size'.format(name), size, + Units.Bytes.value, time.monotonic(), True) + self.add_datum(size_metric) + class DataWriter: """Provides an interface to write collected data to a file.""" diff --git a/ros_cross_compile/dependencies.py b/ros_cross_compile/dependencies.py index bee727d..9e18969 100644 --- a/ros_cross_compile/dependencies.py +++ b/ros_cross_compile/dependencies.py @@ -18,6 +18,7 @@ from pathlib import Path from typing import List from typing import Optional +from ros_cross_compile.data_collector import DataCollector from ros_cross_compile.docker_client import DockerClient from ros_cross_compile.pipeline_stages import PipelineStage from ros_cross_compile.pipeline_stages import PipelineStageConfigOptions @@ -30,6 +31,7 @@ logger = logging.getLogger('Rosdep Gatherer') CUSTOM_SETUP = '/usercustom/rosdep_setup' CUSTOM_DATA = '/usercustom/custom-data' +_IMG_NAME = 'ros_cross_compile:rosdep' def rosdep_install_script(platform: Platform) -> Path: @@ -57,11 +59,10 @@ def gather_rosdeps( """ out_path = rosdep_install_script(platform) - image_name = 'ros_cross_compile:rosdep' - logger.info('Building rosdep collector image: %s', image_name) + logger.info('Building rosdep collector image: %s', _IMG_NAME) docker_client.build_image( dockerfile_name='rosdep.Dockerfile', - tag=image_name, + tag=_IMG_NAME, ) logger.info('Running rosdep collector image on workspace {}'.format(workspace)) @@ -74,7 +75,7 @@ def gather_rosdeps( volumes[custom_data_dir] = CUSTOM_DATA docker_client.run_container( - image_name=image_name, + image_name=_IMG_NAME, environment={ 'CUSTOM_SETUP': CUSTOM_SETUP, 'OUT_PATH': str(out_path), @@ -111,10 +112,13 @@ class DependenciesStage(PipelineStage): super().__init__('gather_rosdeps') def __call__(self, platform: Platform, docker_client: DockerClient, ros_workspace_dir: Path, - pipeline_stage_config_options: PipelineStageConfigOptions): + pipeline_stage_config_options: PipelineStageConfigOptions, + data_collector: DataCollector): """ Run the inspection and output the dependency installation script. + Also recovers the size of the docker image generated. + :raises RuntimeError if the step was skipped when no dependency script has been previously generated """ @@ -129,3 +133,6 @@ class DependenciesStage(PipelineStage): custom_script=pipeline_stage_config_options.custom_script, custom_data_dir=pipeline_stage_config_options.custom_data_dir) assert_install_rosdep_script_exists(ros_workspace_dir, platform) + + img_size = docker_client.get_image_size(_IMG_NAME) + data_collector.add_size(self.name, img_size) diff --git a/ros_cross_compile/docker_client.py b/ros_cross_compile/docker_client.py index 5578142..846ba42 100644 --- a/ros_cross_compile/docker_client.py +++ b/ros_cross_compile/docker_client.py @@ -142,3 +142,6 @@ class DockerClient: if exit_code: raise docker.errors.ContainerError( image_name, exit_code, '', image_name, 'See above ^') + + def get_image_size(self, img_name: str) -> int: + return self._client.images.get(img_name).attrs['Size'] diff --git a/ros_cross_compile/pipeline_stages.py b/ros_cross_compile/pipeline_stages.py index 4078e58..1aa429c 100644 --- a/ros_cross_compile/pipeline_stages.py +++ b/ros_cross_compile/pipeline_stages.py @@ -16,6 +16,7 @@ from abc import ABC, abstractmethod from pathlib import Path from typing import List, NamedTuple, Optional +from ros_cross_compile.data_collector import DataCollector from ros_cross_compile.docker_client import DockerClient from ros_cross_compile.platform import Platform @@ -47,5 +48,6 @@ class PipelineStage(ABC): @abstractmethod def __call__(self, platform: Platform, docker_client: DockerClient, ros_workspace_dir: Path, - customizations: PipelineStageConfigOptions): + pipeline_stage_config_options: PipelineStageConfigOptions, + data_collector: DataCollector): raise NotImplementedError diff --git a/ros_cross_compile/ros_cross_compile.py b/ros_cross_compile/ros_cross_compile.py index 8fdd0da..d823cd7 100644 --- a/ros_cross_compile/ros_cross_compile.py +++ b/ros_cross_compile/ros_cross_compile.py @@ -186,7 +186,7 @@ def cross_compile_pipeline( for stage in stages: with data_collector.timer('cross_compile_{}'.format(stage.name)): - stage(platform, docker_client, ros_workspace_dir, customizations) + stage(platform, docker_client, ros_workspace_dir, customizations, data_collector) def main(): diff --git a/ros_cross_compile/sysroot_creator.py b/ros_cross_compile/sysroot_creator.py index a03cff0..d8d772d 100755 --- a/ros_cross_compile/sysroot_creator.py +++ b/ros_cross_compile/sysroot_creator.py @@ -19,6 +19,8 @@ import platform as py_platform import shutil from typing import Optional +from ros_cross_compile.data_collector import DataCollector +from ros_cross_compile.data_collector import INTERNALS_DIR from ros_cross_compile.docker_client import DockerClient from ros_cross_compile.pipeline_stages import PipelineStage from ros_cross_compile.pipeline_stages import PipelineStageConfigOptions @@ -27,8 +29,6 @@ from ros_cross_compile.platform import Platform logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) -INTERNALS_DIR = 'cc_internals' - def build_internals_dir(platform: Platform) -> Path: """Construct a relative path for this build, for storing intermediate artifacts.""" @@ -135,5 +135,9 @@ class CreateSysrootStage(PipelineStage): super().__init__('create_workspace_sysroot_image') def __call__(self, platform: Platform, docker_client: DockerClient, ros_workspace_dir: Path, - pipeline_stage_config_options: PipelineStageConfigOptions): + pipeline_stage_config_options: PipelineStageConfigOptions, + data_collector: DataCollector): create_workspace_sysroot_image(docker_client, platform) + + img_size = docker_client.get_image_size(platform.sysroot_image_tag) + data_collector.add_size(self.name, img_size)
ros-tooling/cross_compile
fabe7115bad8d08beddd100cdbdeb7d43793b29b
diff --git a/test/test_builders.py b/test/test_builders.py index 4292c96..1e51cc8 100644 --- a/test/test_builders.py +++ b/test/test_builders.py @@ -23,13 +23,15 @@ from ros_cross_compile.platform import Platform def test_emulated_docker_build(): # Very simple smoke test to validate that all internal syntax is correct mock_docker_client = Mock() + mock_data_collector = Mock() platform = Platform('aarch64', 'ubuntu', 'eloquent') # a default set of customizations for the docker build stage customizations = PipelineStageConfigOptions(False, [], None, None, None) temp_stage = DockerBuildStage() - temp_stage(platform, mock_docker_client, Path('dummy_path'), customizations) + temp_stage(platform, mock_docker_client, + Path('dummy_path'), customizations, mock_data_collector) assert mock_docker_client.run_container.call_count == 1 diff --git a/test/test_dependencies.py b/test/test_dependencies.py index 5e35ded..e29394e 100644 --- a/test/test_dependencies.py +++ b/test/test_dependencies.py @@ -17,6 +17,7 @@ import shutil import docker import pytest +from ros_cross_compile.data_collector import DataCollector from ros_cross_compile.dependencies import DependenciesStage from ros_cross_compile.dependencies import gather_rosdeps from ros_cross_compile.dependencies import rosdep_install_script @@ -59,12 +60,13 @@ def test_dummy_ros2_pkg(tmpdir): client = DockerClient() platform = Platform(arch='aarch64', os_name='ubuntu', ros_distro='dashing') out_script = ws / rosdep_install_script(platform) + test_collector = DataCollector() # a default set of customizations for the dependencies stage customizations = PipelineStageConfigOptions(False, [], None, None, None) temp_stage = DependenciesStage() - temp_stage(platform, client, ws, customizations) + temp_stage(platform, client, ws, customizations, test_collector) result = out_script.read_text() assert 'ros-dashing-ament-cmake' in result diff --git a/test/test_sysroot_creator.py b/test/test_sysroot_creator.py index ecd0ae8..854ff9f 100644 --- a/test/test_sysroot_creator.py +++ b/test/test_sysroot_creator.py @@ -85,13 +85,15 @@ def test_basic_sysroot_creation(tmpdir): # Very simple smoke test to validate that all internal syntax is correct mock_docker_client = Mock() + mock_data_collector = Mock() platform = Platform('aarch64', 'ubuntu', 'eloquent') # a default set of customizations for the docker build stage customizations = PipelineStageConfigOptions(False, [], None, None, None) temp_stage = CreateSysrootStage() - temp_stage(platform, mock_docker_client, Path('dummy_path'), customizations) + temp_stage(platform, mock_docker_client, + Path('dummy_path'), customizations, mock_data_collector) assert mock_docker_client.build_image.call_count == 1
Report if an artifact is created per stage ## Description Getting the number of artifacts (Docker images) created per stage allows us to see which stages contribute to the total storage footprint of the tool, and why certain artifacts may contribute more than others. ## Related Issues Part of #205 ## Completion Criteria For each stage, log if an artifact is created and what its name is. ## Implementation Notes / Suggestions None ## Testing Notes / Suggestions For each stage, the accurate number of artifacts is output.
0.0
fabe7115bad8d08beddd100cdbdeb7d43793b29b
[ "test/test_builders.py::test_emulated_docker_build", "test/test_sysroot_creator.py::test_basic_sysroot_creation" ]
[ "test/test_builders.py::test_docker_build_stage_creation", "test/test_builders.py::test_docker_build_stage_name", "test/test_dependencies.py::test_dependencies_stage_creation", "test/test_dependencies.py::test_dependencies_stage_name", "test/test_sysroot_creator.py::test_emulator_not_installed", "test/test_sysroot_creator.py::test_emulator_touch", "test/test_sysroot_creator.py::test_create_sysroot_stage_creation", "test/test_sysroot_creator.py::test_create_sysroot_stage_name" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-15 20:07:05+00:00
apache-2.0
5,293
ros-tooling__cross_compile-240
diff --git a/ros_cross_compile/data_collector.py b/ros_cross_compile/data_collector.py index 1589656..a9f9213 100644 --- a/ros_cross_compile/data_collector.py +++ b/ros_cross_compile/data_collector.py @@ -15,6 +15,7 @@ """Classes for time series data collection and writing said data to a file.""" from contextlib import contextmanager +from datetime import datetime from enum import Enum import json from pathlib import Path @@ -60,13 +61,13 @@ class DataCollector: finally: elapsed = time.monotonic() - start time_metric = Datum('{}-time'.format(name), elapsed, - Units.Seconds.value, time.monotonic(), complete) + Units.Seconds.value, time.time(), complete) self.add_datum(time_metric) def add_size(self, name: str, size: int): """Provide an interface to add collected Docker image sizes.""" size_metric = Datum('{}-size'.format(name), size, - Units.Bytes.value, time.monotonic(), True) + Units.Bytes.value, time.time(), True) self.add_datum(size_metric) @@ -80,7 +81,26 @@ class DataWriter: self._write_path.mkdir(parents=True, exist_ok=True) self.write_file = self._write_path / output_file - def write(self, data_collector: DataCollector): + def print_helper(self, data_to_print: List[Dict]): + print('--------------------------------- Collected Data ---------------------------------') + print('=================================================================================') + for datum in data_to_print: + # readable_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(datum['timestamp'])) + readable_time = datetime.utcfromtimestamp(datum['timestamp']).isoformat() + if datum['unit'] == Units.Seconds.value: + print('{:>12} | {:>35}: {:.2f} {}'.format(readable_time, datum['name'], + datum['value'], datum['unit']), + end='') + else: + print('{:>12} | {:>35}: {} {}'.format(readable_time, datum['name'], + datum['value'], datum['unit']), + end='') + if datum['complete']: + print('\n') + else: + print(' {}'.format('incomplete')) + + def write(self, data_collector: DataCollector, print_data: bool): """ Write collected datums to a file. @@ -88,5 +108,7 @@ class DataWriter: so that they are conveniently 'dumpable' into a JSON file. """ data_to_dump = data_collector.serialize_data() + if print_data: + self.print_helper(data_to_dump) with self.write_file.open('w') as f: json.dump(list(data_to_dump), f, sort_keys=True, indent=4) diff --git a/ros_cross_compile/ros_cross_compile.py b/ros_cross_compile/ros_cross_compile.py index d823cd7..6d3d77f 100644 --- a/ros_cross_compile/ros_cross_compile.py +++ b/ros_cross_compile/ros_cross_compile.py @@ -148,8 +148,12 @@ def parse_args(args: List[str]) -> argparse.Namespace: default='{}.json'.format(datetime.now().strftime('%s')), type=str, help='Provide a filename to store the collected metrics. If no name is provided, ' - 'then the filename will be the current time in UNIX Epoch format. ' - ) + 'then the filename will be the current time in UNIX Epoch format. ') + parser.add_argument( + '--print-metrics', + action='store_true', + required=False, + help='All collected metrics will be printed to stdout via the logging framework.') return parser.parse_args(args) @@ -185,7 +189,7 @@ def cross_compile_pipeline( custom_setup_script) for stage in stages: - with data_collector.timer('cross_compile_{}'.format(stage.name)): + with data_collector.timer('{}'.format(stage.name)): stage(platform, docker_client, ros_workspace_dir, customizations, data_collector) @@ -197,10 +201,10 @@ def main(): data_writer = DataWriter(ros_workspace_dir, args.custom_metric_file) try: - with data_collector.timer('cross_compile_end_to_end'): + with data_collector.timer('end_to_end'): cross_compile_pipeline(args, data_collector) finally: - data_writer.write(data_collector) + data_writer.write(data_collector, args.print_metrics) if __name__ == '__main__':
ros-tooling/cross_compile
378f6c0d067d48c624f4720302ec549b6f534a1d
diff --git a/test/test_data_collector.py b/test/test_data_collector.py index 635c0c5..8a4d888 100644 --- a/test/test_data_collector.py +++ b/test/test_data_collector.py @@ -91,7 +91,21 @@ def test_data_writing(tmp_path): test_writer = DataWriter(tmp_path, 'test.json') - test_writer.write(test_collector) + test_writer.write(test_collector, False) assert test_writer.write_file.exists() assert load_json_validation(test_writer.write_file) + + +def test_data_printing(tmp_path, capfd): + test_collector = DataCollector() + test_datum_a = Datum('test_stat_1', 3, 'tests', 130.243, True) + test_collector.add_datum(test_datum_a) + + test_writer = DataWriter(tmp_path, 'test.json') + test_writer.write(test_collector, True) + + out, err = capfd.readouterr() + test_name = '------------' + + assert test_name in out
Provide User Option to Additionally Print Collected Metrics to `stdout` ## Description As a user, I can provide a command line flag to print performance metric results to stdout, so that I can get the results printed to stdout. ## Related Issues Dependent on: #206, #207, #208, #209 Part of: #205 ## Completion Criteria * The user can communicate to the program that the output should be printed to `stdout` ## Implementation Notes / Suggestions Use a command line argument. ## Testing Notes / Suggestions * Check that the output is not malformed in any way (sometimes trailing newlines or whitespaces can mess up `stdout` printing) * The printed results are accurate
0.0
378f6c0d067d48c624f4720302ec549b6f534a1d
[ "test/test_data_collector.py::test_data_writing", "test/test_data_collector.py::test_data_printing" ]
[ "test/test_data_collector.py::test_datum_construction", "test/test_data_collector.py::test_collector_construction", "test/test_data_collector.py::test_data_collection", "test/test_data_collector.py::test_timer_can_time", "test/test_data_collector.py::test_timer_error_handling" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-21 00:31:09+00:00
apache-2.0
5,294
ross__requests-futures-69
diff --git a/requests_futures/sessions.py b/requests_futures/sessions.py index 1ec90da..c159b19 100644 --- a/requests_futures/sessions.py +++ b/requests_futures/sessions.py @@ -39,7 +39,7 @@ PICKLE_ERROR = ('Cannot pickle function. Refer to documentation: https://' class FuturesSession(Session): - def __init__(self, executor=None, max_workers=2, session=None, + def __init__(self, executor=None, max_workers=8, session=None, adapter_kwargs=None, *args, **kwargs): """Creates a FuturesSession
ross/requests-futures
25f02578d48b0acad6f293c1a445790cec2bf302
diff --git a/test_requests_futures.py b/test_requests_futures.py index e85b699..6cb359f 100644 --- a/test_requests_futures.py +++ b/test_requests_futures.py @@ -77,7 +77,7 @@ class RequestsTestCase(TestCase): """ Tests the `max_workers` shortcut. """ from concurrent.futures import ThreadPoolExecutor session = FuturesSession() - self.assertEqual(session.executor._max_workers, 2) + self.assertEqual(session.executor._max_workers, 8) session = FuturesSession(max_workers=5) self.assertEqual(session.executor._max_workers, 5) session = FuturesSession(executor=ThreadPoolExecutor(max_workers=10))
max_workers default value is too low The default `max_workers` value is **2**, which seems extremely low to be a default. The `concurrent.futures` library itself has much higher defaults for `ThreadPoolExecutor`s at 5 * CPU cores (e.g. a 4 core machine would have 20 threads). I've seen some libraries that use `requests-futures` naively using the default. I'd like to suggest one of the following: 1. Increase the default to something more beneficial, e.g. **5** 2. Use the standard `concurrent.futures` default value (my preferred solution) The only problem with option 2 is that in Python 3.3 and 3.4 `max_workers` had no default value for ThreadPoolExecutors and *had* to be specified. This is easy enough to work around by implementing the same method `concurrent.futures` itself [introduced in Python 3.5](https://github.com/python/cpython/blob/3.5/Lib/concurrent/futures/thread.py#L91): ```python import os class FuturesSession(Session): def __init__(self, executor=None, max_workers=None, session=None, adapter_kwargs=None, *args, **kwargs): # ... if max_workers is None: max_workers = (os.cpu_count() or 1) * 5 ``` Would be happy to open a PR for this, but before doing so wanted to open this in case there's a hard requirement for this low default value I'm not aware of.
0.0
25f02578d48b0acad6f293c1a445790cec2bf302
[ "test_requests_futures.py::RequestsTestCase::test_max_workers", "test_requests_futures.py::RequestsProcessPoolTestCase::test_futures_session" ]
[ "test_requests_futures.py::RequestsTestCase::test_adapter_kwargs", "test_requests_futures.py::RequestsTestCase::test_context", "test_requests_futures.py::RequestsTestCase::test_futures_session", "test_requests_futures.py::RequestsTestCase::test_redirect", "test_requests_futures.py::RequestsTestCase::test_supplied_session", "test_requests_futures.py::RequestsProcessPoolTestCase::test_context", "test_requests_futures.py::RequestsProcessPoolTestCase::test_context_with_session", "test_requests_futures.py::RequestsProcessPoolTestCase::test_futures_existing_session" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-11-14 04:04:09+00:00
apache-2.0
5,295
rosscdh__mkdocs-markdownextradata-plugin-29
diff --git a/README.md b/README.md index a5913f4..1766c43 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,19 @@ If inside your data folder you have a directory and a file file called `[path/to/datafiles/]sections/captions.yaml` - where `[path/to/datafiles/]` is the path in your configuration - the data inside that file will be available in your templates as `sections.captions.whatever_variable_in_the_yaml`. +### Jinja2 Template Engine Configuration +You may provide [Jinja2 configuration](https://jinja.palletsprojects.com/en/2.11.x/api/#high-level-api) as plugin options: + +```yml +plugins: + - markdownextradata: + jinja_options: + comment_start_string: __CUSTOMCOMMENTSTART__ +``` + +The above example will make it so that instead of `{#`, the template engine will interpret `__CUSTOMCOMMENTSTART__` as comment start delimiter. This is useful in cases where +you write Markdown that contains Jinja-like syntax that's colliding with the template engine. Alternatively, it lets you control what the variable delimiter is (instead of the default `{{ }}`). ## Testing diff --git a/markdownextradata/plugin.py b/markdownextradata/plugin.py index 5ad5e2e..5433413 100644 --- a/markdownextradata/plugin.py +++ b/markdownextradata/plugin.py @@ -27,8 +27,11 @@ class MarkdownExtraDataPlugin(BasePlugin): Inject certain config variables into the markdown """ + JINJA_OPTIONS = "jinja_options" + config_scheme = ( ("data", mkdocs.config.config_options.Type(str_type, default=None)), + (JINJA_OPTIONS, mkdocs.config.config_options.Type(dict, default={})) ) def __add_data__(self, config, namespace, data): @@ -91,6 +94,7 @@ class MarkdownExtraDataPlugin(BasePlugin): def on_page_markdown(self, markdown, config, **kwargs): context = {key: config.get(key) for key in CONFIG_KEYS if key in config} context.update(config.get("extra", {})) - env = jinja2.Environment(undefined=jinja2.DebugUndefined) + jinja_options = self.config[self.JINJA_OPTIONS] + env = jinja2.Environment(undefined=jinja2.DebugUndefined, **jinja_options) md_template = env.from_string(markdown) return md_template.render(**config.get("extra"))
rosscdh/mkdocs-markdownextradata-plugin
b816b329a9c5e3c90af605295f1f02ed21ce9220
diff --git a/test/docs/index.md b/test/docs/index.md index 10cb91a..cdc28b4 100644 --- a/test/docs/index.md +++ b/test/docs/index.md @@ -2,4 +2,7 @@ Welcome to {{ customer.web_url }} -Inside the included md file there 3 {{ star }} \ No newline at end of file +Inside the included md file there 3 {{ star }} + +<!-- throws TemplateSyntaxError('Missing end of comment tag') unless comment_start_string is configured --> +You can use `{#binding.path}` to update the UI when the model changes. diff --git a/test/mkdocs.yml b/test/mkdocs.yml index 5a27c0d..7f671f1 100644 --- a/test/mkdocs.yml +++ b/test/mkdocs.yml @@ -5,7 +5,9 @@ use_directory_urls: true # custom_dir: 'theme/' plugins: - search - - markdownextradata + - markdownextradata: + jinja_options: + comment_start_string: __COMMENTSTART__ extra: star: "![star](ressources/star.png)" diff --git a/test/test_basic.py b/test/test_basic.py index 5af748d..f544540 100644 --- a/test/test_basic.py +++ b/test/test_basic.py @@ -23,7 +23,8 @@ def test_basic_working(): contents = index_file.read_text() assert '<h1 id="hi-there-your-name-here">Hi there, Your name here</h1>' in contents, f"customer.name is not in index" - assert '<p>Inside the included md file there 3 <img alt="star" src="ressources/star.png" /></p></div>' in contents, f"customer.star is not in index or not rendering as expected" + assert '<p>Inside the included md file there 3 <img alt="star" src="ressources/star.png" /></p>' in contents, f"customer.star is not in index or not rendering as expected" assert f"Welcome to {customer.get('web_url')}" in contents, f"customer.web_url is not in index" + assert f"{{#binding.path}}" in contents, f"Jinja2 comment syntax wasn't reconfigured via jinja_options as expected" assert isinstance(test_json_string, str), "test_json_string is not a str it should be" assert '{"name": "Bob"}' == test_json_string, f"Json string is not correct"
Feature Request: Support Jinja2 config from mkdocs.yml I just ran into an issue where the Markdown source docs would contain Jinja2-like syntax that lead to errors, more specifically the following: `{#someVariableBindingString}` This is misinterpreted (even though it was in a code block) as a Jinja2 comment due to the initial `{#`. I see two options here: 1. Make the plugin syntax-aware and ignore variables in code blocks 1. Support feeding in Jinja2 options as shown in [different delimiters in jinja2](https://gist.github.com/lost-theory/3925738) and [API](https://jinja.palletsprojects.com/en/2.11.x/api/#high-level-api) I believe 1) to be more of a feature than an issue, and 2) appears like it would enable everyone to customize this plugin to their heart's content. I believe, therefore, that 2) is the way to go. Will open a PR in a few minutes with a draft.
0.0
b816b329a9c5e3c90af605295f1f02ed21ce9220
[ "test/test_basic.py::test_basic_working" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-11-02 13:45:57+00:00
mit
5,296
rr-__docstring_parser-31
diff --git a/docstring_parser/google.py b/docstring_parser/google.py index 5a817c1..1be8972 100644 --- a/docstring_parser/google.py +++ b/docstring_parser/google.py @@ -222,12 +222,20 @@ class GoogleParser: splits.append((matches[j].end(), matches[j + 1].start())) splits.append((matches[-1].end(), len(meta_chunk))) - chunks = OrderedDict() + chunks = OrderedDict() # type: T.Mapping[str,str] for j, (start, end) in enumerate(splits): title = matches[j].group(1) if title not in self.sections: continue - chunks[title] = meta_chunk[start:end].strip("\n") + + # Clear Any Unknown Meta + # Ref: https://github.com/rr-/docstring_parser/issues/29 + meta_details = meta_chunk[start:end] + unknown_meta = re.search(r"\n\S", meta_details) + if unknown_meta is not None: + meta_details = meta_details[: unknown_meta.start()] + + chunks[title] = meta_details.strip("\n") if not chunks: return ret
rr-/docstring_parser
a5dc2cd77eca9fd8aeaf34983b2460b301e5b005
diff --git a/docstring_parser/tests/test_google.py b/docstring_parser/tests/test_google.py index d49544f..a725b7f 100644 --- a/docstring_parser/tests/test_google.py +++ b/docstring_parser/tests/test_google.py @@ -591,3 +591,28 @@ def test_broken_meta() -> None: with pytest.raises(ParseError): parse("Args:\n herp derp") + + +def test_unknown_meta() -> None: + docstring = parse( + """Short desc + + Unknown 0: + title0: content0 + + Args: + arg0: desc0 + arg1: desc1 + + Unknown1: + title1: content1 + + Unknown2: + title2: content2 + """ + ) + + assert docstring.params[0].arg_name == "arg0" + assert docstring.params[0].description == "desc0" + assert docstring.params[1].arg_name == "arg1" + assert docstring.params[1].description == "desc1"
Parameter description parsing captures less indented text of another section Expected behavior: Parameter description ends when there parser encounters less indented line. Actual behavior: The parameter description capturing does not seem to stop when less indented line is encountered and captures it as well. ```python def foo(): '''Converts Keras HDF5 model to Tensorflow SavedModel format. Args: model_path: Keras model in HDF5 format. converted_model_path: Keras model in Tensorflow SavedModel format. Annotations: author: Alexey Volkov <[email protected]> ''' ``` The description for `converted_model_path` becomes: ``` Keras model in Tensorflow SavedModel format. Annotations: ``` P.S. It would be really great if it was possible to parse additional sections that are not currently recognized by the docstring_parser.
0.0
a5dc2cd77eca9fd8aeaf34983b2460b301e5b005
[ "docstring_parser/tests/test_google.py::test_unknown_meta" ]
[ "docstring_parser/tests/test_google.py::test_google_parser", "docstring_parser/tests/test_google.py::test_short_description[-None]", "docstring_parser/tests/test_google.py::test_short_description[\\n-None]", "docstring_parser/tests/test_google.py::test_short_description[Short", "docstring_parser/tests/test_google.py::test_short_description[\\nShort", "docstring_parser/tests/test_google.py::test_short_description[\\n", "docstring_parser/tests/test_google.py::test_long_description[Short", "docstring_parser/tests/test_google.py::test_long_description[\\n", "docstring_parser/tests/test_google.py::test_long_description[\\nShort", "docstring_parser/tests/test_google.py::test_meta_newlines[\\n", "docstring_parser/tests/test_google.py::test_meta_with_multiline_description", "docstring_parser/tests/test_google.py::test_default_args", "docstring_parser/tests/test_google.py::test_multiple_meta", "docstring_parser/tests/test_google.py::test_params", "docstring_parser/tests/test_google.py::test_attributes", "docstring_parser/tests/test_google.py::test_returns", "docstring_parser/tests/test_google.py::test_raises", "docstring_parser/tests/test_google.py::test_examples", "docstring_parser/tests/test_google.py::test_broken_meta" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-09-22 14:51:55+00:00
mit
5,297
rr-__docstring_parser-65
diff --git a/docstring_parser/common.py b/docstring_parser/common.py index 16f14d9..e3e5a56 100644 --- a/docstring_parser/common.py +++ b/docstring_parser/common.py @@ -137,10 +137,12 @@ class DocstringExample(DocstringMeta): def __init__( self, args: T.List[str], + snippet: T.Optional[str], description: T.Optional[str], ) -> None: """Initialize self.""" super().__init__(args, description) + self.snippet = snippet self.description = description diff --git a/docstring_parser/google.py b/docstring_parser/google.py index a31e4a5..2eca8f4 100644 --- a/docstring_parser/google.py +++ b/docstring_parser/google.py @@ -136,7 +136,9 @@ class GoogleParser: args=[section.key], description=desc, type_name=None ) if section.key in EXAMPLES_KEYWORDS: - return DocstringExample(args=[section.key], description=desc) + return DocstringExample( + args=[section.key], snippet=None, description=desc + ) if section.key in PARAM_KEYWORDS: raise ParseError("Expected paramenter name.") return DocstringMeta(args=[section.key], description=desc) diff --git a/docstring_parser/numpydoc.py b/docstring_parser/numpydoc.py index 7920f6c..e613f0f 100644 --- a/docstring_parser/numpydoc.py +++ b/docstring_parser/numpydoc.py @@ -7,10 +7,12 @@ import inspect import itertools import re import typing as T +from textwrap import dedent from .common import ( Docstring, DocstringDeprecated, + DocstringExample, DocstringMeta, DocstringParam, DocstringRaises, @@ -223,6 +225,44 @@ class DeprecationSection(_SphinxSection): ) +class ExamplesSection(Section): + """Parser for numpydoc examples sections. + + E.g. any section that looks like this: + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], # random + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], # random + [ 6586976, 22740995]]) + """ + + def parse(self, text: str) -> T.Iterable[DocstringMeta]: + """Parse ``DocstringExample`` objects from the body of this section. + + :param text: section body text. Should be cleaned with + ``inspect.cleandoc`` before parsing. + """ + lines = dedent(text).strip().splitlines() + while lines: + snippet_lines = [] + description_lines = [] + while lines: + if not lines[0].startswith(">>>"): + break + snippet_lines.append(lines.pop(0)) + while lines: + if lines[0].startswith(">>>"): + break + description_lines.append(lines.pop(0)) + yield DocstringExample( + [self.key], + snippet="\n".join(snippet_lines) if snippet_lines else None, + description="\n".join(description_lines), + ) + + DEFAULT_SECTIONS = [ ParamSection("Parameters", "param"), ParamSection("Params", "param"), @@ -244,8 +284,8 @@ DEFAULT_SECTIONS = [ ReturnsSection("Return", "returns"), YieldsSection("Yields", "yields"), YieldsSection("Yield", "yields"), - Section("Examples", "examples"), - Section("Example", "examples"), + ExamplesSection("Examples", "examples"), + ExamplesSection("Example", "examples"), Section("Warnings", "warnings"), Section("Warning", "warnings"), Section("See Also", "see_also"), diff --git a/pyproject.toml b/pyproject.toml index 76edebe..5136a22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -59,6 +59,7 @@ disable = [ "import-error", "duplicate-code", "too-many-locals", + "too-many-lines", "too-many-branches", "too-many-statements", "too-many-arguments",
rr-/docstring_parser
ba7c874cd7bb483f9af4c9fdd2e0f3c68f446e0a
diff --git a/docstring_parser/tests/test_numpydoc.py b/docstring_parser/tests/test_numpydoc.py index 57c6ac6..60ef1c9 100644 --- a/docstring_parser/tests/test_numpydoc.py +++ b/docstring_parser/tests/test_numpydoc.py @@ -660,20 +660,80 @@ def test_simple_sections() -> None: assert docstring.meta[3].args == ["references"] -def test_examples() -> None: [email protected]( + "source, expected_results", + [ + ( + "Description\nExamples\n--------\nlong example\n\nmore here", + [ + (None, "long example\n\nmore here"), + ], + ), + ( + "Description\nExamples\n--------\n>>> test", + [ + (">>> test", ""), + ], + ), + ( + "Description\nExamples\n--------\n>>> testa\n>>> testb", + [ + (">>> testa\n>>> testb", ""), + ], + ), + ( + "Description\nExamples\n--------\n>>> test1\ndesc1", + [ + (">>> test1", "desc1"), + ], + ), + ( + "Description\nExamples\n--------\n" + ">>> test1a\n>>> test1b\ndesc1a\ndesc1b", + [ + (">>> test1a\n>>> test1b", "desc1a\ndesc1b"), + ], + ), + ( + "Description\nExamples\n--------\n" + ">>> test1\ndesc1\n>>> test2\ndesc2", + [ + (">>> test1", "desc1"), + (">>> test2", "desc2"), + ], + ), + ( + "Description\nExamples\n--------\n" + ">>> test1a\n>>> test1b\ndesc1a\ndesc1b\n" + ">>> test2a\n>>> test2b\ndesc2a\ndesc2b\n", + [ + (">>> test1a\n>>> test1b", "desc1a\ndesc1b"), + (">>> test2a\n>>> test2b", "desc2a\ndesc2b"), + ], + ), + ( + "Description\nExamples\n--------\n" + " >>> test1a\n >>> test1b\n desc1a\n desc1b\n" + " >>> test2a\n >>> test2b\n desc2a\n desc2b\n", + [ + (">>> test1a\n>>> test1b", "desc1a\ndesc1b"), + (">>> test2a\n>>> test2b", "desc2a\ndesc2b"), + ], + ), + ], +) +def test_examples( + source, expected_results: T.List[T.Tuple[T.Optional[str], str]] +) -> None: """Test parsing examples.""" - docstring = parse( - """ - Short description - Examples - -------- - long example - - more here - """ - ) - assert len(docstring.meta) == 1 - assert docstring.meta[0].description == "long example\n\nmore here" + docstring = parse(source) + assert len(docstring.meta) == len(expected_results) + for meta, expected_result in zip(docstring.meta, expected_results): + assert meta.description == expected_result[1] + assert len(docstring.examples) == len(expected_results) + for example, expected_result in zip(docstring.examples, expected_results): + assert example.snippet == expected_result[0] + assert example.description == expected_result[1] @pytest.mark.parametrize( @@ -944,6 +1004,32 @@ def test_deprecation( " ValueError\n" " description", ), + ( + """ + Description + Examples: + -------- + >>> test1a + >>> test1b + desc1a + desc1b + >>> test2a + >>> test2b + desc2a + desc2b + """, + "Description\n" + "Examples:\n" + "--------\n" + ">>> test1a\n" + ">>> test1b\n" + "desc1a\n" + "desc1b\n" + ">>> test2a\n" + ">>> test2b\n" + "desc2a\n" + "desc2b", + ), ], ) def test_compose(source: str, expected: str) -> None:
Examples attribute is empty when using numpydoc parser https://github.com/rr-/docstring_parser/blob/ba7c874cd7bb483f9af4c9fdd2e0f3c68f446e0a/docstring_parser/common.py#L206 This often returns empty when using the numpydoc parser because the type of example is DocstringMeta, not child class DocstringExample.
0.0
ba7c874cd7bb483f9af4c9fdd2e0f3c68f446e0a
[ "docstring_parser/tests/test_numpydoc.py::test_examples[Description\\nExamples\\n--------\\nlong", "docstring_parser/tests/test_numpydoc.py::test_examples[Description\\nExamples\\n--------\\n>>>", "docstring_parser/tests/test_numpydoc.py::test_examples[Description\\nExamples\\n--------\\n" ]
[ "docstring_parser/tests/test_numpydoc.py::test_short_description[-None]", "docstring_parser/tests/test_numpydoc.py::test_short_description[\\n-None]", "docstring_parser/tests/test_numpydoc.py::test_short_description[Short", "docstring_parser/tests/test_numpydoc.py::test_short_description[\\nShort", "docstring_parser/tests/test_numpydoc.py::test_short_description[\\n", "docstring_parser/tests/test_numpydoc.py::test_long_description[Short", "docstring_parser/tests/test_numpydoc.py::test_long_description[\\n", "docstring_parser/tests/test_numpydoc.py::test_long_description[\\nShort", "docstring_parser/tests/test_numpydoc.py::test_meta_newlines[\\n", "docstring_parser/tests/test_numpydoc.py::test_meta_with_multiline_description", "docstring_parser/tests/test_numpydoc.py::test_default_args", "docstring_parser/tests/test_numpydoc.py::test_multiple_meta", "docstring_parser/tests/test_numpydoc.py::test_params", "docstring_parser/tests/test_numpydoc.py::test_attributes", "docstring_parser/tests/test_numpydoc.py::test_other_params", "docstring_parser/tests/test_numpydoc.py::test_yields", "docstring_parser/tests/test_numpydoc.py::test_returns", "docstring_parser/tests/test_numpydoc.py::test_raises", "docstring_parser/tests/test_numpydoc.py::test_warns", "docstring_parser/tests/test_numpydoc.py::test_simple_sections", "docstring_parser/tests/test_numpydoc.py::test_deprecation[Short", "docstring_parser/tests/test_numpydoc.py::test_compose[-]", "docstring_parser/tests/test_numpydoc.py::test_compose[\\n-]", "docstring_parser/tests/test_numpydoc.py::test_compose[Short", "docstring_parser/tests/test_numpydoc.py::test_compose[\\nShort", "docstring_parser/tests/test_numpydoc.py::test_compose[\\n" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-25 09:12:10+00:00
mit
5,298
rr-__screeninfo-61
diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2dc8643 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,6 @@ +# 0.8 (2021-12-04) + +- Started tracking changes +- Switched to poetry +- Added ignoring of enumerators that work, but return no valid monitors +- Added `ScreenInfoError` to list of top-level symbols diff --git a/pyproject.toml b/pyproject.toml index e87056b..534ceab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "screeninfo" -version = "0.7" +version = "0.8" description = "Fetch location and size of physical screens." authors = ["Marcin Kurczewski <[email protected]>"] license = "MIT" diff --git a/screeninfo/__init__.py b/screeninfo/__init__.py index ad1968a..2163dd4 100644 --- a/screeninfo/__init__.py +++ b/screeninfo/__init__.py @@ -1,2 +1,9 @@ from .common import Enumerator, Monitor -from .screeninfo import get_monitors +from .screeninfo import ScreenInfoError, get_monitors + +__all__ = [ + "Enumerator", + "Monitor", + "ScreenInfoError", + "get_monitors", +] diff --git a/screeninfo/screeninfo.py b/screeninfo/screeninfo.py index 01ec49a..e10bb39 100644 --- a/screeninfo/screeninfo.py +++ b/screeninfo/screeninfo.py @@ -13,23 +13,20 @@ ENUMERATOR_MAP = { } -def _get_monitors(enumerator: Enumerator) -> T.List[Monitor]: - return list(ENUMERATOR_MAP[enumerator].enumerate_monitors()) - - def get_monitors( name: T.Union[Enumerator, str, None] = None ) -> T.List[Monitor]: """Returns a list of :class:`Monitor` objects based on active monitors.""" - enumerator = Enumerator(name) if name is not None else None + if name is not None: + return list(ENUMERATOR_MAP[Enumerator(name)].enumerate_monitors()) - if enumerator is not None: - return _get_monitors(enumerator) - - for enumerator in Enumerator: + for enumerator in ENUMERATOR_MAP.keys(): try: - return _get_monitors(enumerator) - except Exception: - pass + monitors = get_monitors(enumerator) + except Exception as ex: + monitors = [] + + if monitors: + return monitors raise ScreenInfoError("No enumerators available")
rr-/screeninfo
9e6cc2208d86976e7c7a503ef9f88d278c9753c9
diff --git a/screeninfo/test_screeninfo.py b/screeninfo/test_screeninfo.py index a30dfb5..26040ef 100644 --- a/screeninfo/test_screeninfo.py +++ b/screeninfo/test_screeninfo.py @@ -1,8 +1,9 @@ from contextlib import contextmanager +from unittest import mock import pytest -from screeninfo import get_monitors +from screeninfo import Enumerator, Monitor, ScreenInfoError, get_monitors @contextmanager @@ -13,11 +14,131 @@ def not_raises(exception): raise pytest.fail("DID RAISE {0}".format(exception)) -def test_get_monitors_does_not_raise(): - with not_raises(Exception): - list(get_monitors()) +def test_get_monitors_without_enumerators(): + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", {} + ) as mock_get_monitors: + with pytest.raises(ScreenInfoError): + get_monitors() -def test_get_monitors_has_at_least_one_monitor(): - # GitHub actions have no physical monitors - assert len(list(get_monitors())) >= 0 +def test_get_monitors_handles_faulty_enumerator(): + enumerator = mock.Mock( + enumerate_monitors=mock.Mock(side_effect=ImportError) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ): + with pytest.raises(ScreenInfoError): + get_monitors() + enumerator.enumerate_monitors.assert_called_once() + + +def test_get_monitors_ignores_enumerator_that_produces_no_results(): + enumerator = mock.Mock(enumerate_monitors=mock.Mock(return_value=[])) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ): + with pytest.raises(ScreenInfoError): + get_monitors() + enumerator.enumerate_monitors.assert_called_once() + + +def test_get_monitors_uses_working_enumerator(): + enumerator = mock.Mock( + enumerate_monitors=mock.Mock( + return_value=[Monitor(x=0, y=0, width=800, height=600)] + ) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ) as mock_get_monitors: + monitors = get_monitors() + assert len(monitors) == 1 + assert monitors[0].x == 0 + assert monitors[0].y == 0 + assert monitors[0].width == 800 + assert monitors[0].height == 600 + enumerator.enumerate_monitors.assert_called_once() + + +def test_get_monitors_uses_first_working_enumerator(): + enumerator1 = mock.Mock( + enumerate_monitors=mock.Mock(side_effect=ImportError) + ) + enumerator2 = mock.Mock( + enumerate_monitors=mock.Mock( + return_value=[Monitor(x=0, y=0, width=800, height=600)] + ) + ) + enumerator3 = mock.Mock( + enumerate_monitors=mock.Mock(side_effect=ImportError) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + { + Enumerator.Windows: enumerator1, + Enumerator.Xinerama: enumerator2, + Enumerator.DRM: enumerator3, + }, + ) as mock_get_monitors: + monitors = get_monitors() + assert len(monitors) == 1 + assert monitors[0].x == 0 + assert monitors[0].y == 0 + assert monitors[0].width == 800 + assert monitors[0].height == 600 + enumerator1.enumerate_monitors.assert_called_once() + enumerator2.enumerate_monitors.assert_called_once() + enumerator3.enumerate_monitors.assert_not_called() + + [email protected]("param", ["windows", Enumerator.Windows]) +def test_get_monitors_with_concrete_enumerator(param): + enumerator = mock.Mock( + enumerate_monitors=mock.Mock( + return_value=[Monitor(x=0, y=0, width=800, height=600)] + ) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ) as mock_get_monitors: + monitors = get_monitors(param) + assert len(monitors) == 1 + assert monitors[0].x == 0 + assert monitors[0].y == 0 + assert monitors[0].width == 800 + assert monitors[0].height == 600 + enumerator.enumerate_monitors.assert_called_once() + + +def test_get_monitors_with_invalid_enumerator(): + enumerator = mock.Mock( + enumerate_monitors=mock.Mock( + return_value=[Monitor(x=0, y=0, width=800, height=600)] + ) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ) as mock_get_monitors: + with pytest.raises(ValueError): + monitors = get_monitors("Invalid") + + +def test_get_monitors_with_unlisted_enumerator(): + enumerator = mock.Mock( + enumerate_monitors=mock.Mock( + return_value=[Monitor(x=0, y=0, width=800, height=600)] + ) + ) + with mock.patch( + "screeninfo.screeninfo.ENUMERATOR_MAP", + {Enumerator.Windows: enumerator}, + ) as mock_get_monitors: + with pytest.raises(KeyError): + monitors = get_monitors(Enumerator.OSX)
get_monitors returns empty on osx when Enumerator not explicitly provided tl;dr: ```py >>> from screeninfo import get_monitors, Enumerator >>> get_monitors() [] >>> get_monitors(Enumerator.OSX) [Monitor(x=0, y=0, width=1680, height=1050, width_mm=None, height_mm=None, name=None)] ``` On those lines: https://github.com/rr-/screeninfo/blob/master/screeninfo/screeninfo.py#L29-L33 ```py for enumerator in Enumerator: try: return _get_monitors(enumerator) except Exception: pass ``` Seems some of the previous enumerator is not raising, so it returns before trying OSX, one solution is to also check for empty return on that try/catch
0.0
9e6cc2208d86976e7c7a503ef9f88d278c9753c9
[ "screeninfo/test_screeninfo.py::test_get_monitors_without_enumerators", "screeninfo/test_screeninfo.py::test_get_monitors_handles_faulty_enumerator", "screeninfo/test_screeninfo.py::test_get_monitors_ignores_enumerator_that_produces_no_results", "screeninfo/test_screeninfo.py::test_get_monitors_uses_working_enumerator", "screeninfo/test_screeninfo.py::test_get_monitors_uses_first_working_enumerator", "screeninfo/test_screeninfo.py::test_get_monitors_with_concrete_enumerator[windows]", "screeninfo/test_screeninfo.py::test_get_monitors_with_concrete_enumerator[Enumerator.Windows]", "screeninfo/test_screeninfo.py::test_get_monitors_with_invalid_enumerator", "screeninfo/test_screeninfo.py::test_get_monitors_with_unlisted_enumerator" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-12-03 17:43:50+00:00
mit
5,299
rsalmei__alive-progress-47
diff --git a/alive_progress/__init__.py b/alive_progress/__init__.py index 6e364dd..f0e16c0 100644 --- a/alive_progress/__init__.py +++ b/alive_progress/__init__.py @@ -12,7 +12,7 @@ from .core.progress import alive_bar from .styles.exhibit import print_chars, show_bars, show_spinners, showtime from .styles.internal import BARS, SPINNERS, THEMES -VERSION = (1, 6, 0) +VERSION = (1, 6, 1) __author__ = 'Rogério Sampaio de Almeida' __email__ = '[email protected]' diff --git a/alive_progress/core/logging_hook.py b/alive_progress/core/logging_hook.py index 1ffa0b4..21570ea 100644 --- a/alive_progress/core/logging_hook.py +++ b/alive_progress/core/logging_hook.py @@ -1,12 +1,31 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + import logging import sys -def install_logging_hook(): # pragma: no cover +def install_logging_hook(): root = logging.root - return {h: h.setStream(sys.stdout) for h in root.handlers - if isinstance(h, logging.StreamHandler)} + return {h: set_stream(h, sys.stdout) for h in root.handlers # noqa + if h.__class__ == logging.StreamHandler} # want only this, not its subclasses. + + +def uninstall_logging_hook(before): + [set_stream(h, s) for h, s in before.items()] -def uninstall_logging_hook(before): # pragma: no cover - [h.setStream(s) for h, s in before.items()] +if sys.version_info >= (3, 7): + def set_stream(handler, stream): + return handler.setStream(stream) +else: # pragma: no cover + def set_stream(handler, stream): + # from python 3.7 implementation. + result = handler.stream + handler.acquire() + try: + handler.flush() + handler.stream = stream + finally: + handler.release() + return result diff --git a/alive_progress/core/progress.py b/alive_progress/core/progress.py index 3848d16..00f95b9 100644 --- a/alive_progress/core/progress.py +++ b/alive_progress/core/progress.py @@ -12,8 +12,8 @@ from itertools import chain, islice, repeat from .configuration import config_handler from .logging_hook import install_logging_hook, uninstall_logging_hook from .timing import gen_simple_exponential_smoothing_eta, to_elapsed_text, to_eta_text -from .utils import clear_traces, hide_cursor, render_title, sanitize_text, show_cursor, \ - terminal_columns +from .utils import clear_traces, hide_cursor, render_title, sanitize_text_marking_wide_chars, \ + show_cursor, terminal_columns from ..animations.utils import spinner_player @@ -107,7 +107,7 @@ def alive_bar(total=None, title=None, calibrate=None, **options): line = ' '.join(filter(None, ( title, bar_repr(run.percent, end), spin, monitor(), 'in', - to_elapsed_text(elapsed, end), run.stats(), run.text))) + to_elapsed_text(elapsed, end), stats(), run.text))) line_len, cols = len(line), terminal_columns() with print_lock: @@ -123,7 +123,7 @@ def alive_bar(total=None, title=None, calibrate=None, **options): print() def set_text(message): - run.text = sanitize_text(message) + run.text = sanitize_text_marking_wide_chars(message) if config.manual: # FIXME update bar signatures and remove deprecated in v2. @@ -219,7 +219,6 @@ def alive_bar(total=None, title=None, calibrate=None, **options): stats = lambda: spec.format(run.rate, to_eta_text(gen_eta.send((current(), run.rate)))) bar_repr = config.bar(config.length) else: # unknown progress. - eta_text = lambda: None # noqa bar_repr = config.unknown(config.length, config.bar) stats = lambda: '({:.1f}/s)'.format(run.rate) # noqa stats_end = lambda: '({:.2{}}/s)'.format(run.rate, rate_spec) # noqa @@ -245,9 +244,8 @@ def alive_bar(total=None, title=None, calibrate=None, **options): return math.log10((run.rate * adjust_log_curve) + 1.) * factor + min_fps return max_fps - end, run.text, run.eta_text, run.stats = False, '', '', stats - run.count, run.last_line_len = 0, 0 - run.percent, run.rate, run.init = 0., 0., 0. + end, run.text, run.last_line_len = False, '', 0 + run.count, run.percent, run.rate, run.init = 0, 0., 0., 0. if total: if config.manual: @@ -282,5 +280,5 @@ def alive_bar(total=None, title=None, calibrate=None, **options): thread = None # lets the internal thread terminate gracefully. local_copy.join() - end, run.text, run.stats = True, '', stats_end + end, run.text, stats = True, '', stats_end alive_repr() diff --git a/alive_progress/core/utils.py b/alive_progress/core/utils.py index 771c091..4f6b19e 100644 --- a/alive_progress/core/utils.py +++ b/alive_progress/core/utils.py @@ -3,6 +3,10 @@ from __future__ import absolute_import, division, print_function, unicode_litera import os import sys +import unicodedata +from itertools import chain + +ZWJ = '\u200d' # zero-width joiner (it's the only one that actually worked on my terminal) def clear_traces(): # pragma: no cover @@ -20,18 +24,23 @@ def show_cursor(): # pragma: no cover sys.__stdout__.write('\033[?25h') -def sanitize_text(text): - return ' '.join(str(text).split()) +def sanitize_text_marking_wide_chars(text): + text = ' '.join((text or '').split()) + return ''.join(chain.from_iterable( + (ZWJ, x) if unicodedata.east_asian_width(x) == 'W' else (x,) + for x in text)) def render_title(title, length): if not title: return '' - elif not length: - return title elif length == 1: return '…' + title = sanitize_text_marking_wide_chars(title) + if not length: + return title + # fixed size left align implementation. # there may be more in v2, like other alignments, variable with maximum size, and # even scrolling and bouncing. diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 0000000..d366a5b --- /dev/null +++ b/noxfile.py @@ -0,0 +1,6 @@ +import nox + [email protected](python=["2.7", "3.5", "3.6", "3.7", "3.8"]) +def tests(session): + session.install('-r', 'requirements/test.txt') + session.run('pytest')
rsalmei/alive-progress
37dca0225a6d4c8207dc34c7d1b691db2d7616bd
diff --git a/requirements/test.txt b/requirements/test.txt index f2fa609..c6cc811 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,5 +1,4 @@ pytest pytest-cov pytest-sugar -pytest-watch mock; python_version < '3' diff --git a/tests/core/test_logging_hook.py b/tests/core/test_logging_hook.py new file mode 100644 index 0000000..02ea23f --- /dev/null +++ b/tests/core/test_logging_hook.py @@ -0,0 +1,32 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +import logging +import sys + +import pytest + +from alive_progress.core.logging_hook import install_logging_hook, uninstall_logging_hook + + [email protected] +def all_handlers(): + handler = logging.StreamHandler(sys.stderr) + nope = logging.FileHandler('/dev/null', delay=True) + [logging.root.addHandler(h) for h in (handler, nope)] + yield handler, nope + [logging.root.removeHandler(h) for h in (handler, nope)] + + +def test_install(all_handlers): + handler, nope = all_handlers + changed = install_logging_hook() + assert handler.stream == sys.stdout + assert nope.stream is None + assert changed == {handler: sys.stderr} + + +def test_uninstall(all_handlers): + handler, _ = all_handlers + uninstall_logging_hook({handler: sys.stderr}) + assert handler.stream == sys.stderr diff --git a/tests/core/test_utils.py b/tests/core/test_utils.py index 07be92f..1620500 100644 --- a/tests/core/test_utils.py +++ b/tests/core/test_utils.py @@ -1,22 +1,48 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function, unicode_literals +import sys + import pytest -from alive_progress.core.utils import render_title, sanitize_text +from alive_progress.core.utils import render_title, sanitize_text_marking_wide_chars, ZWJ @pytest.mark.parametrize('text, expected', [ ('', ''), - (None, 'None'), + (None, ''), ('\n', ''), + (' \n ', ''), + ('\n \n', ''), ('asd\n', 'asd'), ('\nasd', 'asd'), ('asd1\nasd2', 'asd1 asd2'), ('\nasd1\n\n\nasd2\n', 'asd1 asd2'), ]) -def test_sanitize_text(text, expected): - assert sanitize_text(text) == expected +def test_sanitize_text_normal_chars(text, expected): + result = sanitize_text_marking_wide_chars(text) + assert result.replace(ZWJ, 'X') == expected + + +if sys.version_info >= (3, 6): + # 2.7 doesn't mark those chars as Wide (ucd 5.2), so this test fails. + # -> but curiously it does work in terminal, since they are encoded with 2 bytes. + # 3.5 doesn't mark those chars as Wide either (ucd 8.0), so this test also fails. + # -> and here it doesn't work in terminal, since they are encoded with 1 byte. + # more details in https://github.com/rsalmei/alive-progress/issues/19#issuecomment-657120695 + @pytest.mark.parametrize('text, expected', [ + ('😺', 'X😺'), + ('\n😺', 'X😺'), + ('😺 \n 😺', 'X😺 X😺'), + ('\n 😺\n😺', 'X😺 X😺'), + ('asd😺\n', 'asdX😺'), + ('😺\nasd', 'X😺 asd'), + ('asd1\nasd2😺', 'asd1 asd2X😺'), + ('\nasd1😺\n😺\n\nasd2\n', 'asd1X😺 X😺 asd2'), + ]) + def test_sanitize_text_wide_chars(text, expected): + result = sanitize_text_marking_wide_chars(text) + assert result.replace(ZWJ, 'X') == expected @pytest.mark.parametrize('text, length, expected', [
Use with logging module In my module, I use the python logging module to print out messages. During the operation which I want to monitor using alive-progress it may happen that messages are sent out using the logging module. Then, artifacts of the bar remain in the console: ``` Loading the fmu took 0.34800148010253906 s. Starting simulation at t=0.0 s. | ▁▃▅ 0/1000 [0%] in 0s (0.0/s, eta: ?) Simulation took 0.7570006847381592 s.███▌| ▅▇▇ 990/1000 [99%] in 0s (1126.2/s, eta: 0s) Simulation finished at t=1000.0 s. |████████████████████████████████████████| 1000/1000 [100%] in 0.9s (1096.43/s) ``` The first message ("loading ... took ...") was logged before i instantiated the alive bar. The other messages were emitted while the bar was active. I am using a vanilla StreamHandler that sends everything to stdout. By the way - dunno if that's possible - is it possible to have the alive bar redirected to a logging module, too? Might be interesting to have the complete (or not, in case of an error!) progress bar in a log file. Gives structure... By the way 2: it's pretty awesome :) Cheers, Jan
0.0
37dca0225a6d4c8207dc34c7d1b691db2d7616bd
[ "tests/core/test_logging_hook.py::test_install", "tests/core/test_logging_hook.py::test_uninstall", "tests/core/test_utils.py::test_sanitize_text_normal_chars[-]", "tests/core/test_utils.py::test_sanitize_text_normal_chars[None-]", "tests/core/test_utils.py::test_sanitize_text_normal_chars[\\n-]", "tests/core/test_utils.py::test_sanitize_text_normal_chars[", "tests/core/test_utils.py::test_sanitize_text_normal_chars[\\n", "tests/core/test_utils.py::test_sanitize_text_normal_chars[asd\\n-asd]", "tests/core/test_utils.py::test_sanitize_text_normal_chars[\\nasd-asd]", "tests/core/test_utils.py::test_sanitize_text_normal_chars[asd1\\nasd2-asd1", "tests/core/test_utils.py::test_sanitize_text_normal_chars[\\nasd1\\n\\n\\nasd2\\n-asd1", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\U0001f63a-X\\U0001f63a]", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\n\\U0001f63a-X\\U0001f63a]", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\U0001f63a", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\n", "tests/core/test_utils.py::test_sanitize_text_wide_chars[asd\\U0001f63a\\n-asdX\\U0001f63a]", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\U0001f63a\\nasd-X\\U0001f63a", "tests/core/test_utils.py::test_sanitize_text_wide_chars[asd1\\nasd2\\U0001f63a-asd1", "tests/core/test_utils.py::test_sanitize_text_wide_chars[\\nasd1\\U0001f63a\\n\\U0001f63a\\n\\nasd2\\n-asd1X\\U0001f63a", "tests/core/test_utils.py::test_render_title[None-0-]", "tests/core/test_utils.py::test_render_title[-0-]", "tests/core/test_utils.py::test_render_title[cool" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-11 20:07:30+00:00
mit
5,300
rsheftel__pandas_market_calendars-183
diff --git a/pandas_market_calendars/calendar_registry.py b/pandas_market_calendars/calendar_registry.py index 5ea2e60..21ea581 100644 --- a/pandas_market_calendars/calendar_registry.py +++ b/pandas_market_calendars/calendar_registry.py @@ -9,6 +9,7 @@ from .exchange_calendar_cme import \ from .exchange_calendar_eurex import EUREXExchangeCalendar from .exchange_calendar_hkex import HKEXExchangeCalendar from .exchange_calendar_ice import ICEExchangeCalendar +from .exchange_calendar_iex import IEXExchangeCalendar from .exchange_calendar_jpx import JPXExchangeCalendar from .exchange_calendar_lse import LSEExchangeCalendar from .exchange_calendar_nyse import NYSEExchangeCalendar diff --git a/pandas_market_calendars/exchange_calendar_iex.py b/pandas_market_calendars/exchange_calendar_iex.py new file mode 100644 index 0000000..b1a12ca --- /dev/null +++ b/pandas_market_calendars/exchange_calendar_iex.py @@ -0,0 +1,99 @@ +from datetime import time +from itertools import chain +from .exchange_calendar_nyse import NYSEExchangeCalendar +from pandas.tseries.holiday import AbstractHolidayCalendar +from pytz import timezone + +from pandas_market_calendars.holidays_nyse import ( + USPresidentsDay, + GoodFriday, + USMemorialDay, + USJuneteenthAfter2022, + USIndependenceDay, + USThanksgivingDay, + ChristmasNYSE, + USMartinLutherKingJrAfter1998, + + #Ad-Hoc + DayAfterThanksgiving1pmEarlyCloseInOrAfter1993, + DaysBeforeIndependenceDay1pmEarlyCloseAdhoc, + ChristmasEvesAdhoc, +) + +class IEXExchangeCalendar(NYSEExchangeCalendar): + """ + Exchange calendar for the Investor's Exchange (IEX). + + IEX is an equities exchange, based in New York City, US + that integrates proprietary technology to facilitate fair + play between HFT firms and retail investors. + + Most of this class inherits from NYSEExchangeCalendar since + the holdiays are the same. The only variation is (1) IEX began + operation in 2013, and (2) IEX has different hours of operation + + References: + - https://exchange.iex.io/ + - https://iexexchange.io/resources/trading/trading-hours-holidays/index.html + """ + + regular_market_times = { + "pre": (('2013-03-25', time(8)),), + "market_open": ((None, time(9, 30)),), + "market_close":((None, time(16)),), + "post": ((None, time(17)),) + } + + aliases = ['IEX', 'Investors_Exchange'] + + @property + def name(self): + return "IEX" + + @property + def weekmask(self): + return "Mon Tue Wed Thu Fri" + + @property + def regular_holidays(self): + return AbstractHolidayCalendar(rules=[ + USPresidentsDay, + GoodFriday, + USMemorialDay, + USJuneteenthAfter2022, + USIndependenceDay, + USThanksgivingDay, + ChristmasNYSE, + USMartinLutherKingJrAfter1998 + ]) + + @property + def adhoc_holidays(self): + return list(chain( + ChristmasEvesAdhoc, + )) + + @property + def special_closes(self): + return [ + (time(hour=13, tzinfo=timezone('America/New_York')), AbstractHolidayCalendar(rules=[ + DayAfterThanksgiving1pmEarlyCloseInOrAfter1993, + ])) + ] + + """Override NYSE calendar special cases""" + + @property + def special_closes_adhoc(self): + return [ + (time(13, tzinfo=timezone('America/New_York')), + DaysBeforeIndependenceDay1pmEarlyCloseAdhoc) + ] + + @property + def special_opens(self): + return [] + + def valid_days(self, start_date, end_date, tz='UTC'): + trading_days = super().valid_days(start_date, end_date, tz=tz) #all NYSE valid days + return trading_days[~(trading_days <= '2013-08-25')]
rsheftel/pandas_market_calendars
78f7ef1905d807f0b9f261bb6db743976ba9dbf2
diff --git a/tests/test_iex_calendar.py b/tests/test_iex_calendar.py new file mode 100644 index 0000000..c6d325f --- /dev/null +++ b/tests/test_iex_calendar.py @@ -0,0 +1,35 @@ +import pandas as pd +import numpy as np +from datetime import time +from pytz import timezone +from pandas_market_calendars.exchange_calendar_iex import IEXExchangeCalendar +from pandas_market_calendars.class_registry import _ProtectedDict + +iex = IEXExchangeCalendar() + +def test_time_zone(): + assert iex.tz == timezone("America/New_York") + assert iex.name == "IEX" + + +def test_open_close(): + assert iex.open_time == time(9, 30, tzinfo=timezone('America/New_York')) + assert iex.close_time == time(16, tzinfo=timezone('America/New_York')) + + +def test_calendar_utility(): + assert len(iex.holidays().holidays) > 0 + assert isinstance(iex.regular_market_times, _ProtectedDict) + + valid_days = iex.valid_days(start_date='2016-12-20', end_date='2017-01-10') + assert isinstance(valid_days, pd.DatetimeIndex) + assert not valid_days.empty + + schedule = iex.schedule(start_date='2015-07-01', end_date='2017-07-10', start="pre", end="post") + assert isinstance(schedule, pd.DataFrame) + assert not schedule.empty + + +def test_trading_days_before_operation(): + trading_days = iex.valid_days(start_date="2000-01-01", end_date="2022-02-23") + assert np.array([~(trading_days <= '2013-08-25')]).any()
IEX Integration Any plans / blocks with adding integration for [IEX's](https://exchange.iex.io/) trading calendar? Haven't ever seen them deviate from NYSE but would be nice to have. If there are no objections I will submit a PR for this integration.
0.0
78f7ef1905d807f0b9f261bb6db743976ba9dbf2
[ "tests/test_iex_calendar.py::test_time_zone", "tests/test_iex_calendar.py::test_open_close", "tests/test_iex_calendar.py::test_calendar_utility", "tests/test_iex_calendar.py::test_trading_days_before_operation" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2022-02-24 22:48:03+00:00
mit
5,301
rshk__python-pcapng-42
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 639d96b..daa8599 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,7 +12,7 @@ repos: additional_dependencies: - toml - repo: https://github.com/psf/black - rev: 20.8b1 + rev: 22.3.0 hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 740b4f7..c1ce622 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,11 @@ History ####### +Unreleased +========== + +- Use the explicit endianness everywhere when writing. + v0.1 ==== diff --git a/examples/dump_tcpip_stats.py b/examples/dump_tcpip_stats.py index 590300b..ecc0dff 100755 --- a/examples/dump_tcpip_stats.py +++ b/examples/dump_tcpip_stats.py @@ -34,7 +34,7 @@ def human_number(num, k=1000): assert isinstance(num, int) for i, suffix in enumerate(powers): if (num < (k ** (i + 1))) or (i == len(powers) - 1): - return "{0:d}{1}".format(int(round(num / (k ** i))), suffix) + return "{0:d}{1}".format(int(round(num / (k**i))), suffix) raise AssertionError("Should never reach this") diff --git a/pcapng/blocks.py b/pcapng/blocks.py index 0bc2cd0..2c9abab 100644 --- a/pcapng/blocks.py +++ b/pcapng/blocks.py @@ -54,7 +54,9 @@ class Block(object): for key, packed_type, default in self.schema: if key == "options": self._decoded[key] = Options( - schema=packed_type.options_schema, data={}, endianness="=" + schema=packed_type.options_schema, + data={}, + endianness=kwargs["endianness"], ) if "options" in kwargs: for oky, ovl in kwargs["options"].items(): @@ -83,10 +85,10 @@ class Block(object): block_length = 12 + subblock_length if subblock_length % 4 != 0: block_length += 4 - (subblock_length % 4) - write_int(self.magic_number, outstream, 32) - write_int(block_length, outstream, 32) + write_int(self.magic_number, outstream, 32, endianness=self.section.endianness) + write_int(block_length, outstream, 32, endianness=self.section.endianness) write_bytes_padded(outstream, encoded_block) - write_int(block_length, outstream, 32) + write_int(block_length, outstream, 32, endianness=self.section.endianness) def _encode(self, outstream): """Encodes the fields of this block into raw data""" diff --git a/pcapng/flags.py b/pcapng/flags.py index 06b3bbf..fcd6e88 100644 --- a/pcapng/flags.py +++ b/pcapng/flags.py @@ -84,14 +84,14 @@ class FlagEnum(FlagBase): "{cls} needs an iterable of values".format(cls=self.__class__.__name__) ) extra = list(extra) - if len(extra) > 2 ** size: + if len(extra) > 2**size: raise TypeError( "{cls} iterable has too many values (got {got}, " "{size} bits only address {max})".format( cls=self.__class__.__name__, got=len(extra), size=size, - max=2 ** size, + max=2**size, ) )
rshk/python-pcapng
cd0f197c24b7864c50f13f976ed3b95d89ffc818
diff --git a/tests/test_parse_enhanced_packet.py b/tests/test_parse_enhanced_packet.py index 7cabb62..f344b38 100644 --- a/tests/test_parse_enhanced_packet.py +++ b/tests/test_parse_enhanced_packet.py @@ -93,7 +93,7 @@ def test_read_block_enhanced_packet_bigendian(): def _generate_file_with_tsresol(base, exponent): tsresol = pack_timestamp_resolution(base, exponent) base_timestamp = 1420070400.0 # 2015-01-01 00:00 UTC - timestamp = base_timestamp / (base ** exponent) + timestamp = base_timestamp / (base**exponent) stream = io.BytesIO() @@ -167,6 +167,6 @@ def test_read_block_enhanced_packet_tsresol_bigendian(tsr_base, tsr_exp): assert blocks[2].interface_id == 0 assert blocks[2].interface == blocks[1] - resol = tsr_base ** tsr_exp + resol = tsr_base**tsr_exp assert blocks[2].timestamp_resolution == resol assert blocks[2].timestamp == 1420070400.0 diff --git a/tests/test_parse_wireshark_capture_files.py b/tests/test_parse_wireshark_capture_files.py index 85a9e6a..97a0d3e 100644 --- a/tests/test_parse_wireshark_capture_files.py +++ b/tests/test_parse_wireshark_capture_files.py @@ -105,7 +105,7 @@ def test_sample_test005_ntar(): blocks[1].options.get_raw("if_speed") == b"\x00\xe4\x0b\x54\x02\x00\x00\x00" ) # noqa assert blocks[1].options["if_speed"] == 0x00000002540BE400 - assert blocks[1].options["if_speed"] == (10 ** 10) # 10Gbit + assert blocks[1].options["if_speed"] == (10**10) # 10Gbit assert blocks[1].options["if_description"] == "Stupid ethernet interface\x00" @@ -143,7 +143,7 @@ def test_sample_test006_ntar(filename): assert blocks[1].snaplen == 96 assert len(blocks[1].options) == 2 - assert blocks[1].options["if_speed"] == (10 ** 8) # 100Mbit + assert blocks[1].options["if_speed"] == (10**8) # 100Mbit assert blocks[1].options["if_description"] == "Stupid ethernet interface\x00" diff --git a/tests/test_utils.py b/tests/test_utils.py index eb848c0..c774434 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -38,9 +38,9 @@ def test_unpack_tsresol(): assert unpack_timestamp_resolution(bytes((100,))) == 1e-100 assert unpack_timestamp_resolution(bytes((0 | 0b10000000,))) == 1 - assert unpack_timestamp_resolution(bytes((1 | 0b10000000,))) == 2 ** -1 - assert unpack_timestamp_resolution(bytes((6 | 0b10000000,))) == 2 ** -6 - assert unpack_timestamp_resolution(bytes((100 | 0b10000000,))) == 2 ** -100 + assert unpack_timestamp_resolution(bytes((1 | 0b10000000,))) == 2**-1 + assert unpack_timestamp_resolution(bytes((6 | 0b10000000,))) == 2**-6 + assert unpack_timestamp_resolution(bytes((100 | 0b10000000,))) == 2**-100 def test_pack_tsresol(): diff --git a/tests/test_write_support.py b/tests/test_write_support.py index b193f2c..3387cc1 100644 --- a/tests/test_write_support.py +++ b/tests/test_write_support.py @@ -17,17 +17,19 @@ def compare_blocklists(list1, list2): assert list1[i] == list2[i], "block #{} mismatch".format(i) -def test_write_read_all_blocks(): [email protected]("endianness", ["<", ">"]) +def test_write_read_all_blocks(endianness): # Track the blocks we're writing out_blocks = [] # Build our original/output session o_shb = blocks.SectionHeader( + endianness=endianness, options={ "shb_hardware": "pytest", "shb_os": "python", "shb_userappl": "python-pcapng", - } + }, ) out_blocks.append(o_shb) @@ -129,7 +131,8 @@ def test_write_read_all_blocks(): compare_blocklists(in_blocks, out_blocks) -def test_spb_snap_lengths(): [email protected]("endianness", ["<", ">"]) +def test_spb_snap_lengths(endianness): """ Simple Packet Blocks present a unique challenge in parsing. The packet does not contain an explicit "captured length" indicator, only the original observed @@ -147,7 +150,7 @@ def test_spb_snap_lengths(): data = bytes(range(0, 256)) # First session: no snap length - o_shb = blocks.SectionHeader() + o_shb = blocks.SectionHeader(endianness=endianness) o_idb = o_shb.new_member(blocks.InterfaceDescription) # noqa: F841 o_blk1 = o_shb.new_member(blocks.SimplePacket, packet_data=data) @@ -162,7 +165,7 @@ def test_spb_snap_lengths(): assert i_blk1.packet_data == data # Second session: with snap length - o_shb = blocks.SectionHeader() + o_shb = blocks.SectionHeader(endianness=endianness) o_idb = o_shb.new_member(blocks.InterfaceDescription, snaplen=32) # noqa: F841 o_blk1 = o_shb.new_member(blocks.SimplePacket, packet_data=data[:16]) o_blk2 = o_shb.new_member(blocks.SimplePacket, packet_data=data[:32])
Cross-endian pcapng writing is incorrect I'm using pcapng to create test inputs for another system, and I tried to write a big-endian pcapng to make sure that big-endian files are handled correctly. I discovered that the block type and block length are written with native endianness even when the non-native endianness is requested by setting the endianness on the section header block. I will try to find some time to put together a PR fixing this.
0.0
cd0f197c24b7864c50f13f976ed3b95d89ffc818
[ "tests/test_write_support.py::test_write_read_all_blocks[>]", "tests/test_write_support.py::test_spb_snap_lengths[>]" ]
[ "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_bigendian", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[10--6]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[10-0]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[10--3]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[10--9]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[2-0]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[2--5]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[2--10]", "tests/test_parse_enhanced_packet.py::test_read_block_enhanced_packet_tsresol_bigendian[2--20]", "tests/test_parse_wireshark_capture_files.py::test_sample_test001_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test002_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test003_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test004_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test005_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test006_ntar[test_data/test006-fixed.ntar]", "tests/test_parse_wireshark_capture_files.py::test_sample_test007_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test008_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test009_ntar", "tests/test_parse_wireshark_capture_files.py::test_sample_test010_ntar", "tests/test_utils.py::test_unpack_ipv4", "tests/test_utils.py::test_unpack_ipv6", "tests/test_utils.py::test_unpack_macaddr", "tests/test_utils.py::test_unpack_euiaddr", "tests/test_utils.py::test_unpack_tsresol", "tests/test_utils.py::test_pack_tsresol", "tests/test_write_support.py::test_write_read_all_blocks[<]", "tests/test_write_support.py::test_spb_snap_lengths[<]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-05-13 23:30:59+00:00
apache-2.0
5,302
rthalley__dnspython-188
diff --git a/.travis.yml b/.travis.yml index 46a1b13..a88237d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,9 @@ python: - "3.5" - "3.5-dev" # 3.5 development branch - "nightly" # currently points to 3.6-dev +matrix: + allow_failures: + - python: nightly install: - pip install unittest2 pylint script: diff --git a/dns/name.py b/dns/name.py index ef812cf..5288e1e 100644 --- a/dns/name.py +++ b/dns/name.py @@ -488,9 +488,6 @@ class Name(object): def __getitem__(self, index): return self.labels[index] - def __getslice__(self, start, stop): - return self.labels[start:stop] - def __add__(self, other): return self.concatenate(other) diff --git a/dns/resolver.py b/dns/resolver.py index 5bd1e8d..c9a7c78 100644 --- a/dns/resolver.py +++ b/dns/resolver.py @@ -282,9 +282,6 @@ class Answer(object): def __delitem__(self, i): del self.rrset[i] - def __getslice__(self, i, j): - return self.rrset[i:j] - class Cache(object): diff --git a/dns/set.py b/dns/set.py index 0efc7d9..ef7fd29 100644 --- a/dns/set.py +++ b/dns/set.py @@ -232,9 +232,6 @@ class Set(object): def __delitem__(self, i): del self.items[i] - def __getslice__(self, i, j): - return self.items[i:j] - def issubset(self, other): """Is I{self} a subset of I{other}? diff --git a/dns/wiredata.py b/dns/wiredata.py index b381f7b..ccef595 100644 --- a/dns/wiredata.py +++ b/dns/wiredata.py @@ -15,6 +15,7 @@ """DNS Wire Data Helper""" +import sys import dns.exception from ._compat import binary_type, string_types @@ -26,12 +27,16 @@ from ._compat import binary_type, string_types # out what constant Python will use. -class _SliceUnspecifiedBound(str): +class _SliceUnspecifiedBound(binary_type): - def __getslice__(self, i, j): - return j + def __getitem__(self, key): + return key.stop + + if sys.version_info < (3,): + def __getslice__(self, i, j): # pylint: disable=getslice-method + return self.__getitem__(slice(i, j)) -_unspecified_bound = _SliceUnspecifiedBound('')[1:] +_unspecified_bound = _SliceUnspecifiedBound()[1:] class WireData(binary_type): @@ -40,26 +45,40 @@ class WireData(binary_type): def __getitem__(self, key): try: if isinstance(key, slice): - return WireData(super(WireData, self).__getitem__(key)) + # make sure we are not going outside of valid ranges, + # do stricter control of boundaries than python does + # by default + start = key.start + stop = key.stop + + if sys.version_info < (3,): + if stop == _unspecified_bound: + # handle the case where the right bound is unspecified + stop = len(self) + + if start < 0 or stop < 0: + raise dns.exception.FormError + # If it's not an empty slice, access left and right bounds + # to make sure they're valid + if start != stop: + super(WireData, self).__getitem__(start) + super(WireData, self).__getitem__(stop - 1) + else: + for index in (start, stop): + if index is None: + continue + elif abs(index) > len(self): + raise dns.exception.FormError + + return WireData(super(WireData, self).__getitem__( + slice(start, stop))) return bytearray(self.unwrap())[key] except IndexError: raise dns.exception.FormError - def __getslice__(self, i, j): - try: - if j == _unspecified_bound: - # handle the case where the right bound is unspecified - j = len(self) - if i < 0 or j < 0: - raise dns.exception.FormError - # If it's not an empty slice, access left and right bounds - # to make sure they're valid - if i != j: - super(WireData, self).__getitem__(i) - super(WireData, self).__getitem__(j - 1) - return WireData(super(WireData, self).__getslice__(i, j)) - except IndexError: - raise dns.exception.FormError + if sys.version_info < (3,): + def __getslice__(self, i, j): # pylint: disable=getslice-method + return self.__getitem__(slice(i, j)) def __iter__(self): i = 0 diff --git a/dns/zone.py b/dns/zone.py index 4a73e1e..1b5dca2 100644 --- a/dns/zone.py +++ b/dns/zone.py @@ -19,6 +19,7 @@ from __future__ import generators import sys import re +import os from io import BytesIO import dns.exception @@ -498,18 +499,27 @@ class Zone(object): @type nl: string or None """ - str_type = string_types + if isinstance(f, string_types): + f = open(f, 'wb') + want_close = True + else: + want_close = False + + # must be in this way, f.encoding may contain None, or even attribute + # may not be there + file_enc = getattr(f, 'encoding', None) + if file_enc is None: + file_enc = 'utf-8' if nl is None: - opts = 'wb' + nl_b = os.linesep.encode(file_enc) # binary mode, '\n' is not enough + nl = u'\n' + elif isinstance(nl, string_types): + nl_b = nl.encode(file_enc) else: - opts = 'wb' + nl_b = nl + nl = nl.decode() - if isinstance(f, str_type): - f = open(f, opts) - want_close = True - else: - want_close = False try: if sorted: names = list(self.keys()) @@ -520,11 +530,15 @@ class Zone(object): l = self[n].to_text(n, origin=self.origin, relativize=relativize) if isinstance(l, text_type): - l = l.encode() - if nl is None: - f.write(l) - f.write('\n') + l_b = l.encode(file_enc) else: + l_b = l + l = l.decode() + + try: + f.write(l_b) + f.write(nl_b) + except TypeError: # textual mode f.write(l) f.write(nl) finally: diff --git a/pylintrc b/pylintrc index c37ac1e..3f16509 100644 --- a/pylintrc +++ b/pylintrc @@ -23,7 +23,6 @@ disable= bare-except, deprecated-method, fixme, - getslice-method, global-statement, invalid-name, missing-docstring,
rthalley/dnspython
188aa701a6826c607da0624e31a8c4618d0a8017
diff --git a/tests/test_wiredata.py b/tests/test_wiredata.py new file mode 100644 index 0000000..eccc3e2 --- /dev/null +++ b/tests/test_wiredata.py @@ -0,0 +1,126 @@ +# Copyright (C) 2016 +# Author: Martin Basti <[email protected]> +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. + +try: + import unittest2 as unittest +except ImportError: + import unittest + +from dns.exception import FormError +from dns.wiredata import WireData + + +class WireDataSlicingTestCase(unittest.TestCase): + + def testSliceAll(self): + """Get all data""" + inst = WireData(b'0123456789') + self.assertEqual(inst[:], WireData(b'0123456789')) + + def testSliceAllExplicitlyDefined(self): + """Get all data""" + inst = WireData(b'0123456789') + self.assertEqual(inst[0:10], WireData(b'0123456789')) + + def testSliceLowerHalf(self): + """Get lower half of data""" + inst = WireData(b'0123456789') + self.assertEqual(inst[:5], WireData(b'01234')) + + def testSliceLowerHalfWithNegativeIndex(self): + """Get lower half of data""" + inst = WireData(b'0123456789') + self.assertEqual(inst[:-5], WireData(b'01234')) + + def testSliceUpperHalf(self): + """Get upper half of data""" + inst = WireData(b'0123456789') + self.assertEqual(inst[5:], WireData(b'56789')) + + def testSliceMiddle(self): + """Get data from middle""" + inst = WireData(b'0123456789') + self.assertEqual(inst[3:6], WireData(b'345')) + + def testSliceMiddleWithNegativeIndex(self): + """Get data from middle""" + inst = WireData(b'0123456789') + self.assertEqual(inst[-6:-3], WireData(b'456')) + + def testSliceMiddleWithMixedIndex(self): + """Get data from middle""" + inst = WireData(b'0123456789') + self.assertEqual(inst[-8:3], WireData(b'2')) + self.assertEqual(inst[5:-3], WireData(b'56')) + + def testGetOne(self): + """Get data one by one item""" + data = b'0123456789' + inst = WireData(data) + for i, byte in enumerate(bytearray(data)): + self.assertEqual(inst[i], byte) + for i in range(-1, len(data) * -1, -1): + self.assertEqual(inst[i], bytearray(data)[i]) + + def testEmptySlice(self): + """Test empty slice""" + data = b'0123456789' + inst = WireData(data) + for i, byte in enumerate(data): + self.assertEqual(inst[i:i], b'') + for i in range(-1, len(data) * -1, -1): + self.assertEqual(inst[i:i], b'') + self.assertEqual(inst[-3:-6], b'') + + def testSliceStartOutOfLowerBorder(self): + """Get data from out of lower border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[-11:] # pylint: disable=pointless-statement + + def testSliceStopOutOfLowerBorder(self): + """Get data from out of lower border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[:-11] # pylint: disable=pointless-statement + + def testSliceBothOutOfLowerBorder(self): + """Get data from out of lower border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[-12:-11] # pylint: disable=pointless-statement + + def testSliceStartOutOfUpperBorder(self): + """Get data from out of upper border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[11:] # pylint: disable=pointless-statement + + def testSliceStopOutOfUpperBorder(self): + """Get data from out of upper border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[:11] # pylint: disable=pointless-statement + + def testSliceBothOutOfUpperBorder(self): + """Get data from out of lower border""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[10:20] # pylint: disable=pointless-statement + + def testGetOneOutOfLowerBorder(self): + """Get item outside of range""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[-11] # pylint: disable=pointless-statement + + def testGetOneOutOfUpperBorder(self): + """Get item outside of range""" + inst = WireData(b'0123456789') + with self.assertRaises(FormError): + inst[10] # pylint: disable=pointless-statement diff --git a/tests/test_zone.py b/tests/test_zone.py index 712b590..3d53e93 100644 --- a/tests/test_zone.py +++ b/tests/test_zone.py @@ -132,6 +132,59 @@ class ZoneTestCase(unittest.TestCase): os.unlink(here('example2.out')) self.failUnless(ok) + def testToFileTextualStream(self): + z = dns.zone.from_text(example_text, 'example.', relativize=True) + f = StringIO() + z.to_file(f) + out = f.getvalue() + f.close() + self.assertEqual(out, example_text_output) + + def testToFileBinaryStream(self): + z = dns.zone.from_text(example_text, 'example.', relativize=True) + f = BytesIO() + z.to_file(f) + out = f.getvalue() + f.close() + self.assertEqual(out, example_text_output.encode()) + + def testToFileTextual(self): + z = dns.zone.from_file(here('example'), 'example') + try: + f = open(here('example3-textual.out'), 'w') + z.to_file(f) + f.close() + ok = filecmp.cmp(here('example3-textual.out'), + here('example3.good')) + finally: + if not _keep_output: + os.unlink(here('example3-textual.out')) + self.failUnless(ok) + + def testToFileBinary(self): + z = dns.zone.from_file(here('example'), 'example') + try: + f = open(here('example3-binary.out'), 'wb') + z.to_file(f) + f.close() + ok = filecmp.cmp(here('example3-binary.out'), + here('example3.good')) + finally: + if not _keep_output: + os.unlink(here('example3-binary.out')) + self.failUnless(ok) + + def testToFileFilename(self): + z = dns.zone.from_file(here('example'), 'example') + try: + z.to_file('example3-filename.out') + ok = filecmp.cmp(here('example3-filename.out'), + here('example3.good')) + finally: + if not _keep_output: + os.unlink(here('example3-filename.out')) + self.failUnless(ok) + def testToText(self): z = dns.zone.from_file(here('example'), 'example') ok = False
py3: Zone.to_file failed Hello, ``` #!/usr/local/bin/python3 import dns.zone from dns.rdatatype import SOA zone_obj = dns.zone.Zone(dns.name.from_text('test.zone')) zone_obj.find_rdataset('@', rdtype=SOA, create=True) zone_obj.to_file(open('/dev/null', 'w')) Traceback (most recent call last): File "./t.py", line 9, in <module> zone_obj.to_file(open('/dev/null', 'w')) File "/opt/hosting/software/python3/lib/python3.5/site-packages/dns/zone.py", line 516, in to_file f.write(l) TypeError: write() argument must be str, not bytes zone_obj.to_file(open('/dev/null', 'wb')) Traceback (most recent call last): File "./t.py", line 10, in <module> zone_obj.to_file(open('/dev/null', 'wb')) File "/opt/hosting/software/python3/lib/python3.5/site-packages/dns/zone.py", line 517, in to_file f.write('\n') TypeError: a bytes-like object is required, not 'str' ``` looks like a bug ?
0.0
188aa701a6826c607da0624e31a8c4618d0a8017
[ "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceBothOutOfLowerBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceBothOutOfUpperBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceStartOutOfLowerBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceStartOutOfUpperBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceStopOutOfLowerBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceStopOutOfUpperBorder", "tests/test_zone.py::ZoneTestCase::testToFileBinaryStream", "tests/test_zone.py::ZoneTestCase::testToFileTextualStream" ]
[ "tests/test_wiredata.py::WireDataSlicingTestCase::testEmptySlice", "tests/test_wiredata.py::WireDataSlicingTestCase::testGetOne", "tests/test_wiredata.py::WireDataSlicingTestCase::testGetOneOutOfLowerBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testGetOneOutOfUpperBorder", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceAll", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceAllExplicitlyDefined", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceLowerHalf", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceLowerHalfWithNegativeIndex", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceMiddle", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceMiddleWithMixedIndex", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceMiddleWithNegativeIndex", "tests/test_wiredata.py::WireDataSlicingTestCase::testSliceUpperHalf", "tests/test_zone.py::ZoneTestCase::testBadDirective", "tests/test_zone.py::ZoneTestCase::testDeleteRdataset1", "tests/test_zone.py::ZoneTestCase::testDeleteRdataset2", "tests/test_zone.py::ZoneTestCase::testEqual", "tests/test_zone.py::ZoneTestCase::testFindRRset1", "tests/test_zone.py::ZoneTestCase::testFindRRset2", "tests/test_zone.py::ZoneTestCase::testFindRdataset1", "tests/test_zone.py::ZoneTestCase::testFindRdataset2", "tests/test_zone.py::ZoneTestCase::testFirstRRStartsWithWhitespace", "tests/test_zone.py::ZoneTestCase::testFromText", "tests/test_zone.py::ZoneTestCase::testGetRRset1", "tests/test_zone.py::ZoneTestCase::testGetRRset2", "tests/test_zone.py::ZoneTestCase::testGetRdataset1", "tests/test_zone.py::ZoneTestCase::testGetRdataset2", "tests/test_zone.py::ZoneTestCase::testIterateAllRdatas", "tests/test_zone.py::ZoneTestCase::testIterateAllRdatasets", "tests/test_zone.py::ZoneTestCase::testIterateRdatas", "tests/test_zone.py::ZoneTestCase::testIterateRdatasets", "tests/test_zone.py::ZoneTestCase::testNoNS", "tests/test_zone.py::ZoneTestCase::testNoSOA", "tests/test_zone.py::ZoneTestCase::testNodeDeleteRdataset1", "tests/test_zone.py::ZoneTestCase::testNodeDeleteRdataset2", "tests/test_zone.py::ZoneTestCase::testNodeFindRdataset1", "tests/test_zone.py::ZoneTestCase::testNodeFindRdataset2", "tests/test_zone.py::ZoneTestCase::testNodeGetRdataset1", "tests/test_zone.py::ZoneTestCase::testNodeGetRdataset2", "tests/test_zone.py::ZoneTestCase::testNotEqual1", "tests/test_zone.py::ZoneTestCase::testNotEqual2", "tests/test_zone.py::ZoneTestCase::testNotEqual3", "tests/test_zone.py::ZoneTestCase::testReplaceRdataset1", "tests/test_zone.py::ZoneTestCase::testReplaceRdataset2", "tests/test_zone.py::ZoneTestCase::testTTLs", "tests/test_zone.py::ZoneTestCase::testZoneOrigin", "tests/test_zone.py::ZoneTestCase::testZoneOriginNone" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-07-03 00:30:41+00:00
isc
5,303
rthalley__dnspython-406
diff --git a/dns/message.pyi b/dns/message.pyi index ed99b3c..fb55a4c 100644 --- a/dns/message.pyi +++ b/dns/message.pyi @@ -37,6 +37,10 @@ class Message: self.multi = False self.first = True self.index : Dict[Tuple[rrset.RRset, name.Name, int, int, Union[int,str], int], rrset.RRset] = {} + + def is_response(self, other : Message) -> bool: + ... + def from_text(a : str) -> Message: ... diff --git a/dns/resolver.py b/dns/resolver.py index c49598f..735de9f 100644 --- a/dns/resolver.py +++ b/dns/resolver.py @@ -524,7 +524,7 @@ class Resolver(object): """ self.domain = None - self.nameservers = None + self.nameservers = [] self.nameserver_ports = None self.port = None self.search = None @@ -1079,6 +1079,21 @@ class Resolver(object): self.flags = flags + @property + def nameservers(self): + return self._nameservers + + @nameservers.setter + def nameservers(self, nameservers): + """ + :param nameservers: must be a ``list``. + :raise ValueError: if `nameservers` is anything other than a ``list``. + """ + if isinstance(nameservers, list): + self._nameservers = nameservers + else: + raise ValueError('nameservers must be a list' + ' (not a {})'.format(type(nameservers))) #: The default resolver. default_resolver = None diff --git a/dns/resolver.pyi b/dns/resolver.pyi index 06742fe..c68d04a 100644 --- a/dns/resolver.pyi +++ b/dns/resolver.pyi @@ -33,7 +33,7 @@ def zone_for_name(name, rdclass : int = rdataclass.IN, tcp=False, resolver : Opt ... class Resolver: - def __init__(self, configure): + def __init__(self, filename : Optional[str] = '/etc/resolv.conf', configure : Optional[bool] = True): self.nameservers : List[str] def query(self, qname : str, rdtype : Union[int,str] = rdatatype.A, rdclass : Union[int,str] = rdataclass.IN, tcp : bool = False, source : Optional[str] = None, raise_on_no_answer=True, source_port : int = 0):
rthalley/dnspython
a3193c831f97854e82db28492333d1aa269b1a12
diff --git a/tests/test_resolver.py b/tests/test_resolver.py index 1f78839..993a582 100644 --- a/tests/test_resolver.py +++ b/tests/test_resolver.py @@ -404,5 +404,23 @@ class NXDOMAINExceptionTestCase(unittest.TestCase): self.assertTrue(e2.canonical_name == dns.name.from_text(cname2)) +class ResolverNameserverValidTypeTestCase(unittest.TestCase): + def test_set_nameservers_to_list(self): + resolver = dns.resolver.Resolver() + resolver.nameservers = ['1.2.3.4'] + self.assertEqual(resolver.nameservers, ['1.2.3.4']) + + def test_set_namservers_to_empty_list(self): + resolver = dns.resolver.Resolver() + resolver.nameservers = [] + self.assertEqual(resolver.nameservers, []) + + def test_set_nameservers_invalid_type(self): + resolver = dns.resolver.Resolver() + invalid_nameservers = [None, '1.2.3.4', 1234, (1, 2, 3, 4), {'invalid': 'nameserver'}] + for invalid_nameserver in invalid_nameservers: + with self.assertRaises(ValueError): + resolver.nameservers = invalid_nameserver + if __name__ == '__main__': unittest.main()
Error checking of nameservers Feature request: Please verify that the value being set for "nameservers" is an array. It is too easy to say: resolver.nameservers = '8.8.8.8' and queries will time out with no clue as to why. The code should not allow "nameservers" to be set to anything other than an array. It should throw an exception.
0.0
a3193c831f97854e82db28492333d1aa269b1a12
[ "tests/test_resolver.py::ResolverNameserverValidTypeTestCase::test_set_nameservers_invalid_type" ]
[ "tests/test_resolver.py::BaseResolverTests::testCacheCleaning", "tests/test_resolver.py::BaseResolverTests::testCacheExpiration", "tests/test_resolver.py::BaseResolverTests::testEmptyAnswerSection", "tests/test_resolver.py::BaseResolverTests::testIndexErrorOnEmptyRRsetAccess", "tests/test_resolver.py::BaseResolverTests::testIndexErrorOnEmptyRRsetDelete", "tests/test_resolver.py::BaseResolverTests::testLRUDoesLRU", "tests/test_resolver.py::BaseResolverTests::testLRUExpiration", "tests/test_resolver.py::BaseResolverTests::testLRUReplace", "tests/test_resolver.py::BaseResolverTests::testRead", "tests/test_resolver.py::BaseResolverTests::testZoneForName1", "tests/test_resolver.py::BaseResolverTests::testZoneForName2", "tests/test_resolver.py::BaseResolverTests::testZoneForName3", "tests/test_resolver.py::BaseResolverTests::testZoneForName4", "tests/test_resolver.py::SelectResolverTestCase::testCacheCleaning", "tests/test_resolver.py::SelectResolverTestCase::testCacheExpiration", "tests/test_resolver.py::SelectResolverTestCase::testEmptyAnswerSection", "tests/test_resolver.py::SelectResolverTestCase::testIndexErrorOnEmptyRRsetAccess", "tests/test_resolver.py::SelectResolverTestCase::testIndexErrorOnEmptyRRsetDelete", "tests/test_resolver.py::SelectResolverTestCase::testLRUDoesLRU", "tests/test_resolver.py::SelectResolverTestCase::testLRUExpiration", "tests/test_resolver.py::SelectResolverTestCase::testLRUReplace", "tests/test_resolver.py::SelectResolverTestCase::testRead", "tests/test_resolver.py::SelectResolverTestCase::testZoneForName1", "tests/test_resolver.py::SelectResolverTestCase::testZoneForName2", "tests/test_resolver.py::SelectResolverTestCase::testZoneForName3", "tests/test_resolver.py::SelectResolverTestCase::testZoneForName4", "tests/test_resolver.py::PollResolverTestCase::testCacheCleaning", "tests/test_resolver.py::PollResolverTestCase::testCacheExpiration", "tests/test_resolver.py::PollResolverTestCase::testEmptyAnswerSection", "tests/test_resolver.py::PollResolverTestCase::testIndexErrorOnEmptyRRsetAccess", "tests/test_resolver.py::PollResolverTestCase::testIndexErrorOnEmptyRRsetDelete", "tests/test_resolver.py::PollResolverTestCase::testLRUDoesLRU", "tests/test_resolver.py::PollResolverTestCase::testLRUExpiration", "tests/test_resolver.py::PollResolverTestCase::testLRUReplace", "tests/test_resolver.py::PollResolverTestCase::testRead", "tests/test_resolver.py::PollResolverTestCase::testZoneForName1", "tests/test_resolver.py::PollResolverTestCase::testZoneForName2", "tests/test_resolver.py::PollResolverTestCase::testZoneForName3", "tests/test_resolver.py::PollResolverTestCase::testZoneForName4", "tests/test_resolver.py::NXDOMAINExceptionTestCase::test_nxdomain_canonical_name", "tests/test_resolver.py::NXDOMAINExceptionTestCase::test_nxdomain_compatible", "tests/test_resolver.py::NXDOMAINExceptionTestCase::test_nxdomain_merge", "tests/test_resolver.py::ResolverNameserverValidTypeTestCase::test_set_nameservers_to_list", "tests/test_resolver.py::ResolverNameserverValidTypeTestCase::test_set_namservers_to_empty_list" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-12-26 21:57:18+00:00
isc
5,304
rubik__radon-212
diff --git a/Pipfile.lock b/Pipfile.lock index 535ee56..116e260 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -3,6 +3,7 @@ "hash": { "sha256": "d1770e050ee8f186459b846d478570545743da69832155b1ac48b9fcedf00f1e" }, + "pipfile-spec": 6, "requires": {}, "sources": [ { @@ -13,90 +14,175 @@ }, "default": { "colorama": { - "hash": "sha256:463f8483208e921368c9f306094eb6f725c6ca42b0f97e313cb5d5512459feda", + "hashes": [ + "sha256:463f8483208e921368c9f306094eb6f725c6ca42b0f97e313cb5d5512459feda", + "sha256:48eb22f4f8461b1df5734a074b57042430fb06e1d61bd1e11b078c0fe6d7a1f1" + ], "version": "==0.3.9" }, "flake8": { - "hash": "sha256:83905eadba99f73fbfe966598aaf1682b3eb6755d2263c5b33a4e8367d60b0d1", - "version": "==3.3.0" + "hashes": [ + "sha256:1aa8990be1e689d96c745c5682b687ea49f2e05a443aff1f8251092b0014e378", + "sha256:3b9f848952dddccf635be78098ca75010f073bfe14d2c6bda867154bea728d2a" + ], + "version": "==3.9.1" }, "flake8-polyfill": { - "hash": "sha256:da3d14a829cb1ec6377b2065e3f3892cf64b81a24ad15bbdf003c7bfee01723f", + "hashes": [ + "sha256:c77056b1e2cfce7b39d7634370062baf02438962a7d176ea717627b83b17f609", + "sha256:da3d14a829cb1ec6377b2065e3f3892cf64b81a24ad15bbdf003c7bfee01723f" + ], "version": "==1.0.1" }, "mando": { - "hash": "sha256:ef1e10b7004b84c41cb272516640f1d387fcd1e16ba48fb96d6a6eba131faef3", + "hashes": [ + "sha256:4626fe3d74bb23e3a64dda59843d1641f0bf01097f61ff817d3f2e1db21cb4b3", + "sha256:ef1e10b7004b84c41cb272516640f1d387fcd1e16ba48fb96d6a6eba131faef3" + ], "version": "==0.3.3" }, "mccabe": { - "hash": "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", + "hashes": [ + "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", + "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f" + ], "version": "==0.6.1" }, "pycodestyle": { - "hash": "sha256:6c4245ade1edfad79c3446fadfc96b0de2759662dc29d07d80a6f27ad1ca6ba9", - "version": "==2.3.1" + "hashes": [ + "sha256:514f76d918fcc0b55c6680472f0a37970994e07bbb80725808c17089be302068", + "sha256:c389c1d06bf7904078ca03399a4816f974a1d590090fecea0c63ec26ebaf1cef" + ], + "version": "==2.7.0" }, "pyflakes": { - "hash": "sha256:cc5eadfb38041f8366128786b4ca12700ed05bbf1403d808e89d57d67a3875a7", - "version": "==1.5.0" + "hashes": [ + "sha256:7893783d01b8a89811dd72d7dfd4d84ff098e5eed95cfa8905b22bbffe52efc3", + "sha256:f5bc8ecabc05bb9d291eb5203d6810b49040f6ff446a756326104746cc00c1db" + ], + "version": "==2.3.1" } }, "develop": { "appdirs": { - "hash": "sha256:d8b24664561d0d34ddfaec54636d502d7cea6e29c3eaf68f3df6180863e2166e", - "version": "==1.4.3" + "hashes": [ + "sha256:7d5d0167b2b1ba821647616af46a749d1c653740dd0d2415100fe26e27afdf41", + "sha256:a841dacd6b99318a741b166adb07e19ee71a274450e68237b4650ca1055ab128" + ], + "version": "==1.4.4" }, "coverage": { - "hash": "sha256:248783c221af8961278ea706b585586f92c61a024109acde675487632b775971", + "hashes": [ + "sha256:04db33c2a3e5b0cd5bc0ef9f93542eb8fabdd3cd6a80d37a428c92fedbf15e32", + "sha256:0c04f94d5a554e14608987e9877c2dc085c3a667aacb4431fa53f407a64b6cf6", + "sha256:1697d13f21c9c4167d843f2cb66de9b77ebaa657162a31aa71040373b7706e0a", + "sha256:1d36700875b3cc177f9537e012b67505ebb6c56a1d31b2e9e5061d75b981d5a6", + "sha256:216199d5d336c2aa3a64cc5831f23f6c01e1b5710fd56f8d0e77a88f3c230191", + "sha256:248783c221af8961278ea706b585586f92c61a024109acde675487632b775971", + "sha256:2b5c6f27e10fbd156ee7ca6eab3d5511ff9b2f7d485c1a2a431056b8107b9c72", + "sha256:34dd62690a511f0e4eb50ea717f5d4b076ebe86f4b5f4c7e9ed7874e30ed3519", + "sha256:3f1419a0ff97e54966c6b52895547761bd39c755b072c5043998d64a6e680ca3", + "sha256:46b484aaac58be8fcecc363ee3a3eaeb3a8e146a8b370d7d1c18cfaad72ef3a5", + "sha256:4d5311e2fa2e071b852e6c46844958f900febe3663cd741b5743c9e42b38648b", + "sha256:5d143d7bb6fb501f7dfa61af42f8255d8f6324d292e1abf04b5193a4a0c6864a", + "sha256:5eea9b318c58b4444b86d0b6270f4aad0df3c8860be4b9eb71191fa29d6e5f05", + "sha256:7bc8032c543cc4bddff32881e7a27542e6218dbeb8b9ec5e9d69f3213d6e11ef", + "sha256:88c4c15347bc813a7a23c66e13d7a9dc968a0f9d59136fb1d97ebe869db5b88b", + "sha256:8d1e770d7018217a014e06d8a6a67e47b5603d60d96d4b8879bb45aba1eea7de", + "sha256:902f0e340d80e90927dc4afe47d3b8390e1abad9366becb3b1fd609c50eae340", + "sha256:993d3edd6f84bdf969b2c14f5edca2a3c746c6c524593815a2918a1de4548076", + "sha256:9f32c7495e60db1657edb5088e27cfbdb2d30c01f047e72892713629fc0d96ae", + "sha256:a1ef25289f5415f01aadb552ddb3002a18d1c9fc11517a082cf5cb67a766f6a5", + "sha256:b4d5459ff96f2ea612dc92d7a2a6b8232919600cf7e1859629e26310718e9b6f", + "sha256:b52e45af6992d6c1b733a54b60fc96a371a5d5d7ef3efa14ad34f884bf1738d6", + "sha256:bed5bcb2b87cc4bcb3fa295413eb34a4128438f360957922e45901630b299b32", + "sha256:c16edfee46eee75f7fe630bb20a981521a77c03a11a6346f00de30ba8000358e", + "sha256:c26be7636819ae80e339288dc4f594d82d18a6a38879937872ead97b34892a8c", + "sha256:cef649ab5eeb6798bc4b384d4ecb4432e1c6a8f0554b946c83880865ceb8f28c", + "sha256:de832b9b062bf9ff079aeca7689c9cc26b26077a5bb35a945aa942509e3c29d7", + "sha256:e026a40b2842afdf29bba9c16a5b6bc496dcbcca602cc3ed7ad3b934d54f73ae", + "sha256:f3dfee8792241623740e7e2f34a88e6c8c510f7086b2fa695d0387ad815e0d0a", + "sha256:f75d0c7c1a7904d56daa4961299a084278fd12332bd115bcc55efac61d4271c8" + ], "version": "==4.4" }, + "distlib": { + "hashes": [ + "sha256:8c09de2c67b3e7deef7184574fc060ab8a793e7adbb183d942c389c8b13c52fb", + "sha256:edf6116872c863e1aa9d5bb7cb5e05a022c519a4594dc703843343a9ddd9bff1" + ], + "version": "==0.3.1" + }, + "filelock": { + "hashes": [ + "sha256:18d82244ee114f543149c66a6e0c14e9c4f8a1044b5cdaadd0f82159d6a6ff59", + "sha256:929b7d63ec5b7d6b71b0fa5ac14e030b3f70b75747cef1b10da9b879fef15836" + ], + "version": "==3.0.12" + }, "mock": { - "hash": "sha256:5ce3c71c5545b472da17b72268978914d0252980348636840bd34a00b5cc96c1", + "hashes": [ + "sha256:5ce3c71c5545b472da17b72268978914d0252980348636840bd34a00b5cc96c1", + "sha256:b158b6df76edd239b8208d481dc46b6afd45a846b7812ff0ce58971cf5bc8bba" + ], "version": "==2.0.0" }, - "packaging": { - "hash": "sha256:99276dc6e3a7851f32027a68f1095cd3f77c148091b092ea867a351811cfe388", - "version": "==16.8" - }, "pbr": { - "hash": "sha256:86f0e548dfbdc1ad12559725a66b5e1ca0b2e0744940da1ec89991fd11a2b32b", - "version": "==3.0.0" + "hashes": [ + "sha256:5fad80b613c402d5b7df7bd84812548b2a61e9977387a80a5fc5c396492b13c9", + "sha256:b236cde0ac9a6aedd5e3c34517b423cd4fd97ef723849da6b0d2231142d89c00" + ], + "version": "==5.5.1" }, "pluggy": { - "hash": "sha256:d2766caddfbbc8ef641d47da556d2ae3056860ce4d553aa04009e42b76a09951", - "version": "==0.4.0" + "hashes": [ + "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0", + "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d" + ], + "version": "==0.13.1" }, "py": { - "hash": "sha256:81b5e37db3cc1052de438375605fb5d3b3e97f950f415f9143f04697c684d7eb", - "version": "==1.4.33" - }, - "pyparsing": { - "hash": "sha256:fee43f17a9c4087e7ed1605bd6df994c6173c1e977d7ade7b651292fab2bd010", - "version": "==2.2.0" + "hashes": [ + "sha256:21b81bda15b66ef5e1a777a21c4dcd9c20ad3efd0b3f817e7a809035269e1bd3", + "sha256:3b80836aa6d1feeaa108e046da6423ab8f6ceda6468545ae8d02d9d58d18818a" + ], + "version": "==1.10.0" }, "pytest": { - "hash": "sha256:66f332ae62593b874a648b10a8cb106bfdacd2c6288ed7dec3713c3a808a6017", + "hashes": [ + "sha256:66f332ae62593b874a648b10a8cb106bfdacd2c6288ed7dec3713c3a808a6017", + "sha256:b70696ebd1a5e6b627e7e3ac1365a4bc60aaf3495e843c1e70448966c5224cab" + ], "version": "==3.0.7" }, "pytest-mock": { - "hash": "sha256:29bf62c12a67dc0e7f6d02efa2404f0b4d068b38cd64f22a06c8a16cb545a03e", + "hashes": [ + "sha256:29bf62c12a67dc0e7f6d02efa2404f0b4d068b38cd64f22a06c8a16cb545a03e", + "sha256:83a17cbcd4dbc7c6c9dc885a0d598f9acd11f2d5142e0718ed32e14538670c1f" + ], "version": "==1.6.0" }, - "setuptools": { - "hash": "sha256:19d753940f8cdbee7548da318f8b56159aead279ef811a6efc8b8a33d89c86a4", - "version": "==35.0.2" - }, "six": { - "hash": "sha256:0ff78c403d9bccf5a425a6d31a12aa6b47f1c21ca4dc2573a7e2f32a97335eb1", - "version": "==1.10.0" + "hashes": [ + "sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259", + "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced" + ], + "version": "==1.15.0" }, "tox": { - "hash": "sha256:0f37ea637ead4a5bbae91531b0bf8fd327c7152e20255e5960ee180598228d21", + "hashes": [ + "sha256:0f37ea637ead4a5bbae91531b0bf8fd327c7152e20255e5960ee180598228d21", + "sha256:9c3bdc06fe411d24015e8bbbab9d03dc5243a970154496aac13f9283682435f9" + ], "version": "==2.7.0" }, "virtualenv": { - "hash": "sha256:39d88b533b422825d644087a21e78c45cf5af0ef7a99a1fc9fbb7b481e5c85b0", - "version": "==15.1.0" + "hashes": [ + "sha256:09c61377ef072f43568207dc8e46ddeac6bcdcaf288d49011bda0e7f4d38c4a2", + "sha256:a935126db63128861987a7d5d30e23e8ec045a73840eeccb467c148514e29535" + ], + "markers": "python_version != '3.2'", + "version": "==20.4.4" } } -} \ No newline at end of file +} diff --git a/radon/visitors.py b/radon/visitors.py index 1be86b3..9e74fbb 100644 --- a/radon/visitors.py +++ b/radon/visitors.py @@ -229,7 +229,7 @@ class ComplexityVisitor(CodeVisitor): # In Python 3.3 the TryExcept and TryFinally nodes have been merged # into a single node: Try if name in ('Try', 'TryExcept'): - self.complexity += len(node.handlers) + len(node.orelse) + self.complexity += len(node.handlers) + bool(node.orelse) elif name == 'BoolOp': self.complexity += len(node.values) - 1 # Ifs, with and assert statements count all as 1.
rubik/radon
c9ac929fa9bf2418a83ad077f86bc75ca10d73a7
diff --git a/radon/tests/test_complexity_visitor.py b/radon/tests/test_complexity_visitor.py index 284bf62..4ae352d 100644 --- a/radon/tests/test_complexity_visitor.py +++ b/radon/tests/test_complexity_visitor.py @@ -213,6 +213,18 @@ SIMPLE_BLOCKS = [ 3, {}, ), + ( + ''' + try: raise TypeError + except TypeError: pass + else: + pass + pass + finally: pass + ''', + 3, + {}, + ), # Lambda are not counted anymore as per #68 ( '''
Incorrect CC for try-except-else else blocks containing multiple statements A near duplicate of #53, the following code has a CC of 5 when it should be 3. ``` def foo(): try: pass except: pass else: pass pass pass ```
0.0
c9ac929fa9bf2418a83ad077f86bc75ca10d73a7
[ "radon/tests/test_complexity_visitor.py::test_visitor_simple[\\n" ]
[ "radon/tests/test_complexity_visitor.py::test_visitor_single_functions[\\n", "radon/tests/test_complexity_visitor.py::test_visitor_functions[\\n", "radon/tests/test_complexity_visitor.py::test_visitor_classes[\\n", "radon/tests/test_complexity_visitor.py::test_visitor_module[\\n", "radon/tests/test_complexity_visitor.py::test_visitor_closures[\\n", "radon/tests/test_complexity_visitor.py::test_visitor_containers[values0-expected0]", "radon/tests/test_complexity_visitor.py::test_visitor_containers[values1-expected1]", "radon/tests/test_complexity_visitor.py::test_visitor_containers[values2-expected2]", "radon/tests/test_complexity_visitor.py::test_visitor_containers[values3-expected3]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-03-23 20:49:10+00:00
mit
5,305
rubrikinc__rubrik-sdk-for-python-272
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5543e4e..88ca269 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Added `add_organization_protectable_object_mssql_server_host()` ([Issue 234](https://github.com/rubrikinc/rubrik-sdk-for-python/issues/234)) - Added `add_organization_protectable_object_sql_server_db()` ([Issue 234](https://github.com/rubrikinc/rubrik-sdk-for-python/issues/234)) - Added `add_organization_protectable_object_sql_server_availability_group()` ([Issue 234](https://github.com/rubrikinc/rubrik-sdk-for-python/issues/234)) +- Added additional regions to valid_(aws|azure) enums ([Issue 271](https://github.com/rubrikinc/rubrik-sdk-for-python/issues/271)) ### Changed @@ -43,6 +44,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - The `object_id()` function now returns the correct the MSSQL DB and MSSQL Instance. When the object_type is `mssql_instance` the `mssql_host` keyword argument is now required. When the `object_type` is `mssql_db`, both the `mssql_instance` the `mssql_host` keyword arguments are required. - Added all examples to the `object_id()` documentation. - Prevent an error from being thrown when passing in an integer value into the `params` keyword argument in the `get()` function ([Issue 239](https://github.com/rubrikinc/rubrik-sdk-for-python/issues/236)) +- Fix Azure CloudOn api failure by adding resource_id ## v2.0.9 diff --git a/rubrik_cdm/cloud.py b/rubrik_cdm/cloud.py index a46a01e..6475446 100644 --- a/rubrik_cdm/cloud.py +++ b/rubrik_cdm/cloud.py @@ -57,24 +57,29 @@ class Cloud(Api): self.function_name = inspect.currentframe().f_code.co_name valid_aws_regions = [ + 'us-gov-east-1', + 'us-east-1', + 'us-east-2', + 'us-west-1', + 'us-west-2', + 'eu-west-1', + 'eu-west-2', + 'eu-west-3', + 'eu-central-1', + 'eu-north-1', + 'eu-south-1', + 'ap-east-1', 'ap-south-1', - 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', - 'ca-central-1', + 'ap-northeast-2', + 'sa-east-1', 'cn-north-1', 'cn-northwest-1', - 'eu-central-1', - 'eu-west-1', - 'eu-west-2', - 'eu-west-3', - 'sa-east-1', - 'us-gov-west-1', - 'us-west-1', - 'us-east-1', - 'us-east-2', - 'us-west-2'] + 'ca-central-1', + 'af-south-1', + 'me-south-1'] valid_storage_classes = [ 'standard', @@ -405,32 +410,48 @@ class Cloud(Api): self.function_name = inspect.currentframe().f_code.co_name valid_regions = [ - "westus", - "westus2", - "centralus", - "eastus", - "eastus2", - "northcentralus", - "southcentralus", - "westcentralus", - "canadacentral", - "canadaeast", - "brazilsouth", - "northeurope", - "westeurope", - "uksouth", - "ukwest", - "eastasia", - "southeastasia", - "japaneast", - "japanwest", - "australiaeast", - "australiasoutheast", - "centralindia", - "southindia", - "westindia", - "koreacentral", - "koreasouth"] + 'westus', + 'westus2', + 'centralus', + 'eastus', + 'eastus2', + 'northcentralus', + 'southcentralus', + 'westcentralus', + 'canadacentral', + 'canadaeast', + 'brazilsouth', + 'northeurope', + 'westeurope', + 'uksouth', + 'ukwest', + 'francecentral', + 'francesouth', + 'eastasia', + 'southeastasia', + 'japaneast', + 'japanwest', + 'australiaeast', + 'australiasoutheast', + 'australiacentral', + 'australiacentral2', + 'centralindia', + 'southindia', + 'westindia', + 'koreacentral', + 'koreasouth', + 'chinanorth', + 'chinaeast', + 'chinanorth2', + 'chinaeast2', + 'germanycentral', + 'germanynortheast', + 'usgovvirginia', + 'usgoviowa', + 'usgovarizona', + 'usgovtexas', + 'usdodeast', + 'usdodcentral'] if region not in valid_regions: raise InvalidParameterException('The `region` must be one of the following: {}'.format(valid_regions)) @@ -542,23 +563,29 @@ class Cloud(Api): self.function_name = inspect.currentframe().f_code.co_name valid_aws_regions = [ + 'us-gov-east-1', + 'us-east-1', + 'us-east-2', + 'us-west-1', + 'us-west-2', + 'eu-west-1', + 'eu-west-2', + 'eu-west-3', + 'eu-central-1', + 'eu-north-1', + 'eu-south-1', + 'ap-east-1', 'ap-south-1', - 'ap-northeast-3', - 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', - 'ca-central-1', + 'ap-northeast-2', + 'sa-east-1', 'cn-north-1', 'cn-northwest-1', - 'eu-central-1', - 'eu-west-1', - 'eu-west-2', - 'eu-west-3', - 'us-west-1', - 'us-east-1', - 'us-east-2', - 'us-west-2'] + 'ca-central-1', + 'af-south-1', + 'me-south-1'] # verify we are on cdm 4.2 or newer, required for cloud native # protection
rubrikinc/rubrik-sdk-for-python
513ed16c6227e5774bcd11283adc051baae5f4f5
diff --git a/tests/unit/cloud_test.py b/tests/unit/cloud_test.py index 27344a1..2d5f986 100644 --- a/tests/unit/cloud_test.py +++ b/tests/unit/cloud_test.py @@ -16,7 +16,7 @@ def test_aws_s3_cloudout_invalid_aws_region(rubrik): error_message = error.value.args[0] - assert error_message == "The `aws_region` must be one of the following: ['ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-gov-west-1', 'us-west-1', 'us-east-1', 'us-east-2', 'us-west-2']" + assert error_message == "The `aws_region` must be one of the following: ['us-gov-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1', 'eu-north-1', 'eu-south-1', 'ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2', 'sa-east-1', 'cn-north-1', 'cn-northwest-1', 'ca-central-1', 'af-south-1', 'me-south-1']" def test_aws_s3_cloudout_invalid_storage_class(rubrik): @@ -647,7 +647,7 @@ def test_azure_cloudon_invalid_region(rubrik): error_message = error.value.args[0] - assert error_message == "The `region` must be one of the following: ['westus', 'westus2', 'centralus', 'eastus', 'eastus2', 'northcentralus', 'southcentralus', 'westcentralus', 'canadacentral', 'canadaeast', 'brazilsouth', 'northeurope', 'westeurope', 'uksouth', 'ukwest', 'eastasia', 'southeastasia', 'japaneast', 'japanwest', 'australiaeast', 'australiasoutheast', 'centralindia', 'southindia', 'westindia', 'koreacentral', 'koreasouth']" + assert error_message == "The `region` must be one of the following: ['westus', 'westus2', 'centralus', 'eastus', 'eastus2', 'northcentralus', 'southcentralus', 'westcentralus', 'canadacentral', 'canadaeast', 'brazilsouth', 'northeurope', 'westeurope', 'uksouth', 'ukwest', 'francecentral', 'francesouth', 'eastasia', 'southeastasia', 'japaneast', 'japanwest', 'australiaeast', 'australiasoutheast', 'australiacentral', 'australiacentral2', 'centralindia', 'southindia', 'westindia', 'koreacentral', 'koreasouth', 'chinanorth', 'chinaeast', 'chinanorth2', 'chinaeast2', 'germanycentral', 'germanynortheast', 'usgovvirginia', 'usgoviowa', 'usgovarizona', 'usgovtexas', 'usdodeast', 'usdodcentral']" def test_azure_cloudon_idempotence(rubrik, mocker): @@ -872,7 +872,7 @@ def test_add_aws_native_account_invalid_aws_regionss(rubrik, mocker): error_message = error.value.args[0] - assert error_message == "The list `aws_regions` may only contain the following values: ['ap-south-1', 'ap-northeast-3', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1', 'cn-north-1', 'cn-northwest-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'us-west-1', 'us-east-1', 'us-east-2', 'us-west-2']" + assert error_message == "The list `aws_regions` may only contain the following values: ['us-gov-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1', 'eu-north-1', 'eu-south-1', 'ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2', 'sa-east-1', 'cn-north-1', 'cn-northwest-1', 'ca-central-1', 'af-south-1', 'me-south-1']" def test_add_aws_native_account_invalid_regional_bolt_network_configs_list(rubrik, mocker):
Add additional regions to Python Module **Is your feature request related to a problem? Please describe.** Please add missing regions to the module **Describe the solution you'd like** Add additional regions to `cloud.py`
0.0
513ed16c6227e5774bcd11283adc051baae5f4f5
[ "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_region", "tests/unit/cloud_test.py::test_azure_cloudon_invalid_region", "tests/unit/cloud_test.py::test_add_aws_native_account_invalid_aws_regionss" ]
[ "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_storage_class", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[_]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[/]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[*]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[?]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[%]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[.]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[:]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[|]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[<]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_invalid_aws_bucket_name[>]", "tests/unit/cloud_test.py::test_aws_s3_cloudout_missing_aws_region", "tests/unit/cloud_test.py::test_aws_s3_cloudout_missing_aws_access_key", "tests/unit/cloud_test.py::test_aws_s3_cloudout_missing_aws_secret_key", "tests/unit/cloud_test.py::test_aws_s3_cloudout_missing_kms_and_rsa", "tests/unit/cloud_test.py::test_aws_s3_cloudout_both_kms_and_rsa_populated", "tests/unit/cloud_test.py::test_aws_s3_cloudout_idempotence", "tests/unit/cloud_test.py::test_aws_s3_cloudout_archive_name_already_exsits", "tests/unit/cloud_test.py::test_aws_s3_cloudout", "tests/unit/cloud_test.py::test_update_aws_s3_cloudout_invalid_storage_class", "tests/unit/cloud_test.py::test_update_aws_s3_cloudout_current_archive_name_not_found", "tests/unit/cloud_test.py::test_update_aws_s3_cloudout", "tests/unit/cloud_test.py::test_aws_s3_cloudon_idempotence", "tests/unit/cloud_test.py::test_aws_s3_cloudon_archive_name_not_found", "tests/unit/cloud_test.py::test_aws_s3_cloudon_update_enable_consolidation", "tests/unit/cloud_test.py::test_aws_s3_cloudon", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[_]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[/]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[*]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[?]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[%]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[.]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[:]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[|]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[<]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_container[>]", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_instance_type", "tests/unit/cloud_test.py::test_azure_cloudout_idempotence", "tests/unit/cloud_test.py::test_azure_cloudout_invalid_archive_name", "tests/unit/cloud_test.py::test_azure_cloudout", "tests/unit/cloud_test.py::test_azure_cloudon_idempotence", "tests/unit/cloud_test.py::test_update_aws_native_account_minimum_installed_cdm_version_not_met", "tests/unit/cloud_test.py::test_update_aws_native_account_invalid_config", "tests/unit/cloud_test.py::test_update_aws_native_account", "tests/unit/cloud_test.py::test_add_aws_native_account_minimum_installed_cdm_version_not_met", "tests/unit/cloud_test.py::test_add_aws_native_account_missing_aws_region", "tests/unit/cloud_test.py::test_add_aws_native_account_missing_aws_access_key", "tests/unit/cloud_test.py::test_add_aws_native_account_missing_aws_secret_key", "tests/unit/cloud_test.py::test_add_aws_native_account_invalid_regional_bolt_network_configs_list", "tests/unit/cloud_test.py::test_add_aws_native_account_invalid_regional_bolt_network_configs_list_dict", "tests/unit/cloud_test.py::test_add_aws_native_account_invalid_regional_bolt_network_configs_list_dict_value", "tests/unit/cloud_test.py::test_add_aws_native_account_invalid_aws_account_name", "tests/unit/cloud_test.py::test_add_aws_native_account_idempotence", "tests/unit/cloud_test.py::test_add_aws_native_account" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-28 23:08:22+00:00
mit
5,306
rueckstiess__mtools-635
diff --git a/mtools/mplotqueries/mplotqueries.py b/mtools/mplotqueries/mplotqueries.py index 4f8dce6..7256eca 100644 --- a/mtools/mplotqueries/mplotqueries.py +++ b/mtools/mplotqueries/mplotqueries.py @@ -14,6 +14,7 @@ from mtools import __version__ from mtools.util.cmdlinetool import LogFileTool try: + import matplotlib import matplotlib.pyplot as plt from matplotlib.dates import AutoDateFormatter, date2num, AutoDateLocator from matplotlib import __version__ as mpl_version diff --git a/mtools/mplotqueries/plottypes/scatter_type.py b/mtools/mplotqueries/plottypes/scatter_type.py index 6fca067..70c9ac4 100644 --- a/mtools/mplotqueries/plottypes/scatter_type.py +++ b/mtools/mplotqueries/plottypes/scatter_type.py @@ -6,8 +6,6 @@ from operator import itemgetter from mtools.mplotqueries.plottypes.base_type import BasePlotType try: - import matplotlib.pyplot as plt - from matplotlib import __version__ as mpl_version from matplotlib.dates import date2num from matplotlib.patches import Polygon diff --git a/mtools/util/logevent.py b/mtools/util/logevent.py index f9023de..7901e56 100644 --- a/mtools/util/logevent.py +++ b/mtools/util/logevent.py @@ -181,7 +181,10 @@ class LogEvent(object): # split_tokens = self.split_tokens line_str = self.line_str - if line_str and line_str.endswith('ms'): + if (line_str + and line_str.endswith('ms') + and 'Scheduled new oplog query' not in line_str): + try: # find duration from end space_pos = line_str.rfind(" ") diff --git a/requirements.txt b/requirements.txt index 7c0d657..1dd45d3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ ordereddict==1.1 python-dateutil==2.7 -matplotlib==1.3.1 -numpy==1.8.0 +matplotlib==2.2.2 +numpy==1.14.5 pymongo==3.6 psutil==5.4 diff --git a/setup.py b/setup.py index f79cbc4..2cdc6a1 100644 --- a/setup.py +++ b/setup.py @@ -17,12 +17,12 @@ try: # simplify the default install experience, particularly where a build # toolchain is required. extras_requires = { - "all": ['matplotlib==1.3.1', 'numpy==1.8.0', 'pymongo==3.6', 'psutil==5.4'], + "all": ['matplotlib==2.2.2', 'numpy==1.14.5', 'pymongo==3.6', 'psutil==5.4'], "mlaunch": ['pymongo==3.6', 'psutil==5.4'], "mlogfilter": [], - "mloginfo": ['numpy==1.8.0'], + "mloginfo": ['numpy==1.14.5'], "mlogvis": [], - "mplotqueries": ['matplotlib==1.3.1', 'numpy==1.8.0'], + "mplotqueries": ['matplotlib==2.2.2', 'numpy==1.14.5'], } try:
rueckstiess/mtools
6ff062d6f8ce542969bfa4d5f85b0694a5970d3b
diff --git a/mtools/test/test_util_logevent.py b/mtools/test/test_util_logevent.py index 7c4d68b..e0d93e1 100644 --- a/mtools/test/test_util_logevent.py +++ b/mtools/test/test_util_logevent.py @@ -63,6 +63,7 @@ line_truncated_24 = ("Wed Jan 28 00:31:16.302 [conn12345] warning: log line " "reslen:256993 1445ms") line_fassert = ("***aborting after fassert() failure") line_empty = ("") +line_new_oplog_query = ('2018-05-01T21:57:45.989+0000 I REPL [replication-0] Scheduled new oplog query Fetcher source: host.name database: local query: { find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } query metadata: { $replData: 1, $oplogQueryData: 1, $readPreference: { mode: "secondaryPreferred" } } active: 1 findNetworkTimeout: 65000ms getMoreNetworkTimeout: 7500ms shutting down?: 0 first: 1 firstCommandScheduler: RemoteCommandRetryScheduler request: RemoteCommand 16543 -- target:host.name db:local cmd:{ find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } active: 1 callbackHandle.valid: 1 callbackHandle.cancelled: 0 attempt: 1 retryPolicy: RetryPolicyImpl maxAttempts: 1 maxTimeMillis: -1ms') # fake system.profile documents profile_doc1 = {"op": "query", "ns": "test.foo", @@ -252,6 +253,11 @@ def test_logevent_non_log_line(): assert(le.nreturned == None) assert(le.pattern == None) +def test_logevent_new_oplog_query(): + """ Check that LogEvent correctly ignores new oplog query for duration extraction """ + le = LogEvent(line_new_oplog_query) + assert(le.duration == None) + def test_logevent_lazy_evaluation(): """ Check that all LogEvent variables are evaluated lazily. """
Update matplotlib & numpy requirements matplotlib & numpy are pinned to very old versions in `requirements.txt`: ``` matplotlib==1.3.1 numpy==1.8.0 ``` It looks like the versions may be based on a pip freeze when `mplotqueries` was originally developed in ~2013.
0.0
6ff062d6f8ce542969bfa4d5f85b0694a5970d3b
[ "mtools/test/test_util_logevent.py::test_logevent_new_oplog_query" ]
[ "mtools/test/test_util_logevent.py::test_logevent_datetime_parsing", "mtools/test/test_util_logevent.py::test_logevent_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_command_parsing", "mtools/test/test_util_logevent.py::test_logevent_sort_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_profile_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_profile_sort_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_extract_new_and_old_numYields", "mtools/test/test_util_logevent.py::test_logevent_parse_truncated_line", "mtools/test/test_util_logevent.py::test_logevent_extract_planSummary", "mtools/test/test_util_logevent.py::test_logevent_value_extraction", "mtools/test/test_util_logevent.py::test_logevent_non_log_line", "mtools/test/test_util_logevent.py::test_logevent_lazy_evaluation" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-06-27 06:41:36+00:00
apache-2.0
5,307
rueckstiess__mtools-637
diff --git a/mtools/util/logevent.py b/mtools/util/logevent.py index f9023de..7901e56 100644 --- a/mtools/util/logevent.py +++ b/mtools/util/logevent.py @@ -181,7 +181,10 @@ class LogEvent(object): # split_tokens = self.split_tokens line_str = self.line_str - if line_str and line_str.endswith('ms'): + if (line_str + and line_str.endswith('ms') + and 'Scheduled new oplog query' not in line_str): + try: # find duration from end space_pos = line_str.rfind(" ")
rueckstiess/mtools
6ff062d6f8ce542969bfa4d5f85b0694a5970d3b
diff --git a/mtools/test/test_util_logevent.py b/mtools/test/test_util_logevent.py index 7c4d68b..e0d93e1 100644 --- a/mtools/test/test_util_logevent.py +++ b/mtools/test/test_util_logevent.py @@ -63,6 +63,7 @@ line_truncated_24 = ("Wed Jan 28 00:31:16.302 [conn12345] warning: log line " "reslen:256993 1445ms") line_fassert = ("***aborting after fassert() failure") line_empty = ("") +line_new_oplog_query = ('2018-05-01T21:57:45.989+0000 I REPL [replication-0] Scheduled new oplog query Fetcher source: host.name database: local query: { find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } query metadata: { $replData: 1, $oplogQueryData: 1, $readPreference: { mode: "secondaryPreferred" } } active: 1 findNetworkTimeout: 65000ms getMoreNetworkTimeout: 7500ms shutting down?: 0 first: 1 firstCommandScheduler: RemoteCommandRetryScheduler request: RemoteCommand 16543 -- target:host.name db:local cmd:{ find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } active: 1 callbackHandle.valid: 1 callbackHandle.cancelled: 0 attempt: 1 retryPolicy: RetryPolicyImpl maxAttempts: 1 maxTimeMillis: -1ms') # fake system.profile documents profile_doc1 = {"op": "query", "ns": "test.foo", @@ -252,6 +253,11 @@ def test_logevent_non_log_line(): assert(le.nreturned == None) assert(le.pattern == None) +def test_logevent_new_oplog_query(): + """ Check that LogEvent correctly ignores new oplog query for duration extraction """ + le = LogEvent(line_new_oplog_query) + assert(le.duration == None) + def test_logevent_lazy_evaluation(): """ Check that all LogEvent variables are evaluated lazily. """
Replication log entries inappropriately displayed on mplotqueries Newer versions of MongoDB include lines such as the following: ``` 2018-05-01T21:57:45.989+0000 I REPL [replication-0] Scheduled new oplog query Fetcher source: host.name database: local query: { find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } query metadata: { $replData: 1, $oplogQueryData: 1, $readPreference: { mode: "secondaryPreferred" } } active: 1 findNetworkTimeout: 65000ms getMoreNetworkTimeout: 7500ms shutting down?: 0 first: 1 firstCommandScheduler: RemoteCommandRetryScheduler request: RemoteCommand 16543 -- target:host.name db:local cmd:{ find: "oplog.rs", filter: { ts: { $gte: Timestamp(1525211859, 1) } }, tailable: true, oplogReplay: true, awaitData: true, maxTimeMS: 60000, batchSize: 13981010, term: 1, readConcern: { afterClusterTime: Timestamp(1525211859, 1) } } active: 1 callbackHandle.valid: 1 callbackHandle.cancelled: 0 attempt: 1 retryPolicy: RetryPolicyImpl maxAttempts: 1 maxTimeMillis: -1ms ``` It looks like the `-1ms` is getting picked up and interpreted as the duration of the operation. It therefore shows up on the plot with the duration of `-1` milliseconds. ### Expected behavior `Scheduled new oplog query` log entries should not be plotted ### Actual/current behavior The entry gets plotted with the `maxTimeMillis` value. ### Steps to reproduce the actual/current behavior Insert the line above into a file and run `mplotqueries` on it. ### Environment <!--- Include relevant details for the environment you experienced the bug in --> | Software | Version | ---------------- | ------- | mtools | 1.4.1 | MongoDB server | 3.6.4 | Operating system | OS X 10.11.2
0.0
6ff062d6f8ce542969bfa4d5f85b0694a5970d3b
[ "mtools/test/test_util_logevent.py::test_logevent_new_oplog_query" ]
[ "mtools/test/test_util_logevent.py::test_logevent_datetime_parsing", "mtools/test/test_util_logevent.py::test_logevent_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_command_parsing", "mtools/test/test_util_logevent.py::test_logevent_sort_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_profile_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_profile_sort_pattern_parsing", "mtools/test/test_util_logevent.py::test_logevent_extract_new_and_old_numYields", "mtools/test/test_util_logevent.py::test_logevent_parse_truncated_line", "mtools/test/test_util_logevent.py::test_logevent_extract_planSummary", "mtools/test/test_util_logevent.py::test_logevent_value_extraction", "mtools/test/test_util_logevent.py::test_logevent_non_log_line", "mtools/test/test_util_logevent.py::test_logevent_lazy_evaluation" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-06-29 02:31:13+00:00
apache-2.0
5,308
rupert__pyls-black-39
diff --git a/pyls_black/plugin.py b/pyls_black/plugin.py index 407802f..dc5d482 100644 --- a/pyls_black/plugin.py +++ b/pyls_black/plugin.py @@ -4,6 +4,8 @@ import black import toml from pyls import hookimpl +_PY36_VERSIONS = {black.TargetVersion[v] for v in ["PY36", "PY37", "PY38", "PY39"]} + @hookimpl(tryfirst=True) def pyls_format_document(document): @@ -97,7 +99,7 @@ def load_config(filename: str) -> Dict: black.TargetVersion[x.upper()] for x in file_config["target_version"] ) elif file_config.get("py36"): - target_version = black.PY36_VERSIONS + target_version = _PY36_VERSIONS else: target_version = set()
rupert/pyls-black
2ca10aab70c0911d01576427236495a6b10b5caf
diff --git a/tests/test_plugin.py b/tests/test_plugin.py index f943b16..e722dba 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -8,7 +8,12 @@ import pytest from pyls import uris from pyls.workspace import Document, Workspace -from pyls_black.plugin import load_config, pyls_format_document, pyls_format_range +from pyls_black.plugin import ( + _PY36_VERSIONS, + load_config, + pyls_format_document, + pyls_format_range, +) here = Path(__file__).parent fixtures_dir = here / "fixtures" @@ -191,7 +196,7 @@ def test_load_config_target_version(): def test_load_config_py36(): config = load_config(str(fixtures_dir / "py36" / "example.py")) - assert config["target_version"] == black.PY36_VERSIONS + assert config["target_version"] == _PY36_VERSIONS def test_load_config_defaults():
Test failure with black version 21.04b When updating black to version `21.04b` in nixos ( https://github.com/NixOS/nixpkgs/pull/120684 ) the tests for `pyls-black` fail (result at the end). As part of https://github.com/psf/black/pull/1717 `PY36_VERSIONS` were moved from from `src/black/__init__.py` to `tests/test_black.py`. The corresponding commit is https://github.com/psf/black/commit/6dddbd72414061cde9dd8ee72eac373b7fcf8b54 . ``` ============================= test session starts ============================== platform linux -- Python 3.8.9, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 rootdir: /build/source collected 16 items tests/test_plugin.py .............F.. [100%] =================================== FAILURES =================================== ____________________________ test_load_config_py36 _____________________________ def test_load_config_py36(): > config = load_config(str(fixtures_dir / "py36" / "example.py")) tests/test_plugin.py:192: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ filename = '/build/source/tests/fixtures/py36/example.py' def load_config(filename: str) -> Dict: defaults = { "line_length": 88, "fast": False, "pyi": filename.endswith(".pyi"), "skip_string_normalization": False, "target_version": set(), } root = black.find_project_root((filename,)) pyproject_filename = root / "pyproject.toml" if not pyproject_filename.is_file(): return defaults try: pyproject_toml = toml.load(str(pyproject_filename)) except (toml.TomlDecodeError, OSError): return defaults file_config = pyproject_toml.get("tool", {}).get("black", {}) file_config = { key.replace("--", "").replace("-", "_"): value for key, value in file_config.items() } config = { key: file_config.get(key, default_value) for key, default_value in defaults.items() } if file_config.get("target_version"): target_version = set( black.TargetVersion[x.upper()] for x in file_config["target_version"] ) elif file_config.get("py36"): > target_version = black.PY36_VERSIONS E AttributeError: module 'black' has no attribute 'PY36_VERSIONS' /nix/store/qqvpg72b33m1pxc5lzjfmx224jp2vrbx-python3.8-pyls-black-0.4.6/lib/python3.8/site-packages/pyls_black/plugin.py:100: AttributeError =========================== short test summary info ============================ FAILED tests/test_plugin.py::test_load_config_py36 - AttributeError: module '... ========================= 1 failed, 15 passed in 0.66s ========================= ```
0.0
2ca10aab70c0911d01576427236495a6b10b5caf
[ "tests/test_plugin.py::test_entry_point" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-05-24 09:42:15+00:00
mit
5,309
rust-lang__highfive-249
diff --git a/highfive/configs/rust-lang/rust.json b/highfive/configs/rust-lang/rust.json index f056f32..0f62ab3 100644 --- a/highfive/configs/rust-lang/rust.json +++ b/highfive/configs/rust-lang/rust.json @@ -5,7 +5,6 @@ "@estebank", "@matthewjasper", "@petrochenkov", - "@varkor", "@davidtwco", "@oli-obk", "@nagisa" diff --git a/highfive/newpr.py b/highfive/newpr.py index 60c56cf..8b00b72 100644 --- a/highfive/newpr.py +++ b/highfive/newpr.py @@ -33,7 +33,7 @@ surprise_branch_warning = "Pull requests are usually filed against the %s branch review_with_reviewer = 'r? @%s\n\n(rust-highfive has picked a reviewer for you, use r? to override)' review_without_reviewer = '@%s: no appropriate reviewer found, use r? to override' -reviewer_re = re.compile("\\b[rR]\?[:\- ]*@([a-zA-Z0-9\-]+)") +reviewer_re = re.compile("\\b[rR]\?[:\- ]*@(?:([a-zA-Z0-9\-]+)/)?([a-zA-Z0-9\-]+)") submodule_re = re.compile(".*\+Subproject\scommit\s.*", re.DOTALL | re.MULTILINE) target_re = re.compile("^[+-]{3} [ab]/compiler/rustc_target/src/spec/", re.MULTILINE) @@ -230,27 +230,46 @@ class HighfiveHandler(object): else: raise e - def find_reviewer(self, msg): + def get_groups(self): + groups = deepcopy(self.repo_config['groups']) + + # fill in the default groups, ensuring that overwriting is an + # error. + global_ = self._load_json_file('_global.json') + for name, people in global_['groups'].items(): + assert name not in groups, "group %s overlaps with _global.json" % name + groups[name] = people + + return groups + + def find_reviewer(self, msg, exclude): """ If the user specified a reviewer, return the username, otherwise returns None. """ if msg is not None: match = reviewer_re.search(msg) - return match.group(1) if match else None + if match: + if match.group(1): + # assign someone from the specified team + groups = self.get_groups() + potential = groups.get(match.group(2)) + if potential is None: + potential = groups.get("%s/%s" % (match.group(1), match.group(2))) + if potential is None: + potential = groups["all"] + else: + potential.extend(groups["all"]) + + return self.pick_reviewer(groups, potential, exclude) + else: + return match.group(2) def choose_reviewer(self, repo, owner, diff, exclude): """Choose a reviewer for the PR.""" # Get JSON data on reviewers. dirs = self.repo_config.get('dirs', {}) - groups = deepcopy(self.repo_config['groups']) - - # fill in the default groups, ensuring that overwriting is an - # error. - global_ = self._load_json_file('_global.json') - for name, people in global_['groups'].items(): - assert name not in groups, "group %s overlaps with _global.json" % name - groups[name] = people + groups = self.get_groups() most_changed = None # If there's directories with specially assigned groups/users @@ -293,6 +312,9 @@ class HighfiveHandler(object): if not potential: potential = groups['core'] + return self.pick_reviewer(groups, potential, exclude) + + def pick_reviewer(self, groups, potential, exclude): # expand the reviewers list by group reviewers = [] seen = {"all"} @@ -382,7 +404,7 @@ class HighfiveHandler(object): if not self.payload['pull_request', 'assignees']: # Only try to set an assignee if one isn't already set. msg = self.payload['pull_request', 'body'] - reviewer = self.find_reviewer(msg) + reviewer = self.find_reviewer(msg, author) post_msg = False if not reviewer: @@ -437,7 +459,7 @@ class HighfiveHandler(object): # Check for r? and set the assignee. msg = self.payload['comment', 'body'] - reviewer = self.find_reviewer(msg) + reviewer = self.find_reviewer(msg, author) if reviewer: issue = str(self.payload['issue', 'number']) self.set_assignee(
rust-lang/highfive
ab9ad47a683b488de3d85c69445c8daced06c8df
diff --git a/highfive/tests/fakes.py b/highfive/tests/fakes.py index ec7cf8f..7fb5604 100644 --- a/highfive/tests/fakes.py +++ b/highfive/tests/fakes.py @@ -75,6 +75,9 @@ def get_repo_configs(): "reviewers": ["@JohnTitor"], } } + }, + 'teams': { + "groups": {"all": [], "a": ["@pnkfelix"], "b/c": ["@nrc"]} } } diff --git a/highfive/tests/test_newpr.py b/highfive/tests/test_newpr.py index 3634ede..c72ca00 100644 --- a/highfive/tests/test_newpr.py +++ b/highfive/tests/test_newpr.py @@ -351,11 +351,11 @@ Please see [the contribution instructions](%s) for more information. handler = HighfiveHandlerMock(Payload({})).handler for (msg, reviewer) in found_cases: - assert handler.find_reviewer(msg) == reviewer, \ + assert handler.find_reviewer(msg, None) == reviewer, \ "expected '%s' from '%s'" % (reviewer, msg) for msg in not_found_cases: - assert handler.find_reviewer(msg) is None, \ + assert handler.find_reviewer(msg, None) is None, \ "expected '%s' to have no reviewer extracted" % msg class TestApiReq(TestNewPR): @@ -792,7 +792,7 @@ class TestNewPrFunction(TestNewPR): self.mocks['api_req'].assert_called_once_with( 'GET', 'https://the.url/', None, 'application/vnd.github.v3.diff' ) - self.mocks['find_reviewer'].assert_called_once_with('The PR comment.') + self.mocks['find_reviewer'].assert_called_once_with('The PR comment.', 'prAuthor') self.mocks['set_assignee'].assert_called_once_with( reviewer, 'repo-owner', 'repo-name', '7', self.user, 'prAuthor', to_mention @@ -1052,7 +1052,7 @@ class TestNewComment(TestNewPR): self.mocks['find_reviewer'].return_value = None handler.new_comment() self.mocks['is_collaborator'].assert_not_called() - self.mocks['find_reviewer'].assert_called_with('comment!') + self.mocks['find_reviewer'].assert_called_with('comment!', 'userA') self.mocks['set_assignee'].assert_not_called() def test_has_reviewer(self): @@ -1061,7 +1061,7 @@ class TestNewComment(TestNewPR): self.mocks['find_reviewer'].return_value = 'userD' handler.new_comment() self.mocks['is_collaborator'].assert_not_called() - self.mocks['find_reviewer'].assert_called_with('comment!') + self.mocks['find_reviewer'].assert_called_with('comment!', 'userA') self.mocks['set_assignee'].assert_called_with( 'userD', 'repo-owner', 'repo-name', '7', 'integrationUser', 'userA', None @@ -1260,6 +1260,31 @@ class TestChooseReviewer(TestNewPR): ) assert set(["@JohnTitor"]) == mentions + def test_with_team_ping(self): + """Test choosing a reviewer when passed a team ping""" + handler = HighfiveHandlerMock( + Payload({}), repo_config=self.fakes['config']['teams'] + ).handler + + found_cases = ( + ("r? @foo/a", "pnkfelix"), + ("r? @b/c", "nrc"), + ) + + not_found_cases = ( + "r? @/a", + "r? @a/b", + ) + + for (msg, reviewer) in found_cases: + assert handler.find_reviewer(msg, None) == reviewer, \ + "expected '%s' from '%s'" % (reviewer, msg) + + for msg in not_found_cases: + assert handler.find_reviewer(msg, None) is None, \ + "expected '%s' to have no reviewer extracted" % msg + + class TestRun(TestNewPR): @pytest.fixture(autouse=True) def make_mocks(cls, patcherize):
Assign a random team member with r+ priviliges on r? @rust-lang/<team> If someone writes: ``` r? @rust-lang/docs ``` Then we could for example assign steveklabnik since they have r+ rights. This mistake happens from time to time; what happens now when someone writes the above is to leave the PR without a reviewer... cc https://github.com/rust-lang/rust/pull/57357#issuecomment-451675541
0.0
ab9ad47a683b488de3d85c69445c8daced06c8df
[ "highfive/tests/test_newpr.py::TestNewPRGeneral::test_find_reviewer", "highfive/tests/test_newpr.py::TestChooseReviewer::test_with_team_ping", "highfive/tests/test_newpr.py::TestNewPrFunction::test_msg_reviewer_repeat_contributor", "highfive/tests/test_newpr.py::TestNewPrFunction::test_no_msg_reviewer_repeat_contributor", "highfive/tests/test_newpr.py::TestNewPrFunction::test_empty_pr_labels", "highfive/tests/test_newpr.py::TestNewPrFunction::test_no_msg_reviewer_new_contributor", "highfive/tests/test_newpr.py::TestNewPrFunction::test_no_pr_labels_specified", "highfive/tests/test_newpr.py::TestNewComment::test_has_reviewer", "highfive/tests/test_newpr.py::TestNewComment::test_no_reviewer" ]
[ "highfive/tests/test_newpr.py::TestRun::test_unsupported_payload", "highfive/tests/test_newpr.py::TestRun::test_newpr", "highfive/tests/test_newpr.py::TestRun::test_new_comment", "highfive/tests/test_newpr.py::TestHighfiveHandler::test_load_repo_config_unsupported", "highfive/tests/test_newpr.py::TestHighfiveHandler::test_init", "highfive/tests/test_newpr.py::TestHighfiveHandler::test_load_repo_config_supported", "highfive/tests/test_newpr.py::TestPostWarnings::test_unexpected_branch_modifies_submodule", "highfive/tests/test_newpr.py::TestPostWarnings::test_no_warnings", "highfive/tests/test_newpr.py::TestPostWarnings::test_unexpected_branch", "highfive/tests/test_newpr.py::TestPostWarnings::test_modifies_submodule", "highfive/tests/test_newpr.py::TestPostWarnings::test_unexpected_branch_modifies_submodule_and_targets", "highfive/tests/test_newpr.py::TestApiReq::test5", "highfive/tests/test_newpr.py::TestApiReq::test6", "highfive/tests/test_newpr.py::TestApiReq::test4", "highfive/tests/test_newpr.py::TestApiReq::test1", "highfive/tests/test_newpr.py::TestApiReq::test2", "highfive/tests/test_newpr.py::TestApiReq::test3", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_welcome_msg", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_expected_branch_default_expected_no_match", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_post_comment_error", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_is_collaborator_true", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_submodule", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_load_json_file", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_add_labels_success", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_post_comment_error_201", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_is_collaborator_error", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_expected_branch_custom_expected_no_match", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_review_msg", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_add_labels_error", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_targets", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_post_comment_success", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_is_collaborator_false", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_expected_branch_custom_expected_match", "highfive/tests/test_newpr.py::TestNewPRGeneral::test_expected_branch_default_expected_match", "highfive/tests/test_newpr.py::TestChooseReviewer::test_no_potential_reviewers", "highfive/tests/test_newpr.py::TestChooseReviewer::test_mentions", "highfive/tests/test_newpr.py::TestChooseReviewer::test_global_core", "highfive/tests/test_newpr.py::TestChooseReviewer::test_circular_groups", "highfive/tests/test_newpr.py::TestChooseReviewer::test_mentions_without_dirs", "highfive/tests/test_newpr.py::TestChooseReviewer::test_global_group_overlap", "highfive/tests/test_newpr.py::TestChooseReviewer::test_with_dirs", "highfive/tests/test_newpr.py::TestChooseReviewer::test_with_dirs_no_intersection", "highfive/tests/test_newpr.py::TestChooseReviewer::test_individuals_no_dirs_1", "highfive/tests/test_newpr.py::TestChooseReviewer::test_individuals_no_dirs_2", "highfive/tests/test_newpr.py::TestChooseReviewer::test_with_files", "highfive/tests/test_newpr.py::TestIsNewContributor::test_is_new_contributor_has_commits", "highfive/tests/test_newpr.py::TestIsNewContributor::test_is_new_contributor_no_commits", "highfive/tests/test_newpr.py::TestIsNewContributor::test_is_new_contributor_nonexistent_user", "highfive/tests/test_newpr.py::TestIsNewContributor::test_is_new_contributor_fork", "highfive/tests/test_newpr.py::TestIsNewContributor::test_is_new_contributor_error", "highfive/tests/test_newpr.py::TestNewPrFunction::test_assignee_already_set", "highfive/tests/test_newpr.py::TestNewComment::test_unauthorized_assigner", "highfive/tests/test_newpr.py::TestNewComment::test_authorized_assigner_commenter_is_assignee", "highfive/tests/test_newpr.py::TestNewComment::test_authorized_assigner_author_is_commenter", "highfive/tests/test_newpr.py::TestNewComment::test_not_pr", "highfive/tests/test_newpr.py::TestNewComment::test_authorized_assigner_commenter_is_collaborator", "highfive/tests/test_newpr.py::TestNewComment::test_not_open", "highfive/tests/test_newpr.py::TestNewComment::test_commenter_is_integration_user", "highfive/tests/test_newpr.py::TestSetAssignee::test_has_to_mention", "highfive/tests/test_newpr.py::TestSetAssignee::test_has_nick", "highfive/tests/test_newpr.py::TestSetAssignee::test_no_assignee", "highfive/tests/test_newpr.py::TestSetAssignee::test_api_req_error", "highfive/tests/test_newpr.py::TestSetAssignee::test_api_req_201", "highfive/tests/test_newpr.py::TestSetAssignee::test_api_req_good" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-27 13:25:22+00:00
apache-2.0
5,310
rust-lang__homu-100
diff --git a/homu/main.py b/homu/main.py index 6b3b4b6..a86529d 100644 --- a/homu/main.py +++ b/homu/main.py @@ -42,6 +42,12 @@ DEFAULT_TEST_TIMEOUT = 3600 * 10 global_cfg = {} +# Replace @mention with `@mention` to suppress pings in merge commits. +# Note: Don't replace non-mentions like "[email protected]". +def suppress_pings(text): + return re.sub(r'\B(@\S+)', r'`\g<1>`', text) # noqa + + @contextmanager def buildbot_sess(repo_cfg): sess = requests.Session() @@ -347,7 +353,7 @@ class PullReqState: issue = self.get_repo().issue(self.num) self.title = issue.title - self.body = issue.body + self.body = suppress_pings(issue.body) def fake_merge(self, repo_cfg): if not repo_cfg.get('linear', False): @@ -1533,7 +1539,7 @@ def synchronize(repo_label, repo_cfg, logger, gh, states, repos, db, mergeable_q state = PullReqState(pull.number, pull.head.sha, status, db, repo_label, mergeable_que, gh, repo_cfg['owner'], repo_cfg['name'], repo_cfg.get('labels', {}), repos, repo_cfg.get('test-on-fork')) # noqa state.title = pull.title - state.body = pull.body + state.body = suppress_pings(pull.body) state.head_ref = pull.head.repo[0] + ':' + pull.head.ref state.base_ref = pull.base.ref state.set_mergeable(None)
rust-lang/homu
dde7c154e65e9ea9e874b065e996333af84197eb
diff --git a/homu/tests/test_pr_body.py b/homu/tests/test_pr_body.py new file mode 100644 index 0000000..06a5287 --- /dev/null +++ b/homu/tests/test_pr_body.py @@ -0,0 +1,17 @@ +from homu.main import suppress_pings + + +def test_suppress_pings_in_PR_body(): + body = ( + "r? @matklad\n" # should escape + "@bors r+\n" # shouldn't + "[email protected]" # shouldn't + ) + + expect = ( + "r? `@matklad`\n" + "`@bors` r+\n" + "[email protected]" + ) + + assert suppress_pings(body) == expect
[feature request] Replace `@<name>` in PR description with only `<name>` Otherwise the reviewer will be pinged when the PR is rollupped or bor try, or even after the PR merged, the reviewer will be pinged by forks pulling the changes on github. _Originally posted by @lzutao in https://github.com/rust-lang/rust/pull/76161#issuecomment-683807588_ cc @matklad as he is also asking for this.
0.0
dde7c154e65e9ea9e874b065e996333af84197eb
[ "homu/tests/test_pr_body.py::test_suppress_pings_in_PR_body" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-09-01 02:32:01+00:00
mit
5,311
rust-lang__homu-124
diff --git a/homu/parse_issue_comment.py b/homu/parse_issue_comment.py index ce64c1b..108fbcb 100644 --- a/homu/parse_issue_comment.py +++ b/homu/parse_issue_comment.py @@ -158,7 +158,7 @@ def parse_issue_comment(username, body, sha, botname, hooks=[]): re.findall(r'\S+', re.sub(botname_regex, '', x)) for x in body.splitlines() - if '@' + botname in x)) # noqa + if '@' + botname in x and not x.lstrip().startswith('>'))) # noqa commands = [] diff --git a/homu/server.py b/homu/server.py index e383117..ce40fd3 100644 --- a/homu/server.py +++ b/homu/server.py @@ -574,6 +574,7 @@ def github(): state.save() elif event_type == 'issue_comment': + action = info['action'] body = info['comment']['body'] username = info['comment']['user']['login'] user_id = info['comment']['user']['id'] @@ -581,7 +582,7 @@ def github(): state = g.states[repo_label].get(pull_num) - if 'pull_request' in info['issue'] and state: + if action == 'created' and 'pull_request' in info['issue'] and state: state.title = info['issue']['title'] state.body = info['issue']['body']
rust-lang/homu
86945db41af3df4c9eaba6415fa5afa034d452ec
diff --git a/homu/tests/test_parse_issue_comment.py b/homu/tests/test_parse_issue_comment.py index 34da29f..71a1468 100644 --- a/homu/tests/test_parse_issue_comment.py +++ b/homu/tests/test_parse_issue_comment.py @@ -604,3 +604,18 @@ def test_ignore_commands_after_bors_line(): command = commands[0] assert command.action == 'approve' assert command.actor == 'jack' + + +def test_in_quote(): + """ + Test that a command in a quote (e.g. when replying by e-mail) doesn't + trigger. + """ + + author = "jack" + body = """ + > @bors r+ + """ + commands = parse_issue_comment(author, body, commit, "bors") + + assert len(commands) == 0
Ignore commands in quotes There is another edge case in homu command handling: when an user replies to a comment via email by default the parent command is quoted, and the old parser code tried to handle it. We should ignore commands when the line starts with `>`, to hopefully catch quoted emails, or if the new parser already handles this a test should be added. Example: https://github.com/rust-lang/rust/pull/61540#issuecomment-504549595
0.0
86945db41af3df4c9eaba6415fa5afa034d452ec
[ "homu/tests/test_parse_issue_comment.py::test_in_quote" ]
[ "homu/tests/test_parse_issue_comment.py::test_r_plus", "homu/tests/test_parse_issue_comment.py::test_r_plus_with_colon", "homu/tests/test_parse_issue_comment.py::test_r_plus_with_sha", "homu/tests/test_parse_issue_comment.py::test_r_equals", "homu/tests/test_parse_issue_comment.py::test_r_equals_at_user", "homu/tests/test_parse_issue_comment.py::test_hidden_r_equals", "homu/tests/test_parse_issue_comment.py::test_r_me", "homu/tests/test_parse_issue_comment.py::test_r_minus", "homu/tests/test_parse_issue_comment.py::test_priority", "homu/tests/test_parse_issue_comment.py::test_approve_and_priority", "homu/tests/test_parse_issue_comment.py::test_approve_specific_and_priority", "homu/tests/test_parse_issue_comment.py::test_delegate_plus", "homu/tests/test_parse_issue_comment.py::test_delegate_equals", "homu/tests/test_parse_issue_comment.py::test_delegate_minus", "homu/tests/test_parse_issue_comment.py::test_retry", "homu/tests/test_parse_issue_comment.py::test_try", "homu/tests/test_parse_issue_comment.py::test_try_minus", "homu/tests/test_parse_issue_comment.py::test_rollup", "homu/tests/test_parse_issue_comment.py::test_rollup_minus", "homu/tests/test_parse_issue_comment.py::test_rollup_iffy", "homu/tests/test_parse_issue_comment.py::test_rollup_never", "homu/tests/test_parse_issue_comment.py::test_rollup_maybe", "homu/tests/test_parse_issue_comment.py::test_rollup_always", "homu/tests/test_parse_issue_comment.py::test_force", "homu/tests/test_parse_issue_comment.py::test_clean", "homu/tests/test_parse_issue_comment.py::test_ping", "homu/tests/test_parse_issue_comment.py::test_hello", "homu/tests/test_parse_issue_comment.py::test_portal_ping", "homu/tests/test_parse_issue_comment.py::test_treeclosed", "homu/tests/test_parse_issue_comment.py::test_treeclosed_minus", "homu/tests/test_parse_issue_comment.py::test_hook", "homu/tests/test_parse_issue_comment.py::test_hook_equals", "homu/tests/test_parse_issue_comment.py::test_multiple_hooks", "homu/tests/test_parse_issue_comment.py::test_similar_name", "homu/tests/test_parse_issue_comment.py::test_parse_up_to_first_unknown_word", "homu/tests/test_parse_issue_comment.py::test_ignore_commands_before_bors_line", "homu/tests/test_parse_issue_comment.py::test_ignore_commands_after_bors_line" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-11-28 08:57:10+00:00
mit
5,312
rycus86__prometheus_flask_exporter-145
diff --git a/.gitignore b/.gitignore index f40e136..7ac4730 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ *.pyc .coverage coverage.xml +*.egg-info/ diff --git a/README.md b/README.md index 25ffe62..9678ec8 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,13 @@ the following values are supported in the dictionary: Label values are evaluated within the request context. +## Initial metric values +_For more info see: https://github.com/prometheus/client_python#labels_ + +Metrics without any labels will get an initial value. +Metrics that only have static-value labels will also have an initial value. (except when they are created with the option `initial_value_when_only_static_labels=False`) +Metrics that have one or more callable-value labels will not have an initial value. + ## Application information The `PrometheusMetrics.info(..)` method provides a way to expose diff --git a/prometheus_flask_exporter/__init__.py b/prometheus_flask_exporter/__init__.py index 37248d5..e194d0f 100644 --- a/prometheus_flask_exporter/__init__.py +++ b/prometheus_flask_exporter/__init__.py @@ -560,7 +560,7 @@ class PrometheusMetrics(object): view_func = wrapper(view_func) app.view_functions[endpoint] = view_func - def histogram(self, name, description, labels=None, **kwargs): + def histogram(self, name, description, labels=None, initial_value_when_only_static_labels=True, **kwargs): """ Use a Histogram to track the execution time and invocation count of the method. @@ -568,6 +568,8 @@ class PrometheusMetrics(object): :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels + :param initial_value_when_only_static_labels: whether to give metric an initial value + when only static labels are present :param kwargs: additional keyword arguments for creating the Histogram """ @@ -575,10 +577,11 @@ class PrometheusMetrics(object): Histogram, lambda metric, time: metric.observe(time), kwargs, name, description, labels, + initial_value_when_only_static_labels=initial_value_when_only_static_labels, registry=self.registry ) - def summary(self, name, description, labels=None, **kwargs): + def summary(self, name, description, labels=None, initial_value_when_only_static_labels=True, **kwargs): """ Use a Summary to track the execution time and invocation count of the method. @@ -586,6 +589,8 @@ class PrometheusMetrics(object): :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels + :param initial_value_when_only_static_labels: whether to give metric an initial value + when only static labels are present :param kwargs: additional keyword arguments for creating the Summary """ @@ -593,10 +598,11 @@ class PrometheusMetrics(object): Summary, lambda metric, time: metric.observe(time), kwargs, name, description, labels, + initial_value_when_only_static_labels=initial_value_when_only_static_labels, registry=self.registry ) - def gauge(self, name, description, labels=None, **kwargs): + def gauge(self, name, description, labels=None, initial_value_when_only_static_labels=True, **kwargs): """ Use a Gauge to track the number of invocations in progress for the method. @@ -604,6 +610,8 @@ class PrometheusMetrics(object): :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels + :param initial_value_when_only_static_labels: whether to give metric an initial value + when only static labels are present :param kwargs: additional keyword arguments for creating the Gauge """ @@ -611,30 +619,37 @@ class PrometheusMetrics(object): Gauge, lambda metric, time: metric.dec(), kwargs, name, description, labels, + initial_value_when_only_static_labels=initial_value_when_only_static_labels, registry=self.registry, before=lambda metric: metric.inc(), revert_when_not_tracked=lambda metric: metric.dec() ) - def counter(self, name, description, labels=None, **kwargs): + def counter(self, name, description, labels=None, initial_value_when_only_static_labels=True, **kwargs): """ Use a Counter to track the total number of invocations of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels + :param initial_value_when_only_static_labels: whether to give metric an initial value + when only static labels are present :param kwargs: additional keyword arguments for creating the Counter """ return self._track( Counter, lambda metric, time: metric.inc(), - kwargs, name, description, labels, + kwargs, + name, + description, + labels, + initial_value_when_only_static_labels=initial_value_when_only_static_labels, registry=self.registry ) def _track(self, metric_type, metric_call, metric_kwargs, name, description, labels, - registry, before=None, revert_when_not_tracked=None): + initial_value_when_only_static_labels, registry, before=None, revert_when_not_tracked=None): """ Internal method decorator logic. @@ -644,6 +659,8 @@ class PrometheusMetrics(object): :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_value}` for labels + :param initial_value_when_only_static_labels: whether to give metric an initial value + when only static labels are present :param registry: the Prometheus Registry to use :param before: an optional callable to invoke before executing the request handler method accepting the single `metric` argument @@ -662,6 +679,11 @@ class PrometheusMetrics(object): **metric_kwargs ) + # When all labels are already known at this point, the metric can get an initial value. + if initial_value_when_only_static_labels and labels.labels: + if all([label is not callable for label in labels.labels]): + parent_metric.labels(*[value for label, value in labels.labels]) + def get_metric(response): if labels.has_keys(): return parent_metric.labels(**labels.values_for(response))
rycus86/prometheus_flask_exporter
e1aac467124686ad5bd07e3de784b35296777b13
diff --git a/tests/test_metric_initialization.py b/tests/test_metric_initialization.py new file mode 100644 index 0000000..2ed7974 --- /dev/null +++ b/tests/test_metric_initialization.py @@ -0,0 +1,103 @@ +from abc import ABC, abstractmethod + +from flask import request + +from unittest_helper import BaseTestCase + + +# The class nesting avoids that the abstract base class will be tested (which is not possible because it is abstract..) +class MetricInitializationTest: + class MetricInitializationTest(BaseTestCase, ABC): + metric_suffix = None + + @property + @abstractmethod + def metric_type(self): + pass + + def get_metric_decorator(self, metrics): + return getattr(metrics, self.metric_type) + + def _test_metric_initialization(self, labels=None, initial_value_when_only_static_labels=True): + metrics = self.metrics() + metric_decorator = self.get_metric_decorator(metrics) + + test_path = '/test/1' + + @self.app.route(test_path) + @metric_decorator('metric_1', 'Metric 1', + labels=labels, + initial_value_when_only_static_labels=initial_value_when_only_static_labels) + def test1(): + return 'OK' + + if labels: + # replace callable with the "expected" result + if 'path' in labels: + labels['path'] = test_path + + label_value_pairs = labels.items() + else: + label_value_pairs = [] + + prometheus_metric_name = 'metric_1' + if self.metric_suffix: + prometheus_metric_name += self.metric_suffix + + # test metric value before any incoming HTTP call + self.assertMetric(prometheus_metric_name, '0.0', *label_value_pairs) + + self.client.get('/test/1') + + if self.metric_type == 'gauge': + expected_metric_value = '0.0' + else: + expected_metric_value = '1.0' + + self.assertMetric(prometheus_metric_name, expected_metric_value, *label_value_pairs) + + def test_initial_value_no_labels(self): + self._test_metric_initialization() + + def test_initial_value_only_static_labels(self): + labels = {'label_name': 'label_value'} + self._test_metric_initialization(labels) + + def test_initial_value_only_static_labels_no_initialization(self): + labels = {'label_name': 'label_value'} + self.assertRaises(AssertionError, self._test_metric_initialization, labels, initial_value_when_only_static_labels=False) + + def test_initial_value_callable_label(self): + labels = {'path': lambda: request.path} + self.assertRaises(AssertionError, self._test_metric_initialization, labels) + + + +class HistogramInitializationTest(MetricInitializationTest.MetricInitializationTest): + metric_suffix = '_count' + + @property + def metric_type(self): + return 'histogram' + + +class SummaryInitializationTest(MetricInitializationTest.MetricInitializationTest): + metric_suffix = '_count' + + @property + def metric_type(self): + return 'summary' + + +class GaugeInitializationTest(MetricInitializationTest.MetricInitializationTest): + @property + def metric_type(self): + return 'gauge' + + +class CounterInitializationTest(MetricInitializationTest.MetricInitializationTest): + metric_suffix = '_total' + + @property + def metric_type(self): + return 'counter' diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 6582940..0e6190c 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -28,6 +28,8 @@ class MetricsTest(BaseTestCase): def test3(x, y): return 'OK: %d/%d' % (x, y) + self.assertMetric('hist_1_count', '0.0') + self.client.get('/test/1') self.assertMetric('hist_1_count', '1.0') @@ -72,6 +74,8 @@ class MetricsTest(BaseTestCase): def test2(): return 'OK' + self.assertMetric('sum_1_count', '0.0') + self.client.get('/test/1') self.assertMetric('sum_1_count', '1.0') @@ -106,6 +110,8 @@ class MetricsTest(BaseTestCase): return 'OK: %d' % a + self.assertMetric('gauge_1', '0.0') + self.client.get('/test/1') self.assertMetric('gauge_1', '0.0') @@ -133,6 +139,7 @@ class MetricsTest(BaseTestCase): def test2(): return 'OK' + self.assertMetric('cnt_1_total', '0.0') self.client.get('/test/1') self.assertMetric('cnt_1_total', '1.0') self.client.get('/test/1')
Is it possible to give a metric an inital value? I want to monitor (the rate of) api calls to a microservice. The problem that I run into is that a metric is only available _after_ the first HTTP request. This means that the first time that Prometheus sees the metric of an endpoint the value will be 1. The consequence is that Prometheus cannot 'correctly' calculate the `rate` or `increase` for the metric for the first HTTP request since as far as Prometheus knows the value has always been 1. Is it possible to make the metric available _before_ the first request? (e.g. start counting at zero). `/metrics` output before any api call. ``` # HELP python_gc_objects_collected_total Objects collected during gc # TYPE python_gc_objects_collected_total counter python_gc_objects_collected_total{generation="0"} 413.0 python_gc_objects_collected_total{generation="1"} 0.0 python_gc_objects_collected_total{generation="2"} 0.0 # HELP python_gc_objects_uncollectable_total Uncollectable object found during GC # TYPE python_gc_objects_uncollectable_total counter python_gc_objects_uncollectable_total{generation="0"} 0.0 python_gc_objects_uncollectable_total{generation="1"} 0.0 python_gc_objects_uncollectable_total{generation="2"} 0.0 # HELP python_gc_collections_total Number of times this generation was collected # TYPE python_gc_collections_total counter python_gc_collections_total{generation="0"} 77.0 python_gc_collections_total{generation="1"} 7.0 python_gc_collections_total{generation="2"} 0.0 # HELP python_info Python platform information # TYPE python_info gauge python_info{implementation="CPython",major="3",minor="10",patchlevel="4",version="3.10.4"} 1.0 # HELP process_virtual_memory_bytes Virtual memory size in bytes. # TYPE process_virtual_memory_bytes gauge process_virtual_memory_bytes 7.2278016e+07 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 3.3284096e+07 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1.66747764407e+09 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 2.54 # HELP process_open_fds Number of open file descriptors. # TYPE process_open_fds gauge process_open_fds 10.0 # HELP process_max_fds Maximum number of open file descriptors. # TYPE process_max_fds gauge process_max_fds 1.048576e+06 # HELP exporter_info Information about the Prometheus Flask exporter # TYPE exporter_info gauge exporter_info{version="0.20.3"} 1.0 # HELP http_request_duration_seconds Flask HTTP request duration in seconds # TYPE http_request_duration_seconds histogram # HELP http_request_total Total number of HTTP requests # TYPE http_request_total counter # HELP http_request_exceptions_total Total number of HTTP requests which resulted in an exception # TYPE http_request_exceptions_total counter # HELP by_path_counter_total Request count by request paths # TYPE by_path_counter_total counter ``` `/metrics` output after first api call ``` # HELP python_gc_objects_collected_total Objects collected during gc # TYPE python_gc_objects_collected_total counter python_gc_objects_collected_total{generation="0"} 413.0 python_gc_objects_collected_total{generation="1"} 0.0 python_gc_objects_collected_total{generation="2"} 0.0 # HELP python_gc_objects_uncollectable_total Uncollectable object found during GC # TYPE python_gc_objects_uncollectable_total counter python_gc_objects_uncollectable_total{generation="0"} 0.0 python_gc_objects_uncollectable_total{generation="1"} 0.0 python_gc_objects_uncollectable_total{generation="2"} 0.0 # HELP python_gc_collections_total Number of times this generation was collected # TYPE python_gc_collections_total counter python_gc_collections_total{generation="0"} 77.0 python_gc_collections_total{generation="1"} 7.0 python_gc_collections_total{generation="2"} 0.0 # HELP python_info Python platform information # TYPE python_info gauge python_info{implementation="CPython",major="3",minor="10",patchlevel="4",version="3.10.4"} 1.0 # HELP process_virtual_memory_bytes Virtual memory size in bytes. # TYPE process_virtual_memory_bytes gauge process_virtual_memory_bytes 7.2278016e+07 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 3.3284096e+07 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1.66747764407e+09 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 2.54 # HELP process_open_fds Number of open file descriptors. # TYPE process_open_fds gauge process_open_fds 10.0 # HELP process_max_fds Maximum number of open file descriptors. # TYPE process_max_fds gauge process_max_fds 1.048576e+06 # HELP exporter_info Information about the Prometheus Flask exporter # TYPE exporter_info gauge exporter_info{version="0.20.3"} 1.0 # HELP http_request_duration_seconds Flask HTTP request duration in seconds # TYPE http_request_duration_seconds histogram http_request_duration_seconds_bucket{le="0.005",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.01",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.025",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.05",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.075",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.1",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.25",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.5",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="0.75",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="1.0",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="2.5",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="5.0",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="7.5",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="10.0",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_bucket{le="+Inf",method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_count{method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 http_request_duration_seconds_sum{method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 0.0003939999733120203 # HELP http_request_duration_seconds_created Flask HTTP request duration in seconds # TYPE http_request_duration_seconds_created gauge http_request_duration_seconds_created{method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.6674777541179776e+09 # HELP http_request_total Total number of HTTP requests # TYPE http_request_total counter http_request_total{method="GET",microservice_type="placeholder",model_name="devmodel",status="503"} 1.0 # HELP http_request_created Total number of HTTP requests # TYPE http_request_created gauge http_request_created{method="GET",microservice_type="placeholder",model_name="devmodel",status="503"} 1.6674777541180773e+09 # HELP http_request_exceptions_total Total number of HTTP requests which resulted in an exception # TYPE http_request_exceptions_total counter # HELP by_path_counter_total Request count by request paths # TYPE by_path_counter_total counter by_path_counter_total{method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.0 # HELP by_path_counter_created Request count by request paths # TYPE by_path_counter_created gauge by_path_counter_created{method="GET",microservice_type="placeholder",model_name="devmodel",path="/api/example",status="503"} 1.6674777541178892e+09 ```
0.0
e1aac467124686ad5bd07e3de784b35296777b13
[ "tests/test_metric_initialization.py::HistogramInitializationTest::test_initial_value_callable_label", "tests/test_metric_initialization.py::HistogramInitializationTest::test_initial_value_no_labels", "tests/test_metric_initialization.py::HistogramInitializationTest::test_initial_value_only_static_labels", "tests/test_metric_initialization.py::HistogramInitializationTest::test_initial_value_only_static_labels_no_initialization", "tests/test_metric_initialization.py::SummaryInitializationTest::test_initial_value_callable_label", "tests/test_metric_initialization.py::SummaryInitializationTest::test_initial_value_no_labels", "tests/test_metric_initialization.py::SummaryInitializationTest::test_initial_value_only_static_labels", "tests/test_metric_initialization.py::SummaryInitializationTest::test_initial_value_only_static_labels_no_initialization", "tests/test_metric_initialization.py::GaugeInitializationTest::test_initial_value_callable_label", "tests/test_metric_initialization.py::GaugeInitializationTest::test_initial_value_no_labels", "tests/test_metric_initialization.py::GaugeInitializationTest::test_initial_value_only_static_labels", "tests/test_metric_initialization.py::GaugeInitializationTest::test_initial_value_only_static_labels_no_initialization", "tests/test_metric_initialization.py::CounterInitializationTest::test_initial_value_callable_label", "tests/test_metric_initialization.py::CounterInitializationTest::test_initial_value_no_labels", "tests/test_metric_initialization.py::CounterInitializationTest::test_initial_value_only_static_labels", "tests/test_metric_initialization.py::CounterInitializationTest::test_initial_value_only_static_labels_no_initialization" ]
[ "tests/test_metrics.py::MetricsTest::test_counter", "tests/test_metrics.py::MetricsTest::test_default_format", "tests/test_metrics.py::MetricsTest::test_gauge", "tests/test_metrics.py::MetricsTest::test_histogram", "tests/test_metrics.py::MetricsTest::test_openmetrics_format", "tests/test_metrics.py::MetricsTest::test_summary" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-11-07 13:56:02+00:00
mit
5,313
s-weigand__flake8-nb-255
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ed1749f..5fa3966 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -114,12 +114,3 @@ repos: hooks: - id: yesqa additional_dependencies: [flake8-docstrings] - - repo: https://github.com/econchick/interrogate - rev: 1.5.0 - hooks: - - id: interrogate - name: Update interrogate badge - args: [-vv, --config=pyproject.toml, -g, docs/_static] - pass_filenames: false - always_run: true - stages: [push] diff --git a/flake8_nb/flake8_integration/cli.py b/flake8_nb/flake8_integration/cli.py index 960aa1d..d5991cd 100644 --- a/flake8_nb/flake8_integration/cli.py +++ b/flake8_nb/flake8_integration/cli.py @@ -144,9 +144,16 @@ def hack_config_module() -> None: with it with ``"flake8_nb"`` to create our own hacked version and replace the references to the original module with the hacked one. - See: https://github.com/s-weigand/flake8-nb/issues/249 + See: + https://github.com/s-weigand/flake8-nb/issues/249 + https://github.com/s-weigand/flake8-nb/issues/254 """ - hacked_config_source = Path(config.__file__).read_text().replace('"flake8"', '"flake8_nb"') + hacked_config_source = ( + Path(config.__file__) + .read_text() + .replace('"flake8"', '"flake8_nb"') + .replace('".flake8"', '".flake8_nb"') + ) hacked_config_path = Path(__file__).parent / "hacked_config.py" hacked_config_path.write_text(hacked_config_source) @@ -155,6 +162,10 @@ def hack_config_module() -> None: sys.modules["flake8.options.config"] = hacked_config aggregator.config = hacked_config + import flake8.main.application as application_module + + application_module.config = hacked_config + class Flake8NbApplication(Application): # type: ignore[misc] r"""Subclass of ``flake8.main.application.Application``. @@ -183,6 +194,7 @@ class Flake8NbApplication(Application): # type: ignore[misc] self.parse_configuration_and_cli_legacy # type: ignore[assignment] ) else: + hack_config_module() self.register_plugin_options = self.hacked_register_plugin_options def apply_hacks(self) -> None: @@ -377,7 +389,6 @@ class Flake8NbApplication(Application): # type: ignore[misc] assert self.plugins is not None self.apply_hacks() - hack_config_module() self.options = aggregator.aggregate_options( self.option_manager, diff --git a/pyproject.toml b/pyproject.toml index 22a15e1..442d24c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,15 +34,13 @@ verbose = 1 [tool.coverage.run] branch = true -include = [ - 'flake8_nb/*', -] +relative_files = true omit = [ 'setup.py', - "flake8_nb/__init__.py", - "flake8_nb/*/__init__.py", - "tests/__init__.py", - "*/tests/*", + 'flake8_nb/__init__.py', + 'flake8_nb/*/__init__.py', + 'tests/__init__.py', + '*/tests/*', # comment the above line if you want to see if all tests did run ] diff --git a/tox.ini b/tox.ini index 4347ff8..365b929 100644 --- a/tox.ini +++ b/tox.ini @@ -15,7 +15,7 @@ max-line-length = 100 ; *.py [pytest] -addopts = --cov=flake8_nb --cov-report term --cov-report xml --cov-report html --cov-config=pyproject.toml +addopts = --cov=. --cov-report term --cov-report xml --cov-report html --cov-config=pyproject.toml filterwarnings = ignore:.*not_a_notebook.ipynb @@ -43,8 +43,8 @@ commands_pre = {[testenv]commands_pre} {envpython} -m pip install -U -q --force-reinstall git+https://github.com/pycqa/flake8 commands = - {envpython} -c "import flake8_nb;print('FLAKE8 VERSION: ', flake8_nb.FLAKE8_VERSION_TUPLE)" - py.test -vv + {envpython} -c "import flake8_nb;print('FLAKE8 VERSION: ', flake8_nb.FLAKE8_VERSION_TUPLE)" + {envpython} -m pytest -vv [testenv:flake8-legacy] passenv = * @@ -52,7 +52,7 @@ commands_pre = {[testenv]commands_pre} {envpython} -m pip install -U -q 'flake8==3.8.0' commands = - py.test -vv + {envpython} -m pytest -vv [testenv] passenv = * @@ -60,4 +60,4 @@ install_command=python -m pip install {opts} {packages} commands_pre = {envpython} -m pip install -U -q -r {toxinidir}/requirements_dev.txt commands = - py.test + {envpython} -m pytest
s-weigand/flake8-nb
4bc29af0036b32d3899c8c9ab039ba988634f025
diff --git a/.github/workflows/test-nightly-schedule.yml b/.github/workflows/test-nightly-schedule.yml index b998bbe..3f2547a 100644 --- a/.github/workflows/test-nightly-schedule.yml +++ b/.github/workflows/test-nightly-schedule.yml @@ -26,4 +26,4 @@ jobs: pip freeze | grep flake8 - name: Run tests run: | - python -m pytest -vv --cov=./ --cov-report term --cov-report xml --cov-config .coveragerc tests + python -m pytest -vv diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0a592f4..0362a54 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -115,7 +115,7 @@ jobs: pip freeze | grep flake8 - name: Run tests run: | - python -m pytest -vv --cov=./ --cov-report term --cov-report xml --cov-config .coveragerc tests + python -m pytest -vv - name: Codecov Upload uses: codecov/codecov-action@v3 with: @@ -143,7 +143,7 @@ jobs: pip freeze | grep flake8 - name: Run tests run: | - python -m pytest -vv --cov=./ --cov-report term --cov-report xml --cov-config .coveragerc tests + python -m pytest -vv - name: Codecov Upload uses: codecov/codecov-action@v3 with: @@ -171,7 +171,7 @@ jobs: python -m pip install -U -r requirements_dev.txt - name: Run tests run: | - python -m pytest --cov=./ --cov-report term --cov-report xml --cov-config .coveragerc tests + python -m pytest - name: Codecov Upload uses: codecov/codecov-action@v3 with: diff --git a/tests/test__main__.py b/tests/test__main__.py index 146a2e7..da9229d 100644 --- a/tests/test__main__.py +++ b/tests/test__main__.py @@ -1,10 +1,13 @@ import json import os +import shutil import subprocess import sys from pathlib import Path import pytest +from _pytest.capture import CaptureFixture +from _pytest.monkeypatch import MonkeyPatch from flake8 import __version__ as flake_version from flake8_nb import FLAKE8_VERSION_TUPLE @@ -75,6 +78,36 @@ def test_run_main_use_config(capsys, tmp_path: Path): assert any(result.endswith(expected_result.rstrip("\n")) for result in result_list) [email protected]("config_file_name", ("setup.cfg", "tox.ini", ".flake8_nb")) +def test_config_discovered( + config_file_name: str, tmp_path: Path, monkeypatch: MonkeyPatch, capsys: CaptureFixture +): + """Check that config file is discovered.""" + + test_config = tmp_path / config_file_name + test_config.write_text("[flake8_nb]\nextend-ignore = E231,F401") + + shutil.copytree(TEST_NOTEBOOK_BASE_PATH, tmp_path / "notebooks") + + with monkeypatch.context() as m: + m.chdir(tmp_path) + with pytest.raises(SystemExit): + with pytest.warns(InvalidNotebookWarning): + main(["flake8_nb"]) + captured = capsys.readouterr() + result_output = captured.out + result_list = result_output.replace("\r", "").split("\n") + result_list.remove("") + expected_result_path = os.path.join( + os.path.dirname(__file__), "data", "expected_output_config_test.txt" + ) + with open(expected_result_path) as result_file: + expected_result_list = result_file.readlines() + assert len(expected_result_list) == len(result_list) + for expected_result in expected_result_list: + assert any(result.endswith(expected_result.rstrip("\n")) for result in result_list) + + def test_run_main_all_excluded(capsys): argv = ["flake8_nb"] argv += [
[BUG] Excluded directory is checked. **Describe the bug** Directories that I want to exclude and that were previously excluded are not scanned by flake8_nb. **To Reproduce** Steps to reproduce the behavior: 1. Create a `.flake8_nb` file with the following content: ``` exclude = *.git* *venv* *.ipynb_checkpoints* *.virtual_documents* *build* *.py ``` 2. Run `flake8_nb` from the CI 3. Observe how it enters the directory `.virtual_documents` where it should not end up! **Expected behavior** The excluded directories, such as `.virtual_documents` , should not be checked. **Desktop (please complete the following information):** - OS: Windows 10 - Version: flake8_nb-0.5.1 **Additional context** This was working with flake8-nb-0.4.0
0.0
4bc29af0036b32d3899c8c9ab039ba988634f025
[ "tests/test__main__.py::test_config_discovered[setup.cfg]", "tests/test__main__.py::test_config_discovered[tox.ini]", "tests/test__main__.py::test_config_discovered[.flake8_nb]" ]
[ "tests/test__main__.py::test_run_main[{nb_path}#In[{exec_count}]-expected_output_exec_count-True]", "tests/test__main__.py::test_run_main[{nb_path}#In[{exec_count}]-expected_output_exec_count-False]", "tests/test__main__.py::test_run_main[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-True]", "tests/test__main__.py::test_run_main[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-False]", "tests/test__main__.py::test_run_main[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-True]", "tests/test__main__.py::test_run_main[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-False]", "tests/test__main__.py::test_run_main_use_config", "tests/test__main__.py::test_run_main_all_excluded", "tests/test__main__.py::test_syscall[{nb_path}#In[{exec_count}]-expected_output_exec_count-flake8_nb-True]", "tests/test__main__.py::test_syscall[{nb_path}#In[{exec_count}]-expected_output_exec_count-flake8_nb-False]", "tests/test__main__.py::test_syscall[{nb_path}#In[{exec_count}]-expected_output_exec_count-flake8-nb-True]", "tests/test__main__.py::test_syscall[{nb_path}#In[{exec_count}]-expected_output_exec_count-flake8-nb-False]", "tests/test__main__.py::test_syscall[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-flake8_nb-True]", "tests/test__main__.py::test_syscall[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-flake8_nb-False]", "tests/test__main__.py::test_syscall[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-flake8-nb-True]", "tests/test__main__.py::test_syscall[{nb_path}:code_cell#{code_cell_count}-expected_output_code_cell_count-flake8-nb-False]", "tests/test__main__.py::test_syscall[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-flake8_nb-True]", "tests/test__main__.py::test_syscall[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-flake8_nb-False]", "tests/test__main__.py::test_syscall[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-flake8-nb-True]", "tests/test__main__.py::test_syscall[{nb_path}:cell#{total_cell_count}-expected_output_total_cell_count-flake8-nb-False]", "tests/test__main__.py::test_flake8_nb_module_call", "tests/test__main__.py::test_flake8_nb_bug_report" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-17 16:14:10+00:00
apache-2.0
5,314
sabuhish__fastapi-mail-93
diff --git a/Makefile b/Makefile index 4d0b190..6cc23ea 100644 --- a/Makefile +++ b/Makefile @@ -15,7 +15,7 @@ format_code: test_only: - pytest --cov-report term-missing --cov-report html --cov-branch \ + pytest -v --cov-report term-missing --cov-report html --cov-branch \ --cov fastapi_mail/ test: lint test_only diff --git a/docs/example.md b/docs/example.md index 590759c..401b057 100644 --- a/docs/example.md +++ b/docs/example.md @@ -188,6 +188,29 @@ Jinja behind the scenes. In these versions, you can then access your dict in you As you can see our keys in our dict are no longer the top level, they are part of the `body` variable. Nesting works as per normal below this level also. +### Customizing attachments by headers and MIME type + +Used for example for referencing Content-ID images in html of email + +```python +message = MessageSchema( + subject='Fastapi-Mail module', + recipients=recipients, + html="<img src='cid:logo_image'>", + subtype='html', + attachments=[ + { + "file": "/path/to/file.png"), + "headers": {"Content-ID": "<logo_image>"}, + "mime_type": "image", + "mime_subtype": "png", + } + ], +) + +fm = FastMail(conf) +await fm.send_message(message) +``` ## Guide for email utils The utility allows you to check temporary email addresses, you can block any email or domain. diff --git a/fastapi_mail/msg.py b/fastapi_mail/msg.py index cc92b34..183148d 100644 --- a/fastapi_mail/msg.py +++ b/fastapi_mail/msg.py @@ -41,12 +41,14 @@ class MailMsg: return MIMEText(text, _subtype=subtype, _charset=self.charset) async def attach_file(self, message, attachment): - - print(attachment) - - for file in attachment: - - part = MIMEBase(_maintype='application', _subtype='octet-stream') + """Creates a MIMEBase object""" + for file, file_meta in attachment: + if file_meta and 'mime_type' in file_meta and 'mime_subtype' in file_meta: + part = MIMEBase( + _maintype=file_meta['mime_type'], _subtype=file_meta['mime_subtype'] + ) + else: + part = MIMEBase(_maintype='application', _subtype='octet-stream') part.set_payload(await file.read()) encode_base64(part) @@ -62,7 +64,9 @@ class MailMsg: filename = ('UTF8', '', filename) part.add_header('Content-Disposition', 'attachment', filename=filename) - + if file_meta and 'headers' in file_meta: + for header in file_meta['headers'].keys(): + part.add_header(header, file_meta['headers'][header]) self.message.attach(part) async def _message(self, sender): diff --git a/fastapi_mail/schemas.py b/fastapi_mail/schemas.py index 18ff8f9..1fcdde2 100644 --- a/fastapi_mail/schemas.py +++ b/fastapi_mail/schemas.py @@ -1,7 +1,7 @@ import os from enum import Enum from mimetypes import MimeTypes -from typing import Any, Dict, List, Optional, Union +from typing import Dict, List, Optional, Union from pydantic import BaseModel, EmailStr, validator from starlette.datastructures import UploadFile @@ -29,7 +29,7 @@ class MultipartSubtypeEnum(Enum): class MessageSchema(BaseModel): recipients: List[EmailStr] - attachments: List[Any] = [] + attachments: List[Union[UploadFile, Dict, str]] = [] subject: str = '' body: Optional[Union[str, list]] = None template_body: Optional[Union[list, dict]] = None @@ -47,17 +47,25 @@ class MessageSchema(BaseModel): mime = MimeTypes() for file in v: + file_meta = None + if isinstance(file, dict): + keys = file.keys() + if 'file' not in keys: + raise WrongFile('missing "file" key') + file_meta = dict.copy(file) + del file_meta['file'] + file = file['file'] if isinstance(file, str): if os.path.isfile(file) and os.access(file, os.R_OK) and validate_path(file): mime_type = mime.guess_type(file) f = open(file, mode='rb') _, file_name = os.path.split(f.name) u = UploadFile(file_name, f, content_type=mime_type[0]) - temp.append(u) + temp.append((u, file_meta)) else: raise WrongFile('incorrect file path for attachment or not readable') elif isinstance(file, UploadFile): - temp.append(file) + temp.append((file, file_meta)) else: raise WrongFile('attachments field type incorrect, must be UploadFile or path') return temp @@ -69,6 +77,9 @@ class MessageSchema(BaseModel): return 'html' return value + class Config: + arbitrary_types_allowed = True + def validate_path(path): cur_dir = os.path.abspath(os.curdir) diff --git a/files/attachement_2.txt b/files/attachement_2.txt new file mode 100644 index 0000000..1797b61 --- /dev/null +++ b/files/attachement_2.txt @@ -0,0 +1,1 @@ +file test content \ No newline at end of file
sabuhish/fastapi-mail
25f1c6356eaf193c47246d9cbc3851d36befba1b
diff --git a/.github/workflows/test-package.yml b/.github/workflows/test-package.yml index a428294..3822461 100644 --- a/.github/workflows/test-package.yml +++ b/.github/workflows/test-package.yml @@ -1,5 +1,7 @@ name: CI -on: [push] +on: + push: + branches: '**' jobs: ci: diff --git a/tests/test_connection.py b/tests/test_connection.py index 0f6c47e..2a93cb1 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1,7 +1,11 @@ +import os + import pytest from fastapi_mail import ConnectionConfig, FastMail, MessageSchema +CONTENT = 'file test content' + @pytest.mark.asyncio async def test_connection(mail_config): @@ -44,6 +48,76 @@ async def test_html_message(mail_config): assert msg.html == 'html test' [email protected] +async def test_attachement_message(mail_config): + directory = os.getcwd() + attachement = directory + '/files/attachement.txt' + + with open(attachement, 'w') as file: + file.write(CONTENT) + + subject = 'testing' + to = '[email protected]' + msg = MessageSchema( + subject=subject, + recipients=[to], + html='html test', + subtype='html', + attachments=[attachement], + ) + conf = ConnectionConfig(**mail_config) + fm = FastMail(conf) + + with fm.record_messages() as outbox: + await fm.send_message(message=msg) + mail = outbox[0] + + assert len(outbox) == 1 + assert mail._payload[1].get_content_maintype() == 'application' + assert mail._payload[1].__dict__.get('_headers')[0][1] == 'application/octet-stream' + + [email protected] +async def test_attachement_message_with_headers(mail_config): + directory = os.getcwd() + attachement = directory + '/files/attachement.txt' + + with open(attachement, 'w') as file: + file.write(CONTENT) + + subject = 'testing' + to = '[email protected]' + msg = MessageSchema( + subject=subject, + recipients=[to], + html='html test', + subtype='html', + attachments=[ + { + 'file': attachement, + 'headers': {'Content-ID': 'test ID'}, + 'mime_type': 'image', + 'mime_subtype': 'png', + } + ], + ) + conf = ConnectionConfig(**mail_config) + fm = FastMail(conf) + + with fm.record_messages() as outbox: + await fm.send_message(message=msg) + + assert len(outbox) == 1 + mail = outbox[0] + assert mail._payload[1].get_content_maintype() == msg.attachments[0][1].get('mime_type') + assert mail._payload[1].get_content_subtype() == msg.attachments[0][1].get('mime_subtype') + + assert mail._payload[1].__dict__.get('_headers')[0][1] == 'image/png' + assert mail._payload[1].__dict__.get('_headers')[4][1] == msg.attachments[0][1].get( + 'headers' + ).get('Content-ID') + + @pytest.mark.asyncio async def test_jinja_message_list(mail_config): sender = f"{mail_config['MAIL_FROM_NAME']} <{mail_config['MAIL_FROM']}>"
Allow creating custom headers for attachments Use case - attaching html images with Content-ID header to reference them in HTML content of email based on [RFC2392](https://datatracker.ietf.org/doc/html/rfc2392) How to do it: - Modify MessageSchema to allow setting custom headers, like this ```python message = MessageSchema( subject=subject, recipients=recipients, html=html, subtype="html", attachments=[{"file": "/path/to/file", "headers":{"Content-ID": "<image1>"}, "mime_type" : "image", "mime_subtype": "png"}] ) ``` `file` parameter can be as now, UploadFile and path As it's hard to automagically import mime class as they dont' have the same API, it's possible to do it through MIMEBase So it's possible to add custom headers and override `mime_type` used in `MIMEBase` with `type` and `subtype` attributes and in `MailMsg`, in `attach_file` method, unpack the structure and add headers. I can code it if this is fine @sabuhish
0.0
25f1c6356eaf193c47246d9cbc3851d36befba1b
[ "tests/test_connection.py::test_attachement_message_with_headers" ]
[ "tests/test_connection.py::test_connection", "tests/test_connection.py::test_html_message", "tests/test_connection.py::test_attachement_message", "tests/test_connection.py::test_jinja_message_list", "tests/test_connection.py::test_jinja_message_dict", "tests/test_connection.py::test_send_msg", "tests/test_connection.py::test_send_msg_with_subtype", "tests/test_connection.py::test_jinja_message_with_html" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-09-21 21:32:38+00:00
mit
5,315
samkohn__larpix-control-68
diff --git a/larpix/larpix.py b/larpix/larpix.py index b41ce5e..f1f7684 100644 --- a/larpix/larpix.py +++ b/larpix/larpix.py @@ -174,14 +174,14 @@ class Configuration(object): } # These registers store 32 bits over 4 registers each, and those # 32 bits correspond to entries in a 32-entry list. - complex_array_spec = [ + self._complex_array_spec = [ (range(34, 38), 'csa_bypass_select'), (range(38, 42), 'csa_monitor_select'), (range(42, 46), 'csa_testpulse_enable'), (range(52, 56), 'channel_mask'), (range(56, 60), 'external_trigger_mask')] self._complex_array = {} - for addresses, label in complex_array_spec: + for addresses, label in self._complex_array_spec: for i, address in enumerate(addresses): self._complex_array[address] = (label, i) # These registers each correspond to an entry in an array @@ -202,6 +202,19 @@ class Configuration(object): for register_name in self.register_names: if getattr(self, register_name) != getattr(default_config, register_name): d[register_name] = getattr(self, register_name) + # Attempt to simplify some of the long values (array values) + for (name, value) in d.items(): + if (name in (label for _, label in self._complex_array_spec) + or name == 'pixel_trim_thresholds'): + different_values = [] + for ch, (val, default_val) in enumerate(zip(value, getattr( + default_config, name))): + if val != default_val: + different_values.append({'channel': ch, 'value': val}) + if len(different_values) < 5: + d[name] = different_values + else: + pass return d @property
samkohn/larpix-control
c015c00b1f83d2b36fefe0bba5d9cfdd167792e3
diff --git a/test/test_larpix.py b/test/test_larpix.py index f505c2f..b22de84 100644 --- a/test/test_larpix.py +++ b/test/test_larpix.py @@ -528,6 +528,27 @@ def test_configuration_get_nondefault_registers(): expected['adc_burst_length'] = c.adc_burst_length assert c.get_nondefault_registers() == expected +def test_configuration_get_nondefault_registers_array(): + c = Configuration() + c.channel_mask[1] = 1 + c.channel_mask[5] = 1 + result = c.get_nondefault_registers() + expected = { + 'channel_mask': [ + { 'channel': 1, 'value': 1 }, + { 'channel': 5, 'value': 1 } + ] + } + assert result == expected + +def test_configuration_get_nondefault_registers_many_changes(): + c = Configuration() + c.channel_mask[:20] = [1]*20 + result = c.get_nondefault_registers() + expected = { 'channel_mask': [1]*20 + [0]*12 } + assert result == expected + + def test_configuration_set_pixel_trim_thresholds(): c = Configuration() expected = [0x05] * Chip.num_channels
Configuration.get_nondefault_registers() is too verbose for arrays It should only return array entries that are different from the default. There are some decisions to be made about how to represent that in the dict, and when/whether to conclude that enough entries are different that the whole array should be shown anyway
0.0
c015c00b1f83d2b36fefe0bba5d9cfdd167792e3
[ "test/test_larpix.py::test_configuration_get_nondefault_registers_array" ]
[ "test/test_larpix.py::test_FakeSerialPort_write", "test/test_larpix.py::test_FakeSerialPort_read", "test/test_larpix.py::test_FakeSerialPort_read_multi", "test/test_larpix.py::test_chip_str", "test/test_larpix.py::test_chip_get_configuration_packets", "test/test_larpix.py::test_chip_sync_configuration", "test/test_larpix.py::test_chip_export_reads", "test/test_larpix.py::test_chip_export_reads_no_new_reads", "test/test_larpix.py::test_chip_export_reads_all", "test/test_larpix.py::test_controller_save_output", "test/test_larpix.py::test_controller_load", "test/test_larpix.py::test_packet_bits_bytes", "test/test_larpix.py::test_packet_init_default", "test/test_larpix.py::test_packet_init_bytestream", "test/test_larpix.py::test_packet_bytes_zeros", "test/test_larpix.py::test_packet_bytes_custom", "test/test_larpix.py::test_packet_bytes_properties", "test/test_larpix.py::test_packet_export_test", "test/test_larpix.py::test_packet_export_data", "test/test_larpix.py::test_packet_export_config_read", "test/test_larpix.py::test_packet_export_config_write", "test/test_larpix.py::test_packet_set_packet_type", "test/test_larpix.py::test_packet_get_packet_type", "test/test_larpix.py::test_packet_set_chipid", "test/test_larpix.py::test_packet_get_chipid", "test/test_larpix.py::test_packet_set_parity_bit_value", "test/test_larpix.py::test_packet_get_parity_bit_value", "test/test_larpix.py::test_packet_compute_parity", "test/test_larpix.py::test_packet_assign_parity", "test/test_larpix.py::test_packet_has_valid_parity", "test/test_larpix.py::test_packet_set_channel_id", "test/test_larpix.py::test_packet_get_channel_id", "test/test_larpix.py::test_packet_set_timestamp", "test/test_larpix.py::test_packet_get_timestamp", "test/test_larpix.py::test_packet_set_dataword", "test/test_larpix.py::test_packet_get_dataword", "test/test_larpix.py::test_packet_get_dataword_ADC_bug", "test/test_larpix.py::test_packet_set_fifo_half_flag", "test/test_larpix.py::test_packet_get_fifo_half_flag", "test/test_larpix.py::test_packet_set_fifo_full_flag", "test/test_larpix.py::test_packet_get_fifo_full_flag", "test/test_larpix.py::test_packet_set_register_address", "test/test_larpix.py::test_packet_get_register_address", "test/test_larpix.py::test_packet_set_register_data", "test/test_larpix.py::test_packet_get_register_data", "test/test_larpix.py::test_packet_set_test_counter", "test/test_larpix.py::test_packet_get_test_counter", "test/test_larpix.py::test_configuration_get_nondefault_registers", "test/test_larpix.py::test_configuration_get_nondefault_registers_many_changes", "test/test_larpix.py::test_configuration_set_pixel_trim_thresholds", "test/test_larpix.py::test_configuration_get_pixel_trim_thresholds", "test/test_larpix.py::test_configuration_set_global_threshold", "test/test_larpix.py::test_configuration_get_global_threshold", "test/test_larpix.py::test_configuration_set_csa_gain", "test/test_larpix.py::test_configuration_get_csa_gain", "test/test_larpix.py::test_configuration_set_csa_bypass", "test/test_larpix.py::test_configuration_get_csa_bypass", "test/test_larpix.py::test_configuration_set_internal_bypass", "test/test_larpix.py::test_configuration_get_internal_bypass", "test/test_larpix.py::test_configuration_set_csa_bypass_select", "test/test_larpix.py::test_configuration_get_csa_bypass_select", "test/test_larpix.py::test_configuration_set_csa_monitor_select", "test/test_larpix.py::test_configuration_get_csa_monitor_select", "test/test_larpix.py::test_configuration_set_csa_testpulse_enable", "test/test_larpix.py::test_configuration_get_csa_testpulse_enable", "test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_get_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_set_test_mode", "test/test_larpix.py::test_configuration_get_test_mode", "test/test_larpix.py::test_configuration_set_cross_trigger_mode", "test/test_larpix.py::test_configuration_get_cross_trigger_mode", "test/test_larpix.py::test_configuration_set_periodic_reset", "test/test_larpix.py::test_configuration_get_periodic_reset", "test/test_larpix.py::test_configuration_set_fifo_diagnostic", "test/test_larpix.py::test_configuration_get_fifo_diagnostic", "test/test_larpix.py::test_configuration_set_test_burst_length", "test/test_larpix.py::test_configuration_get_test_burst_length", "test/test_larpix.py::test_configuration_set_adc_burst_length", "test/test_larpix.py::test_configuration_get_adc_burst_length", "test/test_larpix.py::test_configuration_set_channel_mask", "test/test_larpix.py::test_configuration_get_channel_mask", "test/test_larpix.py::test_configuration_set_external_trigger_mask", "test/test_larpix.py::test_configuration_get_external_trigger_mask", "test/test_larpix.py::test_configuration_set_reset_cycles", "test/test_larpix.py::test_configuration_get_reset_cycles", "test/test_larpix.py::test_configuration_disable_channels", "test/test_larpix.py::test_configuration_disable_channels_default", "test/test_larpix.py::test_configuration_enable_channels", "test/test_larpix.py::test_configuration_enable_channels_default", "test/test_larpix.py::test_configuration_enable_external_trigger", "test/test_larpix.py::test_configuration_enable_external_trigger_default", "test/test_larpix.py::test_configuration_disable_external_trigger", "test/test_larpix.py::test_configuration_enable_testpulse", "test/test_larpix.py::test_configuration_enable_testpulse_default", "test/test_larpix.py::test_configuration_disable_testpulse", "test/test_larpix.py::test_configuration_disable_testpulse_default", "test/test_larpix.py::test_configuration_enable_analog_monitor", "test/test_larpix.py::test_configuration_disable_analog_monitor", "test/test_larpix.py::test_configuration_trim_threshold_data", "test/test_larpix.py::test_configuration_global_threshold_data", "test/test_larpix.py::test_configuration_csa_gain_and_bypasses_data", "test/test_larpix.py::test_configuration_csa_bypass_select_data", "test/test_larpix.py::test_configuration_csa_monitor_select_data", "test/test_larpix.py::test_configuration_csa_testpulse_enable_data", "test/test_larpix.py::test_configuration_csa_testpulse_dac_amplitude_data", "test/test_larpix.py::test_configuration_test_mode_xtrig_reset_diag_data", "test/test_larpix.py::test_configuration_sample_cycles_data", "test/test_larpix.py::test_configuration_test_burst_length_data", "test/test_larpix.py::test_configuration_adc_burst_length_data", "test/test_larpix.py::test_configuration_channel_mask_data", "test/test_larpix.py::test_configuration_external_trigger_mask_data", "test/test_larpix.py::test_configuration_reset_cycles_data", "test/test_larpix.py::test_configuration_to_dict", "test/test_larpix.py::test_configuration_from_dict", "test/test_larpix.py::test_configuration_write", "test/test_larpix.py::test_configuration_write_force", "test/test_larpix.py::test_configuration_read_absolute", "test/test_larpix.py::test_configuration_read_default", "test/test_larpix.py::test_configuration_read_local", "test/test_larpix.py::test_configuration_from_dict_reg_pixel_trim", "test/test_larpix.py::test_configuration_from_dict_reg_global_threshold", "test/test_larpix.py::test_configuration_from_dict_reg_csa_gain", "test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass", "test/test_larpix.py::test_configuration_from_dict_reg_internal_bypass", "test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass_select", "test/test_larpix.py::test_configuration_from_dict_reg_csa_monitor_select", "test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_enable", "test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_from_dict_reg_test_mode", "test/test_larpix.py::test_configuration_from_dict_reg_cross_trigger_mode", "test/test_larpix.py::test_configuration_from_dict_reg_periodic_reset", "test/test_larpix.py::test_configuration_from_dict_reg_fifo_diagnostic", "test/test_larpix.py::test_configuration_from_dict_reg_sample_cycles", "test/test_larpix.py::test_configuration_from_dict_reg_test_burst_length", "test/test_larpix.py::test_configuration_from_dict_reg_adc_burst_length", "test/test_larpix.py::test_configuration_from_dict_reg_channel_mask", "test/test_larpix.py::test_configuration_from_dict_reg_external_trigger_mask", "test/test_larpix.py::test_configuration_from_dict_reg_reset_cycles", "test/test_larpix.py::test_controller_init_chips", "test/test_larpix.py::test_controller_get_chip", "test/test_larpix.py::test_controller_serial_read_mock", "test/test_larpix.py::test_controller_serial_write_mock", "test/test_larpix.py::test_controller_serial_write_read_mock", "test/test_larpix.py::test_packetcollection_getitem_int", "test/test_larpix.py::test_packetcollection_getitem_int_bits", "test/test_larpix.py::test_packetcollection_getitem_slice", "test/test_larpix.py::test_packetcollection_getitem_slice_bits", "test/test_larpix.py::test_packetcollection_origin", "test/test_larpix.py::test_packetcollection_to_dict", "test/test_larpix.py::test_packetcollection_from_dict" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-11-29 10:12:26+00:00
bsd-3-clause
5,316
samkohn__larpix-control-74
diff --git a/larpix/larpix.py b/larpix/larpix.py index d4ae36b..a0efae8 100644 --- a/larpix/larpix.py +++ b/larpix/larpix.py @@ -1332,7 +1332,7 @@ class PacketCollection(object): d['message'] = str(self.message) d['read_id'] = 'None' if self.read_id is None else self.read_id d['bytestream'] = ('None' if self.bytestream is None else - self.bytestream.decode('utf-8')) + self.bytestream.decode('raw_unicode_escape')) return d def from_dict(self, d): @@ -1342,7 +1342,7 @@ class PacketCollection(object): ''' self.message = d['message'] self.read_id = d['read_id'] - self.bytestream = d['bytestream'].encode('utf-8') + self.bytestream = d['bytestream'].encode('raw_unicode_escape') self.parent = None self.packets = [] for p in d['packets']:
samkohn/larpix-control
345deb77ced183828f951008ad804a06819ccd52
diff --git a/test/test_larpix.py b/test/test_larpix.py index af9e035..8c5165b 100644 --- a/test/test_larpix.py +++ b/test/test_larpix.py @@ -189,7 +189,7 @@ def test_controller_save_output(tmpdir): 'parent': 'None', 'message': 'hi', 'read_id': 0, - 'bytestream': p.bytes().decode('utf-8') + 'bytestream': p.bytes().decode('raw_unicode_escape') } ] } @@ -1699,6 +1699,7 @@ def test_packetcollection_origin(): def test_packetcollection_to_dict(): packet = Packet() + packet.chipid = 246 packet.packet_type = Packet.TEST_PACKET collection = PacketCollection([packet], bytestream=packet.bytes(), message='hello') @@ -1708,11 +1709,11 @@ def test_packetcollection_to_dict(): 'parent': 'None', 'message': 'hello', 'read_id': 'None', - 'bytestream': packet.bytes().decode('utf-8'), + 'bytestream': packet.bytes().decode('raw_unicode_escape'), 'packets': [{ 'bits': packet.bits.bin, 'type': 'test', - 'chipid': 0, + 'chipid': packet.chipid, 'parity': 0, 'valid_parity': True, 'counter': 0
Some bytestreams don't parse well to JSON in Python 2 (PacketCollection.to_dict) ``UnicodeDecodeError: 'utf8' codec can't decode byte 0xd8 in position 1: invalid continuation byte``. Indeed byte ``b"\xd8"`` is in position 1. I think I'll need to insert some Python version logic into the to_dict and from_dict methods.
0.0
345deb77ced183828f951008ad804a06819ccd52
[ "test/test_larpix.py::test_packetcollection_to_dict" ]
[ "test/test_larpix.py::test_FakeSerialPort_write", "test/test_larpix.py::test_FakeSerialPort_read", "test/test_larpix.py::test_FakeSerialPort_read_multi", "test/test_larpix.py::test_chip_str", "test/test_larpix.py::test_chip_get_configuration_packets", "test/test_larpix.py::test_chip_sync_configuration", "test/test_larpix.py::test_chip_export_reads", "test/test_larpix.py::test_chip_export_reads_no_new_reads", "test/test_larpix.py::test_chip_export_reads_all", "test/test_larpix.py::test_controller_save_output", "test/test_larpix.py::test_controller_load", "test/test_larpix.py::test_packet_bits_bytes", "test/test_larpix.py::test_packet_init_default", "test/test_larpix.py::test_packet_init_bytestream", "test/test_larpix.py::test_packet_bytes_zeros", "test/test_larpix.py::test_packet_bytes_custom", "test/test_larpix.py::test_packet_bytes_properties", "test/test_larpix.py::test_packet_export_test", "test/test_larpix.py::test_packet_export_data", "test/test_larpix.py::test_packet_export_config_read", "test/test_larpix.py::test_packet_export_config_write", "test/test_larpix.py::test_packet_set_packet_type", "test/test_larpix.py::test_packet_get_packet_type", "test/test_larpix.py::test_packet_set_chipid", "test/test_larpix.py::test_packet_get_chipid", "test/test_larpix.py::test_packet_set_parity_bit_value", "test/test_larpix.py::test_packet_get_parity_bit_value", "test/test_larpix.py::test_packet_compute_parity", "test/test_larpix.py::test_packet_assign_parity", "test/test_larpix.py::test_packet_has_valid_parity", "test/test_larpix.py::test_packet_set_channel_id", "test/test_larpix.py::test_packet_get_channel_id", "test/test_larpix.py::test_packet_set_timestamp", "test/test_larpix.py::test_packet_get_timestamp", "test/test_larpix.py::test_packet_set_dataword", "test/test_larpix.py::test_packet_get_dataword", "test/test_larpix.py::test_packet_get_dataword_ADC_bug", "test/test_larpix.py::test_packet_set_fifo_half_flag", "test/test_larpix.py::test_packet_get_fifo_half_flag", "test/test_larpix.py::test_packet_set_fifo_full_flag", "test/test_larpix.py::test_packet_get_fifo_full_flag", "test/test_larpix.py::test_packet_set_register_address", "test/test_larpix.py::test_packet_get_register_address", "test/test_larpix.py::test_packet_set_register_data", "test/test_larpix.py::test_packet_get_register_data", "test/test_larpix.py::test_packet_set_test_counter", "test/test_larpix.py::test_packet_get_test_counter", "test/test_larpix.py::test_configuration_get_nondefault_registers", "test/test_larpix.py::test_configuration_get_nondefault_registers_array", "test/test_larpix.py::test_configuration_get_nondefault_registers_many_changes", "test/test_larpix.py::test_configuration_set_pixel_trim_thresholds", "test/test_larpix.py::test_configuration_get_pixel_trim_thresholds", "test/test_larpix.py::test_configuration_set_global_threshold", "test/test_larpix.py::test_configuration_get_global_threshold", "test/test_larpix.py::test_configuration_set_csa_gain", "test/test_larpix.py::test_configuration_get_csa_gain", "test/test_larpix.py::test_configuration_set_csa_bypass", "test/test_larpix.py::test_configuration_get_csa_bypass", "test/test_larpix.py::test_configuration_set_internal_bypass", "test/test_larpix.py::test_configuration_get_internal_bypass", "test/test_larpix.py::test_configuration_set_csa_bypass_select", "test/test_larpix.py::test_configuration_get_csa_bypass_select", "test/test_larpix.py::test_configuration_set_csa_monitor_select", "test/test_larpix.py::test_configuration_get_csa_monitor_select", "test/test_larpix.py::test_configuration_set_csa_testpulse_enable", "test/test_larpix.py::test_configuration_get_csa_testpulse_enable", "test/test_larpix.py::test_configuration_set_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_get_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_set_test_mode", "test/test_larpix.py::test_configuration_get_test_mode", "test/test_larpix.py::test_configuration_set_cross_trigger_mode", "test/test_larpix.py::test_configuration_get_cross_trigger_mode", "test/test_larpix.py::test_configuration_set_periodic_reset", "test/test_larpix.py::test_configuration_get_periodic_reset", "test/test_larpix.py::test_configuration_set_fifo_diagnostic", "test/test_larpix.py::test_configuration_get_fifo_diagnostic", "test/test_larpix.py::test_configuration_set_test_burst_length", "test/test_larpix.py::test_configuration_get_test_burst_length", "test/test_larpix.py::test_configuration_set_adc_burst_length", "test/test_larpix.py::test_configuration_get_adc_burst_length", "test/test_larpix.py::test_configuration_set_channel_mask", "test/test_larpix.py::test_configuration_get_channel_mask", "test/test_larpix.py::test_configuration_set_external_trigger_mask", "test/test_larpix.py::test_configuration_get_external_trigger_mask", "test/test_larpix.py::test_configuration_set_reset_cycles", "test/test_larpix.py::test_configuration_get_reset_cycles", "test/test_larpix.py::test_configuration_disable_channels", "test/test_larpix.py::test_configuration_disable_channels_default", "test/test_larpix.py::test_configuration_enable_channels", "test/test_larpix.py::test_configuration_enable_channels_default", "test/test_larpix.py::test_configuration_enable_external_trigger", "test/test_larpix.py::test_configuration_enable_external_trigger_default", "test/test_larpix.py::test_configuration_disable_external_trigger", "test/test_larpix.py::test_configuration_enable_testpulse", "test/test_larpix.py::test_configuration_enable_testpulse_default", "test/test_larpix.py::test_configuration_disable_testpulse", "test/test_larpix.py::test_configuration_disable_testpulse_default", "test/test_larpix.py::test_configuration_enable_analog_monitor", "test/test_larpix.py::test_configuration_disable_analog_monitor", "test/test_larpix.py::test_configuration_trim_threshold_data", "test/test_larpix.py::test_configuration_global_threshold_data", "test/test_larpix.py::test_configuration_csa_gain_and_bypasses_data", "test/test_larpix.py::test_configuration_csa_bypass_select_data", "test/test_larpix.py::test_configuration_csa_monitor_select_data", "test/test_larpix.py::test_configuration_csa_testpulse_enable_data", "test/test_larpix.py::test_configuration_csa_testpulse_dac_amplitude_data", "test/test_larpix.py::test_configuration_test_mode_xtrig_reset_diag_data", "test/test_larpix.py::test_configuration_sample_cycles_data", "test/test_larpix.py::test_configuration_test_burst_length_data", "test/test_larpix.py::test_configuration_adc_burst_length_data", "test/test_larpix.py::test_configuration_channel_mask_data", "test/test_larpix.py::test_configuration_external_trigger_mask_data", "test/test_larpix.py::test_configuration_reset_cycles_data", "test/test_larpix.py::test_configuration_to_dict", "test/test_larpix.py::test_configuration_from_dict", "test/test_larpix.py::test_configuration_write", "test/test_larpix.py::test_configuration_write_force", "test/test_larpix.py::test_configuration_read_absolute", "test/test_larpix.py::test_configuration_read_default", "test/test_larpix.py::test_configuration_read_local", "test/test_larpix.py::test_configuration_from_dict_reg_pixel_trim", "test/test_larpix.py::test_configuration_from_dict_reg_global_threshold", "test/test_larpix.py::test_configuration_from_dict_reg_csa_gain", "test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass", "test/test_larpix.py::test_configuration_from_dict_reg_internal_bypass", "test/test_larpix.py::test_configuration_from_dict_reg_csa_bypass_select", "test/test_larpix.py::test_configuration_from_dict_reg_csa_monitor_select", "test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_enable", "test/test_larpix.py::test_configuration_from_dict_reg_csa_testpulse_dac_amplitude", "test/test_larpix.py::test_configuration_from_dict_reg_test_mode", "test/test_larpix.py::test_configuration_from_dict_reg_cross_trigger_mode", "test/test_larpix.py::test_configuration_from_dict_reg_periodic_reset", "test/test_larpix.py::test_configuration_from_dict_reg_fifo_diagnostic", "test/test_larpix.py::test_configuration_from_dict_reg_sample_cycles", "test/test_larpix.py::test_configuration_from_dict_reg_test_burst_length", "test/test_larpix.py::test_configuration_from_dict_reg_adc_burst_length", "test/test_larpix.py::test_configuration_from_dict_reg_channel_mask", "test/test_larpix.py::test_configuration_from_dict_reg_external_trigger_mask", "test/test_larpix.py::test_configuration_from_dict_reg_reset_cycles", "test/test_larpix.py::test_controller_init_chips", "test/test_larpix.py::test_controller_get_chip", "test/test_larpix.py::test_controller_get_chip_all_chips", "test/test_larpix.py::test_controller_serial_read_mock", "test/test_larpix.py::test_controller_serial_write_mock", "test/test_larpix.py::test_controller_serial_write_read_mock", "test/test_larpix.py::test_packetcollection_getitem_int", "test/test_larpix.py::test_packetcollection_getitem_int_bits", "test/test_larpix.py::test_packetcollection_getitem_slice", "test/test_larpix.py::test_packetcollection_getitem_slice_bits", "test/test_larpix.py::test_packetcollection_origin", "test/test_larpix.py::test_packetcollection_from_dict" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-11-30 10:39:37+00:00
bsd-3-clause
5,317
sampsyo__wideq-74
diff --git a/.gitignore b/.gitignore index ca4300b..61b11f1 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .tox dist/ wideq_state.json +__pycache__ \ No newline at end of file diff --git a/example.py b/example.py index 05d9b65..1cbb55c 100755 --- a/example.py +++ b/example.py @@ -146,6 +146,8 @@ def ac_config(client, device_id): print(ac.get_filter_state()) print(ac.get_mfilter_state()) print(ac.get_energy_target()) + print(ac.get_power(), " watts") + print(ac.get_outdoor_power(), " watts") print(ac.get_volume()) print(ac.get_light()) print(ac.get_zones()) @@ -233,14 +235,14 @@ def main() -> None: args = parser.parse_args() country_regex = re.compile(r"^[A-Z]{2,3}$") if not country_regex.match(args.country): - print("Error: Country must be two or three letters" \ + print("Error: Country must be two or three letters" f" all upper case (e.g. US, NO, KR) got: '{args.country}'", file=sys.stderr) exit(1) language_regex = re.compile(r"^[a-z]{2,3}-[A-Z]{2,3}$") if not language_regex.match(args.language): - print("Error: Language must be a combination of language" \ - " and country (e.g. en-US, no-NO, kr-KR)" \ + print("Error: Language must be a combination of language" + " and country (e.g. en-US, no-NO, kr-KR)" f" got: '{args.language}'", file=sys.stderr) exit(1) diff --git a/wideq/ac.py b/wideq/ac.py index a9afaf5..f4ac1af 100644 --- a/wideq/ac.py +++ b/wideq/ac.py @@ -249,11 +249,28 @@ class ACDevice(Device): return self._get_config('EnergyDesiredValue') + def get_outdoor_power(self): + """Get instant power usage in watts of the outdoor unit""" + + value = self._get_config('OutTotalInstantPower') + return value['OutTotalInstantPower'] + + def get_power(self): + """Get the instant power usage in watts of the whole unit""" + + value = self._get_config('InOutInstantPower') + return value['InOutInstantPower'] + def get_light(self): """Get a Boolean indicating whether the display light is on.""" - value = self._get_control('DisplayControl') - return value == '0' # Seems backwards, but isn't. + try: + value = self._get_control('DisplayControl') + return value == '0' # Seems backwards, but isn't. + except FailedRequestError: + # Device does not support reporting display light status. + # Since it's probably not changeable the it must be on. + return True def get_volume(self): """Get the speaker volume level.""" diff --git a/wideq/client.py b/wideq/client.py index f6a1ae8..8369ae2 100644 --- a/wideq/client.py +++ b/wideq/client.py @@ -11,8 +11,6 @@ from typing import Any, Dict, Generator, List, Optional from . import core -DEFAULT_COUNTRY = 'US' -DEFAULT_LANGUAGE = 'en-US' #: Represents an unknown enum value. _UNKNOWN = 'Unknown' @@ -79,8 +77,8 @@ class Client(object): gateway: Optional[core.Gateway] = None, auth: Optional[core.Auth] = None, session: Optional[core.Session] = None, - country: str = DEFAULT_COUNTRY, - language: str = DEFAULT_LANGUAGE) -> None: + country: str = core.DEFAULT_COUNTRY, + language: str = core.DEFAULT_LANGUAGE) -> None: # The three steps required to get access to call the API. self._gateway: Optional[core.Gateway] = gateway self._auth: Optional[core.Auth] = auth @@ -146,12 +144,7 @@ class Client(object): client = cls() if 'gateway' in state: - data = state['gateway'] - client._gateway = core.Gateway( - data['auth_base'], data['api_root'], data['oauth_root'], - data.get('country', DEFAULT_COUNTRY), - data.get('language', DEFAULT_LANGUAGE), - ) + client._gateway = core.Gateway.deserialize(state['gateway']) if 'auth' in state: data = state['auth'] @@ -181,19 +174,10 @@ class Client(object): } if self._gateway: - out['gateway'] = { - 'auth_base': self._gateway.auth_base, - 'api_root': self._gateway.api_root, - 'oauth_root': self._gateway.oauth_root, - 'country': self._gateway.country, - 'language': self._gateway.language, - } + out['gateway'] = self._gateway.serialize() if self._auth: - out['auth'] = { - 'access_token': self._auth.access_token, - 'refresh_token': self._auth.refresh_token, - } + out['auth'] = self._auth.serialize() if self._session: out['session'] = self._session.session_id @@ -218,8 +202,8 @@ class Client(object): """ client = cls( - country=country or DEFAULT_COUNTRY, - language=language or DEFAULT_LANGUAGE, + country=country or core.DEFAULT_COUNTRY, + language=language or core.DEFAULT_LANGUAGE, ) client._auth = core.Auth(client.gateway, None, refresh_token) client.refresh() @@ -308,6 +292,7 @@ RangeValue = namedtuple('RangeValue', ['min', 'max', 'step']) #: This is a value that is a reference to another key in the data that is at #: the same level as the `Value` key. ReferenceValue = namedtuple('ReferenceValue', ['reference']) +StringValue = namedtuple('StringValue', ['comment']) class ModelInfo(object): @@ -322,7 +307,7 @@ class ModelInfo(object): :param name: The name to look up. :returns: One of (`BitValue`, `EnumValue`, `RangeValue`, - `ReferenceValue`). + `ReferenceValue`, `StringValue`). :raises ValueError: If an unsupported type is encountered. """ d = self.data['Value'][name] @@ -339,6 +324,8 @@ class ModelInfo(object): elif d['type'].lower() == 'reference': ref = d['option'][0] return ReferenceValue(self.data[ref]) + elif d['type'].lower() == 'string': + return StringValue(d.get('_comment', '')) else: raise ValueError( f"unsupported value name: '{name}'" diff --git a/wideq/core.py b/wideq/core.py index be976a8..7b2a806 100644 --- a/wideq/core.py +++ b/wideq/core.py @@ -18,6 +18,8 @@ CLIENT_ID = 'LGAO221A02' OAUTH_SECRET_KEY = 'c053c2a6ddeb7ad97cb0eed0dcb31cf8' OAUTH_CLIENT_KEY = 'LGAO221A02' DATE_FORMAT = '%a, %d %b %Y %H:%M:%S +0000' +DEFAULT_COUNTRY = 'US' +DEFAULT_LANGUAGE = 'en-US' def gen_uuid() -> str: @@ -253,6 +255,21 @@ class Gateway(object): def oauth_url(self): return oauth_url(self.auth_base, self.country, self.language) + def serialize(self) -> Dict[str, str]: + return { + 'auth_base': self.auth_base, + 'api_root': self.api_root, + 'oauth_root': self.oauth_root, + 'country': self.country, + 'language': self.language, + } + + @classmethod + def deserialize(cls, data: Dict[str, Any]) -> 'Gateway': + return cls(data['auth_base'], data['api_root'], data['oauth_root'], + data.get('country', DEFAULT_COUNTRY), + data.get('language', DEFAULT_LANGUAGE)) + class Auth(object): def __init__(self, gateway, access_token, refresh_token): @@ -286,6 +303,12 @@ class Auth(object): self.refresh_token) return Auth(self.gateway, new_access_token, self.refresh_token) + def serialize(self) -> Dict[str, str]: + return { + 'access_token': self.access_token, + 'refresh_token': self.refresh_token, + } + class Session(object): def __init__(self, auth, session_id) -> None:
sampsyo/wideq
72040db991d7a316d7437db0767798c8e7cbbc69
diff --git a/tests/test_client.py b/tests/test_client.py index 2aeffe2..a7f1f62 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,7 +1,7 @@ import unittest from wideq.client import ( - BitValue, EnumValue, ModelInfo, RangeValue, ReferenceValue) + BitValue, EnumValue, ModelInfo, RangeValue, ReferenceValue, StringValue) DATA = { @@ -66,10 +66,15 @@ DATA = { ], 'type': 'Bit' }, + 'TimeBsOn': { + '_comment': + '오전 12시 30분은 0030, 오후12시30분은 1230 ,오후 4시30분은 1630 off는 0 ', + 'type': 'String' + }, 'Unexpected': {'type': 'Unexpected'}, - 'StringOption': { - 'type': 'String', - 'option': 'some string' + 'Unexpected2': { + 'type': 'Unexpected', + 'option': 'some option' }, }, 'Course': { @@ -120,6 +125,12 @@ class ModelInfoTest(unittest.TestCase): expected = ReferenceValue(DATA['Course']) self.assertEqual(expected, actual) + def test_string(self): + actual = self.model_info.value('TimeBsOn') + expected = StringValue( + "오전 12시 30분은 0030, 오후12시30분은 1230 ,오후 4시30분은 1630 off는 0 ") + self.assertEqual(expected, actual) + def test_value_unsupported(self): data = "{'type': 'Unexpected'}" with self.assertRaisesRegex( @@ -129,9 +140,9 @@ class ModelInfoTest(unittest.TestCase): self.model_info.value('Unexpected') def test_value_unsupported_but_data_available(self): - data = "{'type': 'String', 'option': 'some string'}" + data = "{'type': 'Unexpected', 'option': 'some option'}" with self.assertRaisesRegex( ValueError, - f"unsupported value name: 'StringOption'" - f" type: 'String' data: '{data}"): - self.model_info.value('StringOption') + f"unsupported value name: 'Unexpected2'" + f" type: 'Unexpected' data: '{data}"): + self.model_info.value('Unexpected2')
ValueError: unsupported value type String % python3 example.py -c BR -l pt-BR mon d27c7740-7149-11d3-10b4-7440be9deeb2 Polling... Polling... Polling... - Operation: @AC_MAIN_OPERATION_RIGHT_ON_W - OpMode: @AC_MAIN_OPERATION_MODE_DRY_W - WindStrength: @AC_MAIN_WIND_STRENGTH_LOW_W - TempUnit: NS - TempCur: 28.5 (0.5-39.5) - TempCfg: 25 (18-30) - GroupType: 1 - GroupType: 1 (18-30) - SleepTime: 0 (30-420) - OnTime: 0 (0-1440) - OffTime: 0 (0-1440) - RacAddFunc: @NON - ExtraOp: @OFF - DiagCode: @AC_SMART_DIAGNOSIS_RESULT_NORMAL_S Traceback (most recent call last): File "example.py", line 230, in <module> main() File "example.py", line 226, in main example(args.country, args.language, args.cmd, args.args) File "example.py", line 186, in example example_command(client, cmd, args) File "example.py", line 162, in example_command func(client, *args) File "example.py", line 52, in mon desc = model.value(key) File "/Users/david/dev/unsorted/wideq/wideq/client.py", line 338, in value raise ValueError("unsupported value type {}".format(d['type'])) ValueError: unsupported value type String
0.0
72040db991d7a316d7437db0767798c8e7cbbc69
[ "tests/test_client.py::ModelInfoTest::test_string", "tests/test_client.py::ModelInfoTest::test_value_bit", "tests/test_client.py::ModelInfoTest::test_value_enum", "tests/test_client.py::ModelInfoTest::test_value_range", "tests/test_client.py::ModelInfoTest::test_value_reference", "tests/test_client.py::ModelInfoTest::test_value_unsupported", "tests/test_client.py::ModelInfoTest::test_value_unsupported_but_data_available" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-01-14 13:45:19+00:00
mit
5,318
sangoma__ursine-12
diff --git a/ursine/uri.py b/ursine/uri.py index e7feacc..57be602 100644 --- a/ursine/uri.py +++ b/ursine/uri.py @@ -200,6 +200,16 @@ class URI: else: return uri + def short_uri(self): + if self.user and self.password: + user = f'{self.user}:{self.password}@' + elif self.user: + user = f'{self.user}@' + else: + user = '' + + return f'{self.scheme}:{user}{self.host}:{self.port}' + def __repr__(self): return f'{self.__class__.__name__}({self})'
sangoma/ursine
b9523c22a724b42e84e2e3093cb02b801e03fa70
diff --git a/tests/test_uri.py b/tests/test_uri.py index d74630d..36a8806 100644 --- a/tests/test_uri.py +++ b/tests/test_uri.py @@ -29,6 +29,19 @@ def test_to_str(uri, expect): assert str(URI(uri)) == expect [email protected]('uri,expect', [ + ('sip:localhost', 'sip:localhost:5060'), + ('sips:localhost', 'sips:localhost:5061'), + ('<sip:localhost>', 'sip:localhost:5060'), + ( + 'John Doe <sip:localhost:5080?x=y&a=b>', + 'sip:localhost:5080', + ) +]) +def test_to_short_uri(uri, expect): + assert URI(uri).short_uri() == expect + + @pytest.mark.parametrize('uri,expect', [ ('sip:localhost', 'URI(sip:localhost:5060;transport=udp)'), ('sips:localhost', 'URI(sips:localhost:5061;transport=tcp)'),
Missing `short_uri` aiosip needs this method to generate URI addresses.
0.0
b9523c22a724b42e84e2e3093cb02b801e03fa70
[ "tests/test_uri.py::test_to_short_uri[sip:localhost-sip:localhost:5060]", "tests/test_uri.py::test_to_short_uri[sips:localhost-sips:localhost:5061]", "tests/test_uri.py::test_to_short_uri[<sip:localhost>-sip:localhost:5060]", "tests/test_uri.py::test_to_short_uri[John" ]
[ "tests/test_uri.py::test_invalid[sip:localhost:port]", "tests/test_uri.py::test_invalid[sip:localhost:0]", "tests/test_uri.py::test_invalid[sip:localhost:70000]", "tests/test_uri.py::test_invalid[sip:localhost?]", "tests/test_uri.py::test_invalid[sip:localhost;]", "tests/test_uri.py::test_invalid[sip:localhost&]", "tests/test_uri.py::test_to_str[sip:localhost-sip:localhost:5060;transport=udp]", "tests/test_uri.py::test_to_str[sips:localhost-sips:localhost:5061;transport=tcp]", "tests/test_uri.py::test_to_str[<sip:localhost>-sip:localhost:5060;transport=udp]", "tests/test_uri.py::test_to_str[John", "tests/test_uri.py::test_repr[sip:localhost-URI(sip:localhost:5060;transport=udp)]", "tests/test_uri.py::test_repr[sips:localhost-URI(sips:localhost:5061;transport=tcp)]", "tests/test_uri.py::test_equality[sip:localhost-sip:localhost]", "tests/test_uri.py::test_equality[sip:localhost-sip:localhost;transport=udp]", "tests/test_uri.py::test_equality[<sip:localhost>-sip:localhost]", "tests/test_uri.py::test_equality[Alice", "tests/test_uri.py::test_equality[SIP:localhost-sip:localhost]", "tests/test_uri.py::test_equality[<sip:localhost>;tag=foo-sip:localhost;tag=foo]", "tests/test_uri.py::test_equality[<sip:localhost>", "tests/test_uri.py::test_inequality[sip:localhost-sips:localhost]", "tests/test_uri.py::test_inequality[Bob", "tests/test_uri.py::test_inequality[Alice", "tests/test_uri.py::test_inequality[sip:remotehost-sip:localhost]", "tests/test_uri.py::test_build[kwargs0-sip:localhost]", "tests/test_uri.py::test_build[kwargs1-sip:localhost;transport=tcp]", "tests/test_uri.py::test_build[kwargs2-sips:[::1]:5080;maddr=[::dead:beef]?x=y&a=]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-user-jdoe-sip:jdoe@localhost]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost;transport=tcp-scheme-sips-sips:localhost:5060]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-port-5080-sip:localhost:5080]", "tests/test_uri.py::test_modified_uri_creation[sip:jdoe@localhost-user-None-sip:localhost]", "tests/test_uri.py::test_modified_uri_creation[\"Mark\"", "tests/test_uri.py::test_modified_uri_creation[sip:user:pass@localhost-user-None-sip:localhost]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-user-user:pass-sip:user:pass@localhost]", "tests/test_uri.py::test_modified_uri_creation[sip:alice@localhost-password-pass-sip:alice:pass@localhost]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-transport-tcp-sip:localhost;transport=tcp]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-tag-bler-sip:localhost;transport=udp;tag=bler]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-parameters-new10-sip:localhost;maddr=[::1];foo=bar;x=]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-headers-new11-sip:localhost?ahhhh=&foo=bar]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-parameters-new12-sip:localhost;maddr=[::1];foo=bar;x=]", "tests/test_uri.py::test_modified_uri_creation[sip:localhost-headers-new13-sip:localhost?ahhhh=&foo=bar]", "tests/test_uri.py::test_tag_generation[sip:localhost-None-None]", "tests/test_uri.py::test_tag_generation[sip:localhost-5654-5654]", "tests/test_uri.py::test_tag_generation[sip:localhost;tag=2000-5654-5654]", "tests/test_uri.py::test_tag_generation[sip:localhost;tag=2ace-None-2ace]" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2018-04-27 21:56:42+00:00
apache-2.0
5,319
sanic-org__sanic-2578
diff --git a/sanic/worker/loader.py b/sanic/worker/loader.py index abdcc987..344593db 100644 --- a/sanic/worker/loader.py +++ b/sanic/worker/loader.py @@ -5,18 +5,10 @@ import sys from importlib import import_module from pathlib import Path -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Optional, - Type, - Union, - cast, -) +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union, cast -from sanic.http.tls.creators import CertCreator, MkcertCreator, TrustmeCreator +from sanic.http.tls.context import process_to_context +from sanic.http.tls.creators import MkcertCreator, TrustmeCreator if TYPE_CHECKING: @@ -106,21 +98,30 @@ class AppLoader: class CertLoader: - _creator_class: Type[CertCreator] + _creators = { + "mkcert": MkcertCreator, + "trustme": TrustmeCreator, + } def __init__(self, ssl_data: Dict[str, Union[str, os.PathLike]]): - creator_name = ssl_data.get("creator") - if creator_name not in ("mkcert", "trustme"): + self._ssl_data = ssl_data + + creator_name = cast(str, ssl_data.get("creator")) + + self._creator_class = self._creators.get(creator_name) + if not creator_name: + return + + if not self._creator_class: raise RuntimeError(f"Unknown certificate creator: {creator_name}") - elif creator_name == "mkcert": - self._creator_class = MkcertCreator - elif creator_name == "trustme": - self._creator_class = TrustmeCreator self._key = ssl_data["key"] self._cert = ssl_data["cert"] self._localhost = cast(str, ssl_data["localhost"]) def load(self, app: SanicApp): + if not self._creator_class: + return process_to_context(self._ssl_data) + creator = self._creator_class(app, self._key, self._cert) return creator.generate_cert(self._localhost)
sanic-org/sanic
3f4663b9f8715119130efe1bfe517f70b356939e
diff --git a/tests/test_tls.py b/tests/test_tls.py index 6c369f92..497b67de 100644 --- a/tests/test_tls.py +++ b/tests/test_tls.py @@ -4,6 +4,7 @@ import ssl import subprocess from contextlib import contextmanager +from multiprocessing import Event from pathlib import Path from unittest.mock import Mock, patch from urllib.parse import urlparse @@ -636,3 +637,29 @@ def test_sanic_ssl_context_create(): assert sanic_context is context assert isinstance(sanic_context, SanicSSLContext) + + +def test_ssl_in_multiprocess_mode(app: Sanic, caplog): + + ssl_dict = {"cert": localhost_cert, "key": localhost_key} + event = Event() + + @app.main_process_start + async def main_start(app: Sanic): + app.shared_ctx.event = event + + @app.after_server_start + async def shutdown(app): + app.shared_ctx.event.set() + app.stop() + + assert not event.is_set() + with caplog.at_level(logging.INFO): + app.run(ssl=ssl_dict) + assert event.is_set() + + assert ( + "sanic.root", + logging.INFO, + "Goin' Fast @ https://127.0.0.1:8000", + ) in caplog.record_tuples diff --git a/tests/worker/test_loader.py b/tests/worker/test_loader.py index 6f953c54..d0d04e9a 100644 --- a/tests/worker/test_loader.py +++ b/tests/worker/test_loader.py @@ -86,6 +86,10 @@ def test_input_is_module(): @patch("sanic.worker.loader.TrustmeCreator") @patch("sanic.worker.loader.MkcertCreator") def test_cert_loader(MkcertCreator: Mock, TrustmeCreator: Mock, creator: str): + CertLoader._creators = { + "mkcert": MkcertCreator, + "trustme": TrustmeCreator, + } MkcertCreator.return_value = MkcertCreator TrustmeCreator.return_value = TrustmeCreator data = {
Certificates not created with `mkcert` or `trustme` raise a RuntimeError The `CertLoader` class in `sanic-org/sanic/sanic/worker/loader.py` checks the creator of the certificate. If the creator is not `mkcert` or `trustme` then it raises a `RuntimeError`. This will prevent Sanic from running with certificates from any other sources.
0.0
3f4663b9f8715119130efe1bfe517f70b356939e
[ "tests/test_tls.py::test_ssl_in_multiprocess_mode" ]
[ "tests/test_tls.py::test_url_attributes_with_ssl_context[/foo--https://{}:{}/foo]", "tests/test_tls.py::test_url_attributes_with_ssl_context[/bar/baz--https://{}:{}/bar/baz]", "tests/test_tls.py::test_url_attributes_with_ssl_context[/moo/boo-arg1=val1-https://{}:{}/moo/boo?arg1=val1]", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/foo--https://{}:{}/foo]", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/bar/baz--https://{}:{}/bar/baz]", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/moo/boo-arg1=val1-https://{}:{}/moo/boo?arg1=val1]", "tests/test_tls.py::test_cert_sni_single", "tests/test_tls.py::test_cert_sni_list", "tests/test_tls.py::test_invalid_ssl_dict", "tests/test_tls.py::test_invalid_ssl_type", "tests/test_tls.py::test_cert_file_on_pathlist", "tests/test_tls.py::test_missing_cert_path", "tests/test_tls.py::test_missing_cert_file", "tests/test_tls.py::test_no_certs_on_list", "tests/test_tls.py::test_logger_vhosts", "tests/test_tls.py::test_mk_cert_creator_default", "tests/test_tls.py::test_mk_cert_creator_is_supported", "tests/test_tls.py::test_mk_cert_creator_is_not_supported", "tests/test_tls.py::test_mk_cert_creator_generate_cert_default", "tests/test_tls.py::test_mk_cert_creator_generate_cert_localhost", "tests/test_tls.py::test_trustme_creator_default", "tests/test_tls.py::test_trustme_creator_is_supported", "tests/test_tls.py::test_trustme_creator_is_not_supported", "tests/test_tls.py::test_trustme_creator_generate_cert_default", "tests/test_tls.py::test_trustme_creator_generate_cert_localhost", "tests/test_tls.py::test_get_ssl_context_with_ssl_context", "tests/test_tls.py::test_get_ssl_context_in_production", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-True-False-True-False-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-True-True-True-False-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-False-True-False-True-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-False-False-False-False-Sanic", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-True-False-True-False-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-True-True-True-False-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-False-True-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-False-False-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-True-False-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-True-True-False-True-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-False-True-False-True-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-False-False-False-False-Nope]", "tests/test_tls.py::test_sanic_ssl_context_create", "tests/worker/test_loader.py::test_load_app_instance[tests.fake.server:app]", "tests/worker/test_loader.py::test_load_app_instance[tests.fake.server.app]", "tests/worker/test_loader.py::test_load_app_factory[tests.fake.server:create_app]", "tests/worker/test_loader.py::test_load_app_factory[tests.fake.server:create_app()]", "tests/worker/test_loader.py::test_load_app_simple", "tests/worker/test_loader.py::test_create_with_factory", "tests/worker/test_loader.py::test_cwd_in_path", "tests/worker/test_loader.py::test_input_is_factory", "tests/worker/test_loader.py::test_input_is_module", "tests/worker/test_loader.py::test_cert_loader[mkcert]", "tests/worker/test_loader.py::test_cert_loader[trustme]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-10-19 17:21:31+00:00
mit
5,320
sanic-org__sanic-2615
diff --git a/sanic/http/http1.py b/sanic/http/http1.py index ccfae75d..0cf2fd11 100644 --- a/sanic/http/http1.py +++ b/sanic/http/http1.py @@ -16,6 +16,7 @@ from sanic.exceptions import ( PayloadTooLarge, RequestCancelled, ServerError, + ServiceUnavailable, ) from sanic.headers import format_http1_response from sanic.helpers import has_message_body @@ -428,8 +429,11 @@ class Http(Stream, metaclass=TouchUpMeta): if self.request is None: self.create_empty_request() + request_middleware = not isinstance(exception, ServiceUnavailable) try: - await app.handle_exception(self.request, exception) + await app.handle_exception( + self.request, exception, request_middleware + ) except Exception as e: await app.handle_exception(self.request, e, False) diff --git a/sanic/request.py b/sanic/request.py index f7b3b999..8b8d9530 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -104,6 +104,7 @@ class Request: "_protocol", "_remote_addr", "_request_middleware_started", + "_response_middleware_started", "_scheme", "_socket", "_stream_id", @@ -179,6 +180,7 @@ class Request: Tuple[bool, bool, str, str], List[Tuple[str, str]] ] = defaultdict(list) self._request_middleware_started = False + self._response_middleware_started = False self.responded: bool = False self.route: Optional[Route] = None self.stream: Optional[Stream] = None @@ -337,7 +339,8 @@ class Request: middleware = ( self.route and self.route.extra.response_middleware ) or self.app.response_middleware - if middleware: + if middleware and not self._response_middleware_started: + self._response_middleware_started = True response = await self.app._run_response_middleware( self, response, middleware )
sanic-org/sanic
f32437bf1344cbc2ca2b0cbf3062ab04a93157bb
diff --git a/tests/test_middleware.py b/tests/test_middleware.py index a2034450..6589f4a4 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -1,6 +1,6 @@ import logging -from asyncio import CancelledError +from asyncio import CancelledError, sleep from itertools import count from sanic.exceptions import NotFound @@ -318,6 +318,32 @@ def test_middleware_return_response(app): resp1 = await request.respond() return resp1 - _, response = app.test_client.get("/") + app.test_client.get("/") assert response_middleware_run_count == 1 assert request_middleware_run_count == 1 + + +def test_middleware_run_on_timeout(app): + app.config.RESPONSE_TIMEOUT = 0.1 + response_middleware_run_count = 0 + request_middleware_run_count = 0 + + @app.on_response + def response(_, response): + nonlocal response_middleware_run_count + response_middleware_run_count += 1 + + @app.on_request + def request(_): + nonlocal request_middleware_run_count + request_middleware_run_count += 1 + + @app.get("/") + async def handler(request): + resp1 = await request.respond() + await sleep(1) + return resp1 + + app.test_client.get("/") + assert request_middleware_run_count == 1 + assert response_middleware_run_count == 1
Sanic 22.9.1 entered into the request middlewire twice when response timeout ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug I'm trying to do perforamance test for our apps about new Sanic version v22.9.1 (old version is 22.6.0) During performance testing ,my handler code is slow as expected, and my response time for sanic is 60 seconds Normally, it will return a "response timeout error" to the client, and we test the 22.6.0, and everything works as designe. But after upgrade to 22.9.1(The only change for the code), we see a new err which should be the failure inside one of our blueprint request middlewire. Normally the code will only run once. but in the new version, we see the function was called twice, and the interval between the two calls is longger than response timeout setting. It's very easy to repeat the situation. seems like sanic change involve this. ### Code snippet ```import asyncio from sanic import Blueprint, Sanic from sanic.request import Request from sanic.response import HTTPResponse from sanic.response import text class AsyncNorthHandler(): FUNCCOUNT = 0 async def http_handler(request): print("handling the request") await asyncio.sleep(100) return text('ok') bp = Blueprint("async_north") bp.add_route(http_handler, '/', methods=['GET'], name='handler') @bp.middleware("request") async def set_req_header(request): request: Request AsyncNorthHandler.FUNCCOUNT = AsyncNorthHandler.FUNCCOUNT + 1 print("enter the function {} time".format(AsyncNorthHandler.FUNCCOUNT)) app = Sanic("TEST") app.blueprint(bp) app.run(host='0.0.0.0', port=8888) ``` ### Expected Behavior entery the reqeust middlewire 1 time every request ### How do you run Sanic? As a module ### Operating System linux ### Sanic Version 22.9.1 ### Additional context _No response_
0.0
f32437bf1344cbc2ca2b0cbf3062ab04a93157bb
[ "tests/test_middleware.py::test_middleware_run_on_timeout" ]
[ "tests/test_middleware.py::test_middleware_request", "tests/test_middleware.py::test_middleware_request_as_convenience", "tests/test_middleware.py::test_middleware_response", "tests/test_middleware.py::test_middleware_response_as_convenience", "tests/test_middleware.py::test_middleware_response_as_convenience_called", "tests/test_middleware.py::test_middleware_response_exception", "tests/test_middleware.py::test_middleware_response_raise_cancelled_error", "tests/test_middleware.py::test_middleware_response_raise_exception", "tests/test_middleware.py::test_middleware_override_request", "tests/test_middleware.py::test_middleware_override_response", "tests/test_middleware.py::test_middleware_order", "tests/test_middleware.py::test_request_middleware_executes_once", "tests/test_middleware.py::test_middleware_added_response", "tests/test_middleware.py::test_middleware_return_response" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-07 13:28:31+00:00
mit
5,321
sanic-org__sanic-2636
diff --git a/sanic/app.py b/sanic/app.py index 8d098663..cbefcc4d 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -61,7 +61,7 @@ from sanic.exceptions import ( URLBuildError, ) from sanic.handlers import ErrorHandler -from sanic.helpers import Default +from sanic.helpers import Default, _default from sanic.http import Stage from sanic.log import ( LOGGING_CONFIG_DEFAULTS, @@ -69,6 +69,7 @@ from sanic.log import ( error_logger, logger, ) +from sanic.middleware import Middleware, MiddlewareLocation from sanic.mixins.listeners import ListenerEvent from sanic.mixins.startup import StartupMixin from sanic.models.futures import ( @@ -294,8 +295,12 @@ class Sanic(BaseSanic, StartupMixin, metaclass=TouchUpMeta): return listener def register_middleware( - self, middleware: MiddlewareType, attach_to: str = "request" - ) -> MiddlewareType: + self, + middleware: Union[MiddlewareType, Middleware], + attach_to: str = "request", + *, + priority: Union[Default, int] = _default, + ) -> Union[MiddlewareType, Middleware]: """ Register an application level middleware that will be attached to all the API URLs registered under this application. @@ -311,19 +316,37 @@ class Sanic(BaseSanic, StartupMixin, metaclass=TouchUpMeta): **response** - Invoke before the response is returned back :return: decorated method """ - if attach_to == "request": + retval = middleware + location = MiddlewareLocation[attach_to.upper()] + + if not isinstance(middleware, Middleware): + middleware = Middleware( + middleware, + location=location, + priority=priority if isinstance(priority, int) else 0, + ) + elif middleware.priority != priority and isinstance(priority, int): + middleware = Middleware( + middleware.func, + location=middleware.location, + priority=priority, + ) + + if location is MiddlewareLocation.REQUEST: if middleware not in self.request_middleware: self.request_middleware.append(middleware) - if attach_to == "response": + if location is MiddlewareLocation.RESPONSE: if middleware not in self.response_middleware: self.response_middleware.appendleft(middleware) - return middleware + return retval def register_named_middleware( self, middleware: MiddlewareType, route_names: Iterable[str], attach_to: str = "request", + *, + priority: Union[Default, int] = _default, ): """ Method for attaching middleware to specific routes. This is mainly an @@ -337,19 +360,35 @@ class Sanic(BaseSanic, StartupMixin, metaclass=TouchUpMeta): defaults to "request" :type attach_to: str, optional """ - if attach_to == "request": + retval = middleware + location = MiddlewareLocation[attach_to.upper()] + + if not isinstance(middleware, Middleware): + middleware = Middleware( + middleware, + location=location, + priority=priority if isinstance(priority, int) else 0, + ) + elif middleware.priority != priority and isinstance(priority, int): + middleware = Middleware( + middleware.func, + location=middleware.location, + priority=priority, + ) + + if location is MiddlewareLocation.REQUEST: for _rn in route_names: if _rn not in self.named_request_middleware: self.named_request_middleware[_rn] = deque() if middleware not in self.named_request_middleware[_rn]: self.named_request_middleware[_rn].append(middleware) - if attach_to == "response": + if location is MiddlewareLocation.RESPONSE: for _rn in route_names: if _rn not in self.named_response_middleware: self.named_response_middleware[_rn] = deque() if middleware not in self.named_response_middleware[_rn]: self.named_response_middleware[_rn].appendleft(middleware) - return middleware + return retval def _apply_exception_handler( self, diff --git a/sanic/middleware.py b/sanic/middleware.py index 5bbd777b..0c6058fa 100644 --- a/sanic/middleware.py +++ b/sanic/middleware.py @@ -32,6 +32,9 @@ class Middleware: def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) + def __hash__(self) -> int: + return hash(self.func) + def __repr__(self) -> str: return ( f"{self.__class__.__name__}("
sanic-org/sanic
911485d52e45a895a938f5dc62f3ed8e8fc031e5
diff --git a/tests/test_middleware_priority.py b/tests/test_middleware_priority.py index 9646f6d0..c16f658b 100644 --- a/tests/test_middleware_priority.py +++ b/tests/test_middleware_priority.py @@ -3,7 +3,7 @@ from functools import partial import pytest from sanic import Sanic -from sanic.middleware import Middleware +from sanic.middleware import Middleware, MiddlewareLocation from sanic.response import json @@ -40,6 +40,86 @@ def reset_middleware(): Middleware.reset_count() +def test_add_register_priority(app: Sanic): + def foo(*_): + ... + + app.register_middleware(foo, priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 0 + assert app.request_middleware[0].priority == 999 # type: ignore + app.register_middleware(foo, attach_to="response", priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 1 + assert app.response_middleware[0].priority == 999 # type: ignore + + +def test_add_register_named_priority(app: Sanic): + def foo(*_): + ... + + app.register_named_middleware(foo, route_names=["foo"], priority=999) + assert len(app.named_request_middleware) == 1 + assert len(app.named_response_middleware) == 0 + assert app.named_request_middleware["foo"][0].priority == 999 # type: ignore + app.register_named_middleware( + foo, attach_to="response", route_names=["foo"], priority=999 + ) + assert len(app.named_request_middleware) == 1 + assert len(app.named_response_middleware) == 1 + assert app.named_response_middleware["foo"][0].priority == 999 # type: ignore + + +def test_add_decorator_priority(app: Sanic): + def foo(*_): + ... + + app.middleware(foo, priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 0 + assert app.request_middleware[0].priority == 999 # type: ignore + app.middleware(foo, attach_to="response", priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 1 + assert app.response_middleware[0].priority == 999 # type: ignore + + +def test_add_convenience_priority(app: Sanic): + def foo(*_): + ... + + app.on_request(foo, priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 0 + assert app.request_middleware[0].priority == 999 # type: ignore + app.on_response(foo, priority=999) + assert len(app.request_middleware) == 1 + assert len(app.response_middleware) == 1 + assert app.response_middleware[0].priority == 999 # type: ignore + + +def test_add_conflicting_priority(app: Sanic): + def foo(*_): + ... + + middleware = Middleware(foo, MiddlewareLocation.REQUEST, priority=998) + app.register_middleware(middleware=middleware, priority=999) + assert app.request_middleware[0].priority == 999 # type: ignore + middleware.priority == 998 + + +def test_add_conflicting_priority_named(app: Sanic): + def foo(*_): + ... + + middleware = Middleware(foo, MiddlewareLocation.REQUEST, priority=998) + app.register_named_middleware( + middleware=middleware, route_names=["foo"], priority=999 + ) + assert app.named_request_middleware["foo"][0].priority == 999 # type: ignore + middleware.priority == 998 + + @pytest.mark.parametrize( "expected,priorities", PRIORITY_TEST_CASES,
Missing priority functionality in app-wide middlware ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug In v22.9 the priority feature was added, but unfortunately it appears it was overlooked and there is priority parameter to `register_middleware()` for `Sanic`. I am looking to use this feature because I have a Blueprint-specific middleware which appears to run before the application-wide middleware. In my case the application-wide middleware does authorization and updates `request.ctx` which is then used in the Blueprint-specific middleware. ### Code snippet _No response_ ### Expected Behavior _No response_ ### How do you run Sanic? ASGI ### Operating System Windows ### Sanic Version Sanic 22.9.1; Routing 22.8.0 ### Additional context _No response_
0.0
911485d52e45a895a938f5dc62f3ed8e8fc031e5
[ "tests/test_middleware_priority.py::test_add_register_priority", "tests/test_middleware_priority.py::test_add_register_named_priority", "tests/test_middleware_priority.py::test_add_conflicting_priority", "tests/test_middleware_priority.py::test_add_conflicting_priority_named" ]
[ "tests/test_middleware_priority.py::test_add_decorator_priority", "tests/test_middleware_priority.py::test_add_convenience_priority", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected0-priorities0]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected1-priorities1]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected2-priorities2]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected3-priorities3]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected4-priorities4]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected5-priorities5]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected6-priorities6]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected7-priorities7]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected8-priorities8]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected9-priorities9]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected10-priorities10]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected11-priorities11]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected12-priorities12]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected13-priorities13]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected14-priorities14]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected15-priorities15]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected16-priorities16]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected17-priorities17]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected18-priorities18]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected19-priorities19]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected20-priorities20]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected21-priorities21]", "tests/test_middleware_priority.py::test_request_middleware_order_priority[expected22-priorities22]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected0-priorities0]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected1-priorities1]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected2-priorities2]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected3-priorities3]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected4-priorities4]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected5-priorities5]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected6-priorities6]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected7-priorities7]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected8-priorities8]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected9-priorities9]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected10-priorities10]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected11-priorities11]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected12-priorities12]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected13-priorities13]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected14-priorities14]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected15-priorities15]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected16-priorities16]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected17-priorities17]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected18-priorities18]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected19-priorities19]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected20-priorities20]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected21-priorities21]", "tests/test_middleware_priority.py::test_response_middleware_order_priority[expected22-priorities22]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-12-18 13:04:05+00:00
mit
5,322
sanic-org__sanic-2651
diff --git a/sanic/server/websockets/connection.py b/sanic/server/websockets/connection.py index 87881b84..8ff19da6 100644 --- a/sanic/server/websockets/connection.py +++ b/sanic/server/websockets/connection.py @@ -45,7 +45,7 @@ class WebSocketConnection: await self._send(message) - async def recv(self, *args, **kwargs) -> Optional[str]: + async def recv(self, *args, **kwargs) -> Optional[Union[str, bytes]]: message = await self._receive() if message["type"] == "websocket.receive": @@ -53,7 +53,7 @@ class WebSocketConnection: return message["text"] except KeyError: try: - return message["bytes"].decode() + return message["bytes"] except KeyError: raise InvalidUsage("Bad ASGI message received") elif message["type"] == "websocket.disconnect":
sanic-org/sanic
c7a71cd00c10334d4440a1a8b23b480ac7b987f6
diff --git a/tests/test_asgi.py b/tests/test_asgi.py index 0c76a67f..fe9ff306 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -342,7 +342,7 @@ async def test_websocket_send(send, receive, message_stack): @pytest.mark.asyncio -async def test_websocket_receive(send, receive, message_stack): +async def test_websocket_text_receive(send, receive, message_stack): msg = {"text": "hello", "type": "websocket.receive"} message_stack.append(msg) @@ -351,6 +351,15 @@ async def test_websocket_receive(send, receive, message_stack): assert text == msg["text"] [email protected] +async def test_websocket_bytes_receive(send, receive, message_stack): + msg = {"bytes": b"hello", "type": "websocket.receive"} + message_stack.append(msg) + + ws = WebSocketConnection(send, receive) + data = await ws.receive() + + assert data == msg["bytes"] @pytest.mark.asyncio async def test_websocket_accept_with_no_subprotocols(
ASGI websocket must pass thru bytes as is _Originally posted by @Tronic in https://github.com/sanic-org/sanic/pull/2640#discussion_r1058027028_
0.0
c7a71cd00c10334d4440a1a8b23b480ac7b987f6
[ "tests/test_asgi.py::test_websocket_bytes_receive" ]
[ "tests/test_asgi.py::test_mockprotocol_events", "tests/test_asgi.py::test_protocol_push_data", "tests/test_asgi.py::test_websocket_send", "tests/test_asgi.py::test_websocket_text_receive", "tests/test_asgi.py::test_websocket_accept_with_no_subprotocols", "tests/test_asgi.py::test_websocket_accept_with_subprotocol", "tests/test_asgi.py::test_websocket_accept_with_multiple_subprotocols", "tests/test_asgi.py::test_improper_websocket_connection", "tests/test_asgi.py::test_request_class_regular", "tests/test_asgi.py::test_request_class_custom", "tests/test_asgi.py::test_cookie_customization", "tests/test_asgi.py::test_content_type", "tests/test_asgi.py::test_request_handle_exception", "tests/test_asgi.py::test_request_exception_suppressed_by_middleware", "tests/test_asgi.py::test_signals_triggered", "tests/test_asgi.py::test_asgi_serve_location", "tests/test_asgi.py::test_error_on_lifespan_exception_start", "tests/test_asgi.py::test_error_on_lifespan_exception_stop" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2023-01-08 03:15:02+00:00
mit
5,323
sanic-org__sanic-2668
diff --git a/sanic/errorpages.py b/sanic/errorpages.py index c20896db..77b1a3b7 100644 --- a/sanic/errorpages.py +++ b/sanic/errorpages.py @@ -22,6 +22,7 @@ from traceback import extract_tb from sanic.exceptions import BadRequest, SanicException from sanic.helpers import STATUS_CODES +from sanic.log import deprecation, logger from sanic.response import html, json, text @@ -42,6 +43,7 @@ FALLBACK_TEXT = ( "cannot complete your request." ) FALLBACK_STATUS = 500 +JSON = "application/json" class BaseRenderer: @@ -390,21 +392,18 @@ def escape(text): return f"{text}".replace("&", "&amp;").replace("<", "&lt;") -RENDERERS_BY_CONFIG = { - "html": HTMLRenderer, - "json": JSONRenderer, - "text": TextRenderer, +MIME_BY_CONFIG = { + "text": "text/plain", + "json": "application/json", + "html": "text/html", } - +CONFIG_BY_MIME = {v: k for k, v in MIME_BY_CONFIG.items()} RENDERERS_BY_CONTENT_TYPE = { "text/plain": TextRenderer, "application/json": JSONRenderer, "multipart/form-data": HTMLRenderer, "text/html": HTMLRenderer, } -CONTENT_TYPE_BY_RENDERERS = { - v: k for k, v in RENDERERS_BY_CONTENT_TYPE.items() -} # Handler source code is checked for which response types it returns with the # route error_format="auto" (default) to determine which format to use. @@ -420,7 +419,7 @@ RESPONSE_MAPPING = { def check_error_format(format): - if format not in RENDERERS_BY_CONFIG and format != "auto": + if format not in MIME_BY_CONFIG and format != "auto": raise SanicException(f"Unknown format: {format}") @@ -435,94 +434,68 @@ def exception_response( """ Render a response for the default FALLBACK exception handler. """ - content_type = None - if not renderer: - # Make sure we have something set - renderer = base - render_format = fallback - - if request: - # If there is a request, try and get the format - # from the route - if request.route: - try: - if request.route.extra.error_format: - render_format = request.route.extra.error_format - except AttributeError: - ... - - content_type = request.headers.getone("content-type", "").split( - ";" - )[0] - - acceptable = request.accept - - # If the format is auto still, make a guess - if render_format == "auto": - # First, if there is an Accept header, check if text/html - # is the first option - # According to MDN Web Docs, all major browsers use text/html - # as the primary value in Accept (with the exception of IE 8, - # and, well, if you are supporting IE 8, then you have bigger - # problems to concern yourself with than what default exception - # renderer is used) - # Source: - # https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values - - if acceptable and acceptable.match( - "text/html", accept_wildcards=False - ): - renderer = HTMLRenderer - - # Second, if there is an Accept header, check if - # application/json is an option, or if the content-type - # is application/json - elif ( - acceptable - and acceptable.match( - "application/json", accept_wildcards=False - ) - or content_type == "application/json" - ): - renderer = JSONRenderer - - # Third, if there is no Accept header, assume we want text. - # The likely use case here is a raw socket. - elif not acceptable: - renderer = TextRenderer - else: - # Fourth, look to see if there was a JSON body - # When in this situation, the request is probably coming - # from curl, an API client like Postman or Insomnia, or a - # package like requests or httpx - try: - # Give them the benefit of the doubt if they did: - # $ curl localhost:8000 -d '{"foo": "bar"}' - # And provide them with JSONRenderer - renderer = JSONRenderer if request.json else base - except BadRequest: - renderer = base - else: - renderer = RENDERERS_BY_CONFIG.get(render_format, renderer) - - # Lastly, if there is an Accept header, make sure - # our choice is okay - if acceptable: - type_ = CONTENT_TYPE_BY_RENDERERS.get(renderer) # type: ignore - if type_ and not acceptable.match(type_): - # If the renderer selected is not in the Accept header - # look through what is in the Accept header, and select - # the first option that matches. Otherwise, just drop back - # to the original default - for accept in acceptable: - mtype = f"{accept.type}/{accept.subtype}" - maybe = RENDERERS_BY_CONTENT_TYPE.get(mtype) - if maybe: - renderer = maybe - break - else: - renderer = base + mt = guess_mime(request, fallback) + renderer = RENDERERS_BY_CONTENT_TYPE.get(mt, base) renderer = t.cast(t.Type[BaseRenderer], renderer) return renderer(request, exception, debug).render() + + +def guess_mime(req: Request, fallback: str) -> str: + # Attempt to find a suitable MIME format for the response. + # Insertion-ordered map of formats["html"] = "source of that suggestion" + formats = {} + name = "" + # Route error_format (by magic from handler code if auto, the default) + if req.route: + name = req.route.name + f = req.route.extra.error_format + if f in MIME_BY_CONFIG: + formats[f] = name + + if not formats and fallback in MIME_BY_CONFIG: + formats[fallback] = "FALLBACK_ERROR_FORMAT" + + # If still not known, check for the request for clues of JSON + if not formats and fallback == "auto" and req.accept.match(JSON): + if JSON in req.accept: # Literally, not wildcard + formats["json"] = "request.accept" + elif JSON in req.headers.getone("content-type", ""): + formats["json"] = "content-type" + # DEPRECATION: Remove this block in 24.3 + else: + c = None + try: + c = req.json + except BadRequest: + pass + if c: + formats["json"] = "request.json" + deprecation( + "Response type was determined by the JSON content of " + "the request. This behavior is deprecated and will be " + "removed in v24.3. Please specify the format either by\n" + f' error_format="json" on route {name}, by\n' + ' FALLBACK_ERROR_FORMAT = "json", or by adding header\n' + " accept: application/json to your requests.", + 24.3, + ) + + # Any other supported formats + if fallback == "auto": + for k in MIME_BY_CONFIG: + if k not in formats: + formats[k] = "any" + + mimes = [MIME_BY_CONFIG[k] for k in formats] + m = req.accept.match(*mimes) + if m: + format = CONFIG_BY_MIME[m.mime] + source = formats[format] + logger.debug( + f"The client accepts {m.header}, using '{format}' from {source}" + ) + else: + logger.debug(f"No format found, the client accepts {req.accept!r}") + return m.mime diff --git a/sanic/headers.py b/sanic/headers.py index b192fa24..067e985b 100644 --- a/sanic/headers.py +++ b/sanic/headers.py @@ -166,7 +166,6 @@ class Matched: def _compare(self, other) -> Tuple[bool, Matched]: if isinstance(other, str): - # return self.mime == other, Accept.parse(other) parsed = Matched.parse(other) if self.mime == other: return True, parsed diff --git a/sanic/request.py b/sanic/request.py index 62ed6cf2..26fa17a8 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -500,13 +500,16 @@ class Request: @property def accept(self) -> AcceptList: - """ + """Accepted response content types. + + A convenience handler for easier RFC-compliant matching of MIME types, + parsed as a list that can match wildcards and includes */* by default. + :return: The ``Accept`` header parsed :rtype: AcceptList """ if self.parsed_accept is None: - accept_header = self.headers.getone("accept", "") - self.parsed_accept = parse_accept(accept_header) + self.parsed_accept = parse_accept(self.headers.get("accept")) return self.parsed_accept @property
sanic-org/sanic
d238995f1be11510aad81c4e877485ae446afb5c
diff --git a/tests/test_errorpages.py b/tests/test_errorpages.py index fda629ca..538acf1b 100644 --- a/tests/test_errorpages.py +++ b/tests/test_errorpages.py @@ -1,12 +1,14 @@ +import logging + import pytest from sanic import Sanic from sanic.config import Config -from sanic.errorpages import HTMLRenderer, exception_response +from sanic.errorpages import TextRenderer, guess_mime, exception_response from sanic.exceptions import NotFound, SanicException from sanic.handlers import ErrorHandler from sanic.request import Request -from sanic.response import HTTPResponse, html, json, text +from sanic.response import HTTPResponse, empty, html, json, text @pytest.fixture @@ -17,6 +19,45 @@ def app(): def err(request): raise Exception("something went wrong") + @app.get("/forced_json/<fail>", error_format="json") + def manual_fail(request, fail): + if fail == "fail": + raise Exception + return html("") # Should be ignored + + @app.get("/empty/<fail>") + def empty_fail(request, fail): + if fail == "fail": + raise Exception + return empty() + + @app.get("/json/<fail>") + def json_fail(request, fail): + if fail == "fail": + raise Exception + # After 23.3 route format should become json, older versions think it + # is mixed due to empty mapping to html, and don't find any format. + return json({"foo": "bar"}) if fail == "json" else empty() + + @app.get("/html/<fail>") + def html_fail(request, fail): + if fail == "fail": + raise Exception + return html("<h1>foo</h1>") + + @app.get("/text/<fail>") + def text_fail(request, fail): + if fail == "fail": + raise Exception + return text("foo") + + @app.get("/mixed/<param>") + def mixed_fail(request, param): + if param not in ("json", "html"): + raise Exception + return json({}) if param == "json" else html("") + + return app @@ -28,14 +69,14 @@ def fake_request(app): @pytest.mark.parametrize( "fallback,content_type, exception, status", ( - (None, "text/html; charset=utf-8", Exception, 500), + (None, "text/plain; charset=utf-8", Exception, 500), ("html", "text/html; charset=utf-8", Exception, 500), - ("auto", "text/html; charset=utf-8", Exception, 500), + ("auto", "text/plain; charset=utf-8", Exception, 500), ("text", "text/plain; charset=utf-8", Exception, 500), ("json", "application/json", Exception, 500), - (None, "text/html; charset=utf-8", NotFound, 404), + (None, "text/plain; charset=utf-8", NotFound, 404), ("html", "text/html; charset=utf-8", NotFound, 404), - ("auto", "text/html; charset=utf-8", NotFound, 404), + ("auto", "text/plain; charset=utf-8", NotFound, 404), ("text", "text/plain; charset=utf-8", NotFound, 404), ("json", "application/json", NotFound, 404), ), @@ -43,6 +84,10 @@ def fake_request(app): def test_should_return_html_valid_setting( fake_request, fallback, content_type, exception, status ): + # Note: if fallback is None or "auto", prior to PR #2668 base was returned + # and after that a text response is given because it matches */*. Changed + # base to TextRenderer in this test, like it is in Sanic itself, so the + # test passes with either version but still covers everything that it did. if fallback: fake_request.app.config.FALLBACK_ERROR_FORMAT = fallback @@ -53,7 +98,7 @@ def test_should_return_html_valid_setting( fake_request, e, True, - base=HTMLRenderer, + base=TextRenderer, fallback=fake_request.app.config.FALLBACK_ERROR_FORMAT, ) @@ -259,15 +304,17 @@ def test_fallback_with_content_type_mismatch_accept(app): "accept,content_type,expected", ( (None, None, "text/plain; charset=utf-8"), - ("foo/bar", None, "text/html; charset=utf-8"), + ("foo/bar", None, "text/plain; charset=utf-8"), ("application/json", None, "application/json"), ("application/json,text/plain", None, "application/json"), ("text/plain,application/json", None, "application/json"), ("text/plain,foo/bar", None, "text/plain; charset=utf-8"), - # Following test is valid after v22.3 - # ("text/plain,text/html", None, "text/plain; charset=utf-8"), - ("*/*", "foo/bar", "text/html; charset=utf-8"), + ("text/plain,text/html", None, "text/plain; charset=utf-8"), + ("*/*", "foo/bar", "text/plain; charset=utf-8"), ("*/*", "application/json", "application/json"), + # App wants text/plain but accept has equal entries for it + ("text/*,*/plain", None, "text/plain; charset=utf-8"), + ), ) def test_combinations_for_auto(fake_request, accept, content_type, expected): @@ -286,7 +333,7 @@ def test_combinations_for_auto(fake_request, accept, content_type, expected): fake_request, e, True, - base=HTMLRenderer, + base=TextRenderer, fallback="auto", ) @@ -376,3 +423,49 @@ def test_config_fallback_bad_value(app): message = "Unknown format: fake" with pytest.raises(SanicException, match=message): app.config.FALLBACK_ERROR_FORMAT = "fake" + + [email protected]( + "route_format,fallback,accept,expected", + ( + ("json", "html", "*/*", "The client accepts */*, using 'json' from fakeroute"), + ("json", "auto", "text/html,*/*;q=0.8", "The client accepts text/html, using 'html' from any"), + ("json", "json", "text/html,*/*;q=0.8", "The client accepts */*;q=0.8, using 'json' from fakeroute"), + ("", "html", "text/*,*/plain", "The client accepts text/*, using 'html' from FALLBACK_ERROR_FORMAT"), + ("", "json", "text/*,*/*", "The client accepts */*, using 'json' from FALLBACK_ERROR_FORMAT"), + ("", "auto", "*/*,application/json;q=0.5", "The client accepts */*, using 'json' from request.accept"), + ("", "auto", "*/*", "The client accepts */*, using 'json' from content-type"), + ("", "auto", "text/html,text/plain", "The client accepts text/plain, using 'text' from any"), + ("", "auto", "text/html,text/plain;q=0.9", "The client accepts text/html, using 'html' from any"), + ("html", "json", "application/xml", "No format found, the client accepts [application/xml]"), + ("", "auto", "*/*", "The client accepts */*, using 'text' from any"), + ("", "", "*/*", "No format found, the client accepts [*/*]"), + # DEPRECATED: remove in 24.3 + ("", "auto", "*/*", "The client accepts */*, using 'json' from request.json"), + ), +) +def test_guess_mime_logging(caplog, fake_request, route_format, fallback, accept, expected): + class FakeObject: + pass + fake_request.route = FakeObject() + fake_request.route.name = "fakeroute" + fake_request.route.extra = FakeObject() + fake_request.route.extra.error_format = route_format + if accept is None: + del fake_request.headers["accept"] + else: + fake_request.headers["accept"] = accept + + if "content-type" in expected: + fake_request.headers["content-type"] = "application/json" + + # Fake JSON content (DEPRECATED: remove in 24.3) + if "request.json" in expected: + fake_request.parsed_json = {"foo": "bar"} + + with caplog.at_level(logging.DEBUG, logger="sanic.root"): + guess_mime(fake_request, fallback) + + logmsg, = [r.message for r in caplog.records if r.funcName == "guess_mime"] + + assert logmsg == expected diff --git a/tests/test_request.py b/tests/test_request.py index a4757b52..c7c13910 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -150,26 +150,29 @@ def test_request_accept(): async def get(request): return response.empty() + header_value = "text/plain;format=flowed, text/plain, text/*, */*" request, _ = app.test_client.get( "/", - headers={ - "Accept": "text/*, text/plain, text/plain;format=flowed, */*" - }, + headers={"Accept": header_value}, ) - assert [str(i) for i in request.accept] == [ + assert str(request.accept) == header_value + match = request.accept.match( + "*/*;format=flowed", "text/plain;format=flowed", "text/plain", "text/*", "*/*", - ] + ) + assert match == "*/*;format=flowed" + assert match.header.mime == "text/plain" + assert match.header.params == {"format": "flowed"} + header_value = ( + "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c" + ) request, _ = app.test_client.get( "/", - headers={ - "Accept": ( - "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c" - ) - }, + headers={"Accept": header_value}, ) assert [str(i) for i in request.accept] == [ "text/html", @@ -177,6 +180,17 @@ def test_request_accept(): "text/x-dvi;q=0.8", "text/plain;q=0.5", ] + match = request.accept.match( + "application/json", + "text/plain", # Has lower q in accept header + "text/html;format=flowed", # Params mismatch + "text/*", # Matches + "*/*", + ) + assert match == "text/*" + assert match.header.mime == "text/html" + assert match.header.q == 1.0 + assert not match.header.params def test_bad_url_parse():
FALLBACK_ERROR_FORMAT does not work with empty() ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug Today I tested a handler which always returns `empty()` (see example below). I was quite confused by the format of the errors, as they were all in HTML format, even though the fallback was set to json. It took me a while to figure out that this was because of the `empty()` statement returned by the function, which somehow hijacks the error format, so that the errors are converted to html. I could use the `error_format` from now on for handlers returning `empty()`, but was wondering if this is a feature or a bug. ### Code snippet ```python from sanic import Sanic, empty from sanic.exceptions import Unauthorized app = Sanic(__name__) app.config.FALLBACK_ERROR_FORMAT = "json" # Returns error in html format @app.post("/empty") async def empty_(request): raise Unauthorized("bli bla blub") return empty() # Returns error in json format @app.post("/nothing") async def nothing(request): raise Unauthorized("bli bla blub") if __name__ == '__main__': app.run("127.0.0.1", port=3000, auto_reload=True, debug=True, dev=True) ``` ### How do you run Sanic? As a script ### Operating System Ubuntu ### Sanic Version 22.9.1
0.0
d238995f1be11510aad81c4e877485ae446afb5c
[ "tests/test_errorpages.py::test_should_return_html_valid_setting[None-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[html-text/html;", "tests/test_errorpages.py::test_should_return_html_valid_setting[auto-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[text-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-Exception-500]", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-NotFound-404]", "tests/test_errorpages.py::test_auto_fallback_with_data", "tests/test_errorpages.py::test_auto_fallback_with_content_type", "tests/test_errorpages.py::test_route_error_format_set_on_auto", "tests/test_errorpages.py::test_route_error_response_from_auto_route", "tests/test_errorpages.py::test_route_error_response_from_explicit_format", "tests/test_errorpages.py::test_unknown_fallback_format", "tests/test_errorpages.py::test_route_error_format_unknown", "tests/test_errorpages.py::test_fallback_with_content_type_html", "tests/test_errorpages.py::test_fallback_with_content_type_mismatch_accept", "tests/test_errorpages.py::test_combinations_for_auto[None-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[application/json,text/plain-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,text/html-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-foo/bar-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-application/json-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/*,*/plain-None-text/plain;", "tests/test_errorpages.py::test_allow_fallback_error_format_set_main_process_start", "tests/test_errorpages.py::test_setting_fallback_on_config_changes_as_expected", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_injection", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_replacement", "tests/test_errorpages.py::test_config_fallback_before_and_after_startup", "tests/test_errorpages.py::test_config_fallback_using_update_dict", "tests/test_errorpages.py::test_config_fallback_using_update_kwarg", "tests/test_errorpages.py::test_config_fallback_bad_value", "tests/test_errorpages.py::test_guess_mime_logging[json-html-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[json-auto-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[json-json-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[-html-text/*,*/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-json-text/*,*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*,application/json;q=0.5-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain;q=0.9-The", "tests/test_errorpages.py::test_guess_mime_logging[html-json-application/xml-No", "tests/test_errorpages.py::test_guess_mime_logging[--*/*-No", "tests/test_request.py::test_no_request_id_not_called", "tests/test_request.py::test_request_id_generates_from_request", "tests/test_request.py::test_request_id_defaults_uuid", "tests/test_request.py::test_name_none", "tests/test_request.py::test_name_from_route", "tests/test_request.py::test_name_from_set", "tests/test_request.py::test_request_id[99-int]", "tests/test_request.py::test_request_id[request_id1-UUID]", "tests/test_request.py::test_request_id[foo-str]", "tests/test_request.py::test_custom_generator", "tests/test_request.py::test_route_assigned_to_request", "tests/test_request.py::test_protocol_attribute", "tests/test_request.py::test_ipv6_address_is_not_wrapped", "tests/test_request.py::test_request_accept", "tests/test_request.py::test_bad_url_parse", "tests/test_request.py::test_request_scope_raises_exception_when_no_asgi", "tests/test_request.py::test_request_scope_is_not_none_when_running_in_asgi", "tests/test_request.py::test_cannot_get_request_outside_of_cycle", "tests/test_request.py::test_get_current_request", "tests/test_request.py::test_request_stream_id", "tests/test_request.py::test_request_safe[DELETE-False]", "tests/test_request.py::test_request_safe[GET-True]", "tests/test_request.py::test_request_safe[HEAD-True]", "tests/test_request.py::test_request_safe[OPTIONS-True]", "tests/test_request.py::test_request_safe[PATCH-False]", "tests/test_request.py::test_request_safe[POST-False]", "tests/test_request.py::test_request_safe[PUT-False]", "tests/test_request.py::test_request_idempotent[DELETE-True]", "tests/test_request.py::test_request_idempotent[GET-True]", "tests/test_request.py::test_request_idempotent[HEAD-True]", "tests/test_request.py::test_request_idempotent[OPTIONS-True]", "tests/test_request.py::test_request_idempotent[PATCH-False]", "tests/test_request.py::test_request_idempotent[POST-False]", "tests/test_request.py::test_request_idempotent[PUT-True]", "tests/test_request.py::test_request_cacheable[DELETE-False]", "tests/test_request.py::test_request_cacheable[GET-True]", "tests/test_request.py::test_request_cacheable[HEAD-True]", "tests/test_request.py::test_request_cacheable[OPTIONS-False]", "tests/test_request.py::test_request_cacheable[PATCH-False]", "tests/test_request.py::test_request_cacheable[POST-False]", "tests/test_request.py::test_request_cacheable[PUT-False]" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-01-29 04:23:33+00:00
mit
5,324
sanic-org__sanic-2704
diff --git a/sanic/app.py b/sanic/app.py index 1adc2732..9fb7e027 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -16,7 +16,7 @@ from asyncio import ( ) from asyncio.futures import Future from collections import defaultdict, deque -from contextlib import suppress +from contextlib import contextmanager, suppress from functools import partial from inspect import isawaitable from os import environ @@ -33,6 +33,7 @@ from typing import ( Deque, Dict, Iterable, + Iterator, List, Optional, Set, @@ -433,14 +434,15 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): ctx = params.pop("route_context") - routes = self.router.add(**params) - if isinstance(routes, Route): - routes = [routes] + with self.amend(): + routes = self.router.add(**params) + if isinstance(routes, Route): + routes = [routes] - for r in routes: - r.extra.websocket = websocket - r.extra.static = params.get("static", False) - r.ctx.__dict__.update(ctx) + for r in routes: + r.extra.websocket = websocket + r.extra.static = params.get("static", False) + r.ctx.__dict__.update(ctx) return routes @@ -449,17 +451,19 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): middleware: FutureMiddleware, route_names: Optional[List[str]] = None, ): - if route_names: - return self.register_named_middleware( - middleware.middleware, route_names, middleware.attach_to - ) - else: - return self.register_middleware( - middleware.middleware, middleware.attach_to - ) + with self.amend(): + if route_names: + return self.register_named_middleware( + middleware.middleware, route_names, middleware.attach_to + ) + else: + return self.register_middleware( + middleware.middleware, middleware.attach_to + ) def _apply_signal(self, signal: FutureSignal) -> Signal: - return self.signal_router.add(*signal) + with self.amend(): + return self.signal_router.add(*signal) def dispatch( self, @@ -1520,6 +1524,27 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): # Lifecycle # -------------------------------------------------------------------- # + @contextmanager + def amend(self) -> Iterator[None]: + """ + If the application has started, this function allows changes + to be made to add routes, middleware, and signals. + """ + if not self.state.is_started: + yield + else: + do_router = self.router.finalized + do_signal_router = self.signal_router.finalized + if do_router: + self.router.reset() + if do_signal_router: + self.signal_router.reset() + yield + if do_signal_router: + self.signalize(self.config.TOUCHUP) + if do_router: + self.finalize() + def finalize(self): try: self.router.finalize()
sanic-org/sanic
5ee36fd933344861cb578105b3ad25b032f22912
diff --git a/tests/test_late_adds.py b/tests/test_late_adds.py new file mode 100644 index 00000000..f7281d38 --- /dev/null +++ b/tests/test_late_adds.py @@ -0,0 +1,54 @@ +import pytest + +from sanic import Sanic, text + + [email protected] +def late_app(app: Sanic): + app.config.TOUCHUP = False + app.get("/")(lambda _: text("")) + return app + + +def test_late_route(late_app: Sanic): + @late_app.before_server_start + async def late(app: Sanic): + @app.get("/late") + def handler(_): + return text("late") + + _, response = late_app.test_client.get("/late") + assert response.status_code == 200 + assert response.text == "late" + + +def test_late_middleware(late_app: Sanic): + @late_app.get("/late") + def handler(request): + return text(request.ctx.late) + + @late_app.before_server_start + async def late(app: Sanic): + @app.on_request + def handler(request): + request.ctx.late = "late" + + _, response = late_app.test_client.get("/late") + assert response.status_code == 200 + assert response.text == "late" + + +def test_late_signal(late_app: Sanic): + @late_app.get("/late") + def handler(request): + return text(request.ctx.late) + + @late_app.before_server_start + async def late(app: Sanic): + @app.signal("http.lifecycle.request") + def handler(request): + request.ctx.late = "late" + + _, response = late_app.test_client.get("/late") + assert response.status_code == 200 + assert response.text == "late"
request middleware not running when registered in a method since 22.9.0 ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug Prior to 22.9.0, you could register request middleware in functions and listeners. Since 22.9.0 this has stopped working. I'm unclear on whether this is by design or not, but I wasn't able to find anything in the docs that explains the discrepancy. The last working version I tested was 22.6.2. ### Code snippet ``` from sanic import Sanic, response app = Sanic("my-hello-world-app") @app.middleware("request") async def this_always_works(request): print("this is request middleware") @app.before_server_start async def before_server_start_listener(app, loop): def this_fails_in_22_9_0_and_after(request): print("this will not fire after in 22.9.0 and after") app.register_middleware(this_fails_in_22_9_0_and_after, "request") @app.route('/') async def test(request): return response.json({'hello': 'world'}) if __name__ == '__main__': app.register_middleware(lambda app: print("this will also not fire in 22.9.0 and after"), "request") app.run(host="0.0.0.0", debug=True, auto_reload=True) ``` ### Expected Behavior I expected all middleware to fire, but only the first one I set up fires since 22.9.0. I know middlware priority was introduced in 22.9, but I wouldn't expect that to have broken existing apps. I tried explicitly setting the priority and I still was not able to get the middleware to fire. ### How do you run Sanic? As a script (`app.run` or `Sanic.serve`) ### Operating System Linux ### Sanic Version 22.9.0 ### Additional context Thanks for Sanic!
0.0
5ee36fd933344861cb578105b3ad25b032f22912
[ "tests/test_late_adds.py::test_late_route", "tests/test_late_adds.py::test_late_middleware", "tests/test_late_adds.py::test_late_signal" ]
[]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-02 10:35:10+00:00
mit
5,325
sanic-org__sanic-2722
diff --git a/sanic/app.py b/sanic/app.py index 9fb7e027..9efc53ef 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -92,6 +92,7 @@ from sanic.signals import Signal, SignalRouter from sanic.touchup import TouchUp, TouchUpMeta from sanic.types.shared_ctx import SharedContext from sanic.worker.inspector import Inspector +from sanic.worker.loader import CertLoader from sanic.worker.manager import WorkerManager @@ -139,6 +140,7 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): "_test_client", "_test_manager", "blueprints", + "certloader_class", "config", "configure_logging", "ctx", @@ -181,6 +183,7 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): loads: Optional[Callable[..., Any]] = None, inspector: bool = False, inspector_class: Optional[Type[Inspector]] = None, + certloader_class: Optional[Type[CertLoader]] = None, ) -> None: super().__init__(name=name) # logging @@ -215,6 +218,9 @@ class Sanic(StaticHandleMixin, BaseSanic, StartupMixin, metaclass=TouchUpMeta): self.asgi = False self.auto_reload = False self.blueprints: Dict[str, Blueprint] = {} + self.certloader_class: Type[CertLoader] = ( + certloader_class or CertLoader + ) self.configure_logging: bool = configure_logging self.ctx: Any = ctx or SimpleNamespace() self.error_handler: ErrorHandler = error_handler or ErrorHandler() diff --git a/sanic/worker/loader.py b/sanic/worker/loader.py index 344593db..d29f4c68 100644 --- a/sanic/worker/loader.py +++ b/sanic/worker/loader.py @@ -5,6 +5,7 @@ import sys from importlib import import_module from pathlib import Path +from ssl import SSLContext from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union, cast from sanic.http.tls.context import process_to_context @@ -103,8 +104,16 @@ class CertLoader: "trustme": TrustmeCreator, } - def __init__(self, ssl_data: Dict[str, Union[str, os.PathLike]]): + def __init__( + self, + ssl_data: Optional[ + Union[SSLContext, Dict[str, Union[str, os.PathLike]]] + ], + ): self._ssl_data = ssl_data + self._creator_class = None + if not ssl_data or not isinstance(ssl_data, dict): + return creator_name = cast(str, ssl_data.get("creator")) diff --git a/sanic/worker/serve.py b/sanic/worker/serve.py index 39c647b2..583d3eaf 100644 --- a/sanic/worker/serve.py +++ b/sanic/worker/serve.py @@ -73,8 +73,8 @@ def worker_serve( info.settings["app"] = a a.state.server_info.append(info) - if isinstance(ssl, dict): - cert_loader = CertLoader(ssl) + if isinstance(ssl, dict) or app.certloader_class is not CertLoader: + cert_loader = app.certloader_class(ssl or {}) ssl = cert_loader.load(app) for info in app.state.server_info: info.settings["ssl"] = ssl
sanic-org/sanic
a245ab37733411fab555c5ea602833e713eae4f2
diff --git a/tests/test_tls.py b/tests/test_tls.py index d41784f0..6d2cb981 100644 --- a/tests/test_tls.py +++ b/tests/test_tls.py @@ -12,7 +12,7 @@ from urllib.parse import urlparse import pytest -from sanic_testing.testing import HOST, PORT +from sanic_testing.testing import HOST, PORT, SanicTestClient import sanic.http.tls.creators @@ -29,6 +29,7 @@ from sanic.http.tls.creators import ( get_ssl_context, ) from sanic.response import text +from sanic.worker.loader import CertLoader current_dir = os.path.dirname(os.path.realpath(__file__)) @@ -427,6 +428,29 @@ def test_no_certs_on_list(app): assert "No certificates" in str(excinfo.value) +def test_custom_cert_loader(): + class MyCertLoader(CertLoader): + def load(self, app: Sanic): + self._ssl_data = { + "key": localhost_key, + "cert": localhost_cert, + } + return super().load(app) + + app = Sanic("custom", certloader_class=MyCertLoader) + + @app.get("/test") + async def handler(request): + return text("ssl test") + + client = SanicTestClient(app, port=44556) + + request, response = client.get("https://localhost:44556/test") + assert request.scheme == "https" + assert response.status_code == 200 + assert response.text == "ssl test" + + def test_logger_vhosts(caplog): app = Sanic(name="test_logger_vhosts")
Can't run normally when using SSLContext ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug ``` app.run(host='0.0.0.0', port=443, ssl=context, dev=True) File "/usr/lib/python3.10/site-packages/sanic/mixins/startup.py", line 209, in run serve(primary=self) # type: ignore File "/usr/lib/python3.10/site-packages/sanic/mixins/startup.py", line 862, in serve manager.run() File "/usr/lib/python3.10/site-packages/sanic/worker/manager.py", line 94, in run self.start() File "/usr/lib/python3.10/site-packages/sanic/worker/manager.py", line 101, in start process.start() File "/usr/lib/python3.10/site-packages/sanic/worker/process.py", line 53, in start self._current_process.start() File "/usr/lib/python3.10/multiprocessing/process.py", line 121, in start self._popen = self._Popen(self) File "/usr/lib/python3.10/multiprocessing/context.py", line 284, in _Popen return Popen(process_obj) File "/usr/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 32, in __init__ super().__init__(process_obj) File "/usr/lib/python3.10/multiprocessing/popen_fork.py", line 19, in __init__ self._launch(process_obj) File "/usr/lib/python3.10/multiprocessing/popen_spawn_posix.py", line 47, in _launch reduction.dump(process_obj, fp) File "/usr/lib/python3.10/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) TypeError: cannot pickle 'SSLContext' object ``` ### Code snippet ```python from sanic import Sanic import ssl context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain("certs/fullchain.pem", "certs/privkey.pem") app = Sanic('test') if __name__ == "__main__": app.run(host='0.0.0.0', port=443, ssl=context, dev=True) ``` ### Expected Behavior _No response_ ### How do you run Sanic? As a script (`app.run` or `Sanic.serve`) ### Operating System linux ### Sanic Version 22.12.0 ### Additional context pickle does not support dump ssl.SSLContext causing this problem. `multiprocessing.context` use `pickle` ```python import ssl context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain("certs/fullchain.pem", "certs/privkey.pem") pickle.dumps(context) ```
0.0
a245ab37733411fab555c5ea602833e713eae4f2
[ "tests/test_tls.py::test_custom_cert_loader" ]
[ "tests/test_tls.py::test_url_attributes_with_ssl_context[/foo--https://{}:{}/foo]", "tests/test_tls.py::test_url_attributes_with_ssl_context[/moo/boo-arg1=val1-https://{}:{}/moo/boo?arg1=val1]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-True-False-True-False-None]", "tests/test_tls.py::test_cert_file_on_pathlist", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-True-False-False-False-Nope]", "tests/test_tls.py::test_mk_cert_creator_default", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-False-False-False-False-Sanic", "tests/test_tls.py::test_trustme_creator_generate_cert_localhost", "tests/test_tls.py::test_invalid_ssl_type", "tests/test_tls.py::test_logger_vhosts", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/foo--https://{}:{}/foo]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-True-True-True-False-None]", "tests/test_tls.py::test_missing_cert_path", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-True-False-True-False-None]", "tests/test_tls.py::test_ssl_in_multiprocess_mode_password", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/bar/baz--https://{}:{}/bar/baz]", "tests/test_tls.py::test_trustme_creator_is_not_supported", "tests/test_tls.py::test_cert_sni_single", "tests/test_tls.py::test_trustme_creator_generate_cert_default", "tests/test_tls.py::test_trustme_creator_is_supported", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-False-True-False-True-None]", "tests/test_tls.py::test_sanic_ssl_context_create", "tests/test_tls.py::test_missing_cert_file", "tests/test_tls.py::test_no_certs_on_list", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-False-False-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[AUTO-True-True-True-False-None]", "tests/test_tls.py::test_mk_cert_creator_generate_cert_localhost", "tests/test_tls.py::test_invalid_ssl_dict", "tests/test_tls.py::test_ssl_in_multiprocess_mode", "tests/test_tls.py::test_mk_cert_creator_is_not_supported", "tests/test_tls.py::test_url_attributes_with_ssl_dict[/moo/boo-arg1=val1-https://{}:{}/moo/boo?arg1=val1]", "tests/test_tls.py::test_mk_cert_creator_is_supported", "tests/test_tls.py::test_url_attributes_with_ssl_context[/bar/baz--https://{}:{}/bar/baz]", "tests/test_tls.py::test_cert_sni_list", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-False-True-False-True-None]", "tests/test_tls.py::test_get_ssl_context_in_production", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-True-True-False-True-None]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[MKCERT-False-True-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_only_mkcert[TRUSTME-False-False-False-False-Nope]", "tests/test_tls.py::test_get_ssl_context_with_ssl_context", "tests/test_tls.py::test_trustme_creator_default", "tests/test_tls.py::test_mk_cert_creator_generate_cert_default" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-20 09:51:17+00:00
mit
5,326
sanic-org__sanic-2737
diff --git a/sanic/response/types.py b/sanic/response/types.py index 3f93855d..d3c8cdb6 100644 --- a/sanic/response/types.py +++ b/sanic/response/types.py @@ -345,7 +345,7 @@ class JSONResponse(HTTPResponse): body: Optional[Any] = None, status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, - content_type: Optional[str] = None, + content_type: str = "application/json", dumps: Optional[Callable[..., str]] = None, **kwargs: Any, ):
sanic-org/sanic
6eaab2a7e5be418385856371fdaebe4701f8c4fc
diff --git a/tests/test_response_json.py b/tests/test_response_json.py index c89dba42..aa1c61dd 100644 --- a/tests/test_response_json.py +++ b/tests/test_response_json.py @@ -213,3 +213,12 @@ def test_pop_list(json_app: Sanic): _, resp = json_app.test_client.get("/json-pop") assert resp.body == json_dumps(["b"]).encode() + + +def test_json_response_class_sets_proper_content_type(json_app: Sanic): + @json_app.get("/json-class") + async def handler(request: Request): + return JSONResponse(JSON_BODY) + + _, resp = json_app.test_client.get("/json-class") + assert resp.headers["content-type"] == "application/json"
JSONResponse defaults to None content-type ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug ```python @app.get("/") async def handler(request: Request): return JSONResponse({"message": "Hello World!"}) ``` ```sh ╰─▶ curl localhost:9999 HTTP/1.1 200 OK content-length: 26 connection: keep-alive alt-svc: content-type: None {"message":"Hello World!"} ``` ### Code snippet _No response_ ### Expected Behavior `content-type: application/json` ### How do you run Sanic? Sanic CLI ### Operating System all ### Sanic Version LTS+ ### Additional context _No response_
0.0
6eaab2a7e5be418385856371fdaebe4701f8c4fc
[ "tests/test_response_json.py::test_json_response_class_sets_proper_content_type" ]
[ "tests/test_response_json.py::test_body_can_be_retrieved", "tests/test_response_json.py::test_body_can_be_set", "tests/test_response_json.py::test_raw_body_can_be_retrieved", "tests/test_response_json.py::test_raw_body_can_be_set", "tests/test_response_json.py::test_raw_body_cant_be_retrieved_after_body_set", "tests/test_response_json.py::test_raw_body_can_be_reset_after_body_set", "tests/test_response_json.py::test_set_body_method", "tests/test_response_json.py::test_set_body_method_after_body_set", "tests/test_response_json.py::test_custom_dumps_and_kwargs", "tests/test_response_json.py::test_override_dumps_and_kwargs", "tests/test_response_json.py::test_append", "tests/test_response_json.py::test_extend", "tests/test_response_json.py::test_update", "tests/test_response_json.py::test_pop_dict", "tests/test_response_json.py::test_pop_list" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-04-09 16:19:44+00:00
mit
5,327
sanic-org__sanic-2773
diff --git a/sanic/blueprints.py b/sanic/blueprints.py index a52495b9..fc9408fe 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -319,6 +319,10 @@ class Blueprint(BaseSanic): # Prepend the blueprint URI prefix if available uri = self._setup_uri(future.uri, url_prefix) + route_error_format = ( + future.error_format if future.error_format else error_format + ) + version_prefix = self.version_prefix for prefix in ( future.version_prefix, @@ -358,7 +362,7 @@ class Blueprint(BaseSanic): future.unquote, future.static, version_prefix, - error_format, + route_error_format, future.route_context, )
sanic-org/sanic
976da69e79e22c08ba2ea9ffe48bed72bf3290df
diff --git a/tests/test_errorpages.py b/tests/test_errorpages.py index a2df90b3..6c4334b7 100644 --- a/tests/test_errorpages.py +++ b/tests/test_errorpages.py @@ -2,6 +2,7 @@ import logging import pytest +import sanic from sanic import Sanic from sanic.config import Config from sanic.errorpages import TextRenderer, exception_response, guess_mime @@ -205,6 +206,27 @@ def test_route_error_response_from_explicit_format(app): assert response.content_type == "text/plain; charset=utf-8" +def test_blueprint_error_response_from_explicit_format(app): + bp = sanic.Blueprint("MyBlueprint") + + @bp.get("/text", error_format="json") + def text_response(request): + raise Exception("oops") + return text("Never gonna see this") + + @bp.get("/json", error_format="text") + def json_response(request): + raise Exception("oops") + return json({"message": "Never gonna see this"}) + + app.blueprint(bp) + _, response = app.test_client.get("/text") + assert response.content_type == "application/json" + + _, response = app.test_client.get("/json") + assert response.content_type == "text/plain; charset=utf-8" + + def test_unknown_fallback_format(app): with pytest.raises(SanicException, match="Unknown format: bad"): app.config.FALLBACK_ERROR_FORMAT = "bad"
Blueprint ignores error_format option ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug `add_route` and its route-decorator friends respect the `error_format` option to specify "text", "json", or "html", as documented [here](https://sanic.dev/en/guide/best-practices/exceptions.html#built-in-error-handling). But if I wrap the route in a blueprint, the `error_format` option no longer works, it just uses the default. ### Code snippet #### Without Blueprint ```python from sanic import Sanic import sanic.exceptions app = Sanic("MyHelloWorldApp") @app.get("/", error_format="json") async def hello_world(request): raise sanic.exceptions.SanicException("Big Mistake, Huge.", status_code=400) ``` // Elsewhere... ```bash $ curl localhost:8000/ -i HTTP/1.1 400 Bad Request content-length: 73 connection: keep-alive content-type: application/json {"description":"Bad Request","status":400,"message":"Big Mistake, Huge."} ``` #### With Blueprint ```python from sanic import Sanic import sanic.exceptions app = Sanic("MyHelloWorldApp") bp = sanic.Blueprint("MyBlueprint") @bp.get("/", error_format="json") async def hello_world(request): raise sanic.exceptions.SanicException("Big Mistake, Huge.", status_code=400) app.blueprint(bp) ``` // Elsewhere... ```bash $ curl localhost:8000/ -i HTTP/1.1 400 Bad Request content-length: 68 connection: keep-alive content-type: text/plain; charset=utf-8 ⚠️ 400 — Bad Request ==================== Big Mistake, Huge. ``` ### Expected Behavior I expect the `error_format` option to be applied to the blueprint route the same as if applied to an app route. ### How do you run Sanic? Sanic CLI ### Operating System Mac OSX 12.3 ### Sanic Version 23.3.0 ### Additional context _No response_
0.0
976da69e79e22c08ba2ea9ffe48bed72bf3290df
[ "tests/test_errorpages.py::test_blueprint_error_response_from_explicit_format" ]
[ "tests/test_errorpages.py::test_should_return_html_valid_setting[None-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[html-text/html;", "tests/test_errorpages.py::test_should_return_html_valid_setting[auto-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[text-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-Exception-500]", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-NotFound-404]", "tests/test_errorpages.py::test_auto_fallback_with_data", "tests/test_errorpages.py::test_auto_fallback_with_content_type", "tests/test_errorpages.py::test_route_error_format_set_on_auto", "tests/test_errorpages.py::test_route_error_response_from_auto_route", "tests/test_errorpages.py::test_route_error_response_from_explicit_format", "tests/test_errorpages.py::test_unknown_fallback_format", "tests/test_errorpages.py::test_route_error_format_unknown", "tests/test_errorpages.py::test_fallback_with_content_type_html", "tests/test_errorpages.py::test_fallback_with_content_type_mismatch_accept", "tests/test_errorpages.py::test_combinations_for_auto[None-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[application/json,text/plain-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,text/html-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-foo/bar-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-application/json-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/*,*/plain-None-text/plain;", "tests/test_errorpages.py::test_allow_fallback_error_format_set_main_process_start", "tests/test_errorpages.py::test_setting_fallback_on_config_changes_as_expected", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_injection", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_replacement", "tests/test_errorpages.py::test_config_fallback_before_and_after_startup", "tests/test_errorpages.py::test_config_fallback_using_update_dict", "tests/test_errorpages.py::test_config_fallback_using_update_kwarg", "tests/test_errorpages.py::test_config_fallback_bad_value", "tests/test_errorpages.py::test_guess_mime_logging[json-html-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[json-auto-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[json-json-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[-html-text/*,*/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-json-text/*,*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*,application/json;q=0.5-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain;q=0.9-The", "tests/test_errorpages.py::test_guess_mime_logging[html-json-application/xml-No", "tests/test_errorpages.py::test_guess_mime_logging[--*/*-No", "tests/test_errorpages.py::test_exception_header_on_renderers[html-text/html;", "tests/test_errorpages.py::test_exception_header_on_renderers[text-text/plain;", "tests/test_errorpages.py::test_exception_header_on_renderers[json-application/json]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-07-08 19:08:49+00:00
mit
5,328
sanic-org__sanic-2774
diff --git a/sanic/errorpages.py b/sanic/errorpages.py index 19ccc69b..7b243ddb 100644 --- a/sanic/errorpages.py +++ b/sanic/errorpages.py @@ -92,8 +92,10 @@ class BaseRenderer: self.full if self.debug and not getattr(self.exception, "quiet", False) else self.minimal - ) - return output() + )() + output.status = self.status + output.headers.update(self.headers) + return output def minimal(self) -> HTTPResponse: # noqa """ @@ -125,7 +127,7 @@ class HTMLRenderer(BaseRenderer): request=self.request, exc=self.exception, ) - return html(page.render(), status=self.status, headers=self.headers) + return html(page.render()) def minimal(self) -> HTTPResponse: return self.full() @@ -146,8 +148,7 @@ class TextRenderer(BaseRenderer): text=self.text, bar=("=" * len(self.title)), body=self._generate_body(full=True), - ), - status=self.status, + ) ) def minimal(self) -> HTTPResponse: @@ -157,9 +158,7 @@ class TextRenderer(BaseRenderer): text=self.text, bar=("=" * len(self.title)), body=self._generate_body(full=False), - ), - status=self.status, - headers=self.headers, + ) ) @property @@ -218,11 +217,11 @@ class JSONRenderer(BaseRenderer): def full(self) -> HTTPResponse: output = self._generate_output(full=True) - return json(output, status=self.status, dumps=self.dumps) + return json(output, dumps=self.dumps) def minimal(self) -> HTTPResponse: output = self._generate_output(full=False) - return json(output, status=self.status, dumps=self.dumps) + return json(output, dumps=self.dumps) def _generate_output(self, *, full): output = {
sanic-org/sanic
c17230ef9443d7e9932ac425ddbca4ad850f96a2
diff --git a/tests/test_errorpages.py b/tests/test_errorpages.py index d2c1fc7b..a2df90b3 100644 --- a/tests/test_errorpages.py +++ b/tests/test_errorpages.py @@ -527,3 +527,26 @@ def test_guess_mime_logging( ] assert logmsg == expected + + [email protected]( + "format,expected", + ( + ("html", "text/html; charset=utf-8"), + ("text", "text/plain; charset=utf-8"), + ("json", "application/json"), + ), +) +def test_exception_header_on_renderers(app: Sanic, format, expected): + app.config.FALLBACK_ERROR_FORMAT = format + + @app.get("/test") + def test(request): + raise SanicException( + "test", status_code=400, headers={"exception": "test"} + ) + + _, response = app.test_client.get("/test") + assert response.status == 400 + assert response.headers.get("exception") == "test" + assert response.content_type == expected
Headers from Exceptions ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug Headers set on Exception objects not carried through on all renderers ### Code snippet ```py raise Unauthorized( "Auth required.", headers={"foo": "bar"}, ) ``` ### Expected Behavior Response should have: ``` Foo: bar ``` ### How do you run Sanic? Sanic CLI ### Operating System all ### Sanic Version 23.3 ### Additional context _No response_
0.0
c17230ef9443d7e9932ac425ddbca4ad850f96a2
[ "tests/test_errorpages.py::test_exception_header_on_renderers[json-application/json]" ]
[ "tests/test_errorpages.py::test_should_return_html_valid_setting[None-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[html-text/html;", "tests/test_errorpages.py::test_should_return_html_valid_setting[auto-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[text-text/plain;", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-Exception-500]", "tests/test_errorpages.py::test_should_return_html_valid_setting[json-application/json-NotFound-404]", "tests/test_errorpages.py::test_auto_fallback_with_data", "tests/test_errorpages.py::test_auto_fallback_with_content_type", "tests/test_errorpages.py::test_route_error_format_set_on_auto", "tests/test_errorpages.py::test_route_error_response_from_auto_route", "tests/test_errorpages.py::test_route_error_response_from_explicit_format", "tests/test_errorpages.py::test_unknown_fallback_format", "tests/test_errorpages.py::test_route_error_format_unknown", "tests/test_errorpages.py::test_fallback_with_content_type_html", "tests/test_errorpages.py::test_fallback_with_content_type_mismatch_accept", "tests/test_errorpages.py::test_combinations_for_auto[None-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[application/json,text/plain-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,application/json-None-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,foo/bar-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[text/plain,text/html-None-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-foo/bar-text/plain;", "tests/test_errorpages.py::test_combinations_for_auto[*/*-application/json-application/json]", "tests/test_errorpages.py::test_combinations_for_auto[text/*,*/plain-None-text/plain;", "tests/test_errorpages.py::test_allow_fallback_error_format_set_main_process_start", "tests/test_errorpages.py::test_setting_fallback_on_config_changes_as_expected", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_injection", "tests/test_errorpages.py::test_allow_fallback_error_format_in_config_replacement", "tests/test_errorpages.py::test_config_fallback_before_and_after_startup", "tests/test_errorpages.py::test_config_fallback_using_update_dict", "tests/test_errorpages.py::test_config_fallback_using_update_kwarg", "tests/test_errorpages.py::test_config_fallback_bad_value", "tests/test_errorpages.py::test_guess_mime_logging[json-html-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[json-auto-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[json-json-text/html,*/*;q=0.8-The", "tests/test_errorpages.py::test_guess_mime_logging[-html-text/*,*/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-json-text/*,*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*,application/json;q=0.5-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-*/*-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain-The", "tests/test_errorpages.py::test_guess_mime_logging[-auto-text/html,text/plain;q=0.9-The", "tests/test_errorpages.py::test_guess_mime_logging[html-json-application/xml-No", "tests/test_errorpages.py::test_guess_mime_logging[--*/*-No", "tests/test_errorpages.py::test_exception_header_on_renderers[html-text/html;", "tests/test_errorpages.py::test_exception_header_on_renderers[text-text/plain;" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-09 06:34:27+00:00
mit
5,329
sanic-org__sanic-2824
diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index f5e45e19..515de0fa 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -69,7 +69,7 @@ jobs: tags="${tag_year}.${tag_month}" if [[ "${tag_month}" == "12" ]]; then - tags+=",LTS" + tags+=",lts" echo "::notice::Tag ${tag} is LTS version" else echo "::notice::Tag ${tag} is not LTS version" @@ -122,7 +122,7 @@ jobs: name: Publish Docker / Python ${{ matrix.python-version }} needs: [generate_info, publish_package] runs-on: ubuntu-latest - if: ${{ needs.generate_info.IS_TEST == 'false' }} + if: ${{ needs.generate_info.outputs.is-test == 'false' }} strategy: fail-fast: true matrix: diff --git a/crowdin.yml b/crowdin.yml new file mode 100644 index 00000000..e0c660db --- /dev/null +++ b/crowdin.yml @@ -0,0 +1,3 @@ +files: + - source: /guide/content/en/**/*.md + translation: /guide/content/%two_letters_code%/**/%original_file_name% diff --git a/readthedocs.yml b/readthedocs.yml index 87320098..f6a89418 100644 --- a/readthedocs.yml +++ b/readthedocs.yml @@ -1,9 +1,12 @@ version: 2 python: - version: 3.8 install: - method: pip path: . extra_requirements: - docs - system_packages: true + +build: + os: "ubuntu-22.04" + tools: + python: "3.8" diff --git a/sanic/helpers.py b/sanic/helpers.py index d7ac8968..fbdac97f 100644 --- a/sanic/helpers.py +++ b/sanic/helpers.py @@ -122,25 +122,6 @@ def is_hop_by_hop_header(header): return header.lower() in _HOP_BY_HOP_HEADERS -def remove_entity_headers(headers, allowed=("content-location", "expires")): - """ - Removes all the entity headers present in the headers given. - According to RFC 2616 Section 10.3.5, - Content-Location and Expires are allowed as for the - "strong cache validator". - https://tools.ietf.org/html/rfc2616#section-10.3.5 - - returns the headers without the entity headers - """ - allowed = set([h.lower() for h in allowed]) - headers = { - header: value - for header, value in headers.items() - if not is_entity_header(header) or header.lower() in allowed - } - return headers - - def import_string(module_name, package=None): """ import a module or class by string path. diff --git a/sanic/response/types.py b/sanic/response/types.py index 9d8a8e73..8dbde38e 100644 --- a/sanic/response/types.py +++ b/sanic/response/types.py @@ -24,7 +24,6 @@ from sanic.helpers import ( Default, _default, has_message_body, - remove_entity_headers, ) from sanic.http import Http @@ -104,9 +103,6 @@ class BaseHTTPResponse: Returns: Iterator[Tuple[bytes, bytes]]: A list of header tuples encoded in bytes for sending """ # noqa: E501 - # TODO: Make a blacklist set of header names and then filter with that - if self.status in (304, 412): # Not Modified, Precondition Failed - self.headers = remove_entity_headers(self.headers) if has_message_body(self.status): self.headers.setdefault("content-type", self.content_type) # Encode headers into bytes
sanic-org/sanic
57d44f263fa84bd5cd6f77b5565825640d85b1e2
diff --git a/tests/test_helpers.py b/tests/test_helpers.py index cecdd7c6..8f62121b 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -41,28 +41,6 @@ def test_is_hop_by_hop_header(): assert helpers.is_hop_by_hop_header(header) is expected -def test_remove_entity_headers(): - tests = ( - ({}, {}), - ({"Allow": "GET, POST, HEAD"}, {}), - ( - { - "Content-Type": "application/json", - "Expires": "Wed, 21 Oct 2015 07:28:00 GMT", - "Foo": "Bar", - }, - {"Expires": "Wed, 21 Oct 2015 07:28:00 GMT", "Foo": "Bar"}, - ), - ( - {"Allow": "GET, POST, HEAD", "Content-Location": "/test"}, - {"Content-Location": "/test"}, - ), - ) - - for header, expected in tests: - assert helpers.remove_entity_headers(header) == expected - - def test_import_string_class(): obj = helpers.import_string("sanic.config.Config") assert isinstance(obj, Config) diff --git a/tests/test_response.py b/tests/test_response.py index 42180b69..9f39b4e0 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -178,6 +178,10 @@ def json_app(app): async def unmodified_handler(request: Request): return json(JSON_DATA, status=304) + @app.get("/precondition") + async def precondition_handler(request: Request): + return json(JSON_DATA, status=412) + @app.delete("/") async def delete_handler(request: Request): return json(None, status=204) @@ -193,6 +197,10 @@ def test_json_response(json_app): assert response.text == json_dumps(JSON_DATA) assert response.json == JSON_DATA + request, response = json_app.test_client.get("/precondition") + assert response.status == 412 + assert response.json == JSON_DATA + def test_no_content(json_app): request, response = json_app.test_client.get("/no-content")
The Sanic built-in server blocks for exactly 90 seconds on status code 412 ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug When responding to any request in the Sanic development server, it usually responds immediately. However, if the response has status code 412, it takes is very slow and takes exactly 90 seconds to respond, after the handler finishes. This behavior does not happen when running Sanic with uvicorn. Only the official Sanic server. ### Code snippet ```python import sanic app = sanic.Sanic(__name__) @app.get("/") async def root(req: sanic.Request): status = int(req.args.get("status", "200")) return sanic.json({"message": "Hello World"}, status=status) ``` ### Expected Behavior ```bash sanic main:app --port 8051 ``` Then: ```sh-session $ curl http://localhost:8051 {"message":"Hello World"} $ curl http://localhost:8051/?status=400 # fine {"message":"Hello World"} $ curl http://localhost:8051/?status=411 # fine {"message":"Hello World"} $ curl http://localhost:8051/?status=413 # fine {"message":"Hello World"} $ curl http://localhost:8051/?status=412 # stalls with no response for 90 seconds ``` ### How do you run Sanic? Sanic CLI ### Operating System Linux ### Sanic Version Sanic v23.6.0 ### Additional context I have reproduced this on both Linux and macOS. I have also reproduced this using both the Sanic CLI and the `Sanic.serve()` function programmatically.
0.0
57d44f263fa84bd5cd6f77b5565825640d85b1e2
[ "tests/test_response.py::test_json_response" ]
[ "tests/test_helpers.py::test_has_message_body", "tests/test_helpers.py::test_is_entity_header", "tests/test_helpers.py::test_is_hop_by_hop_header", "tests/test_helpers.py::test_import_string_class", "tests/test_helpers.py::test_import_string_module", "tests/test_helpers.py::test_import_string_exception", "tests/test_response.py::test_response_body_not_a_string", "tests/test_response.py::test_method_not_allowed", "tests/test_response.py::test_response_header", "tests/test_response.py::test_response_content_length", "tests/test_response.py::test_response_content_length_with_different_data_types", "tests/test_response.py::test_no_content", "tests/test_response.py::test_chunked_streaming_adds_correct_headers", "tests/test_response.py::test_chunked_streaming_returns_correct_content", "tests/test_response.py::test_chunked_streaming_returns_correct_content_asgi", "tests/test_response.py::test_non_chunked_streaming_adds_correct_headers", "tests/test_response.py::test_non_chunked_streaming_adds_correct_headers_asgi", "tests/test_response.py::test_non_chunked_streaming_returns_correct_content", "tests/test_response.py::test_stream_response_with_cookies", "tests/test_response.py::test_stream_response_without_cookies", "tests/test_response.py::test_file_response[200-test.file]", "tests/test_response.py::test_file_response[200-decode", "tests/test_response.py::test_file_response[200-python.png]", "tests/test_response.py::test_file_response[401-test.file]", "tests/test_response.py::test_file_response[401-decode", "tests/test_response.py::test_file_response[401-python.png]", "tests/test_response.py::test_file_response_custom_filename[test.file-my_file.txt]", "tests/test_response.py::test_file_response_custom_filename[decode", "tests/test_response.py::test_file_response_custom_filename[python.png-logo.png]", "tests/test_response.py::test_file_head_response[test.file]", "tests/test_response.py::test_file_head_response[decode", "tests/test_response.py::test_file_stream_response[test.file]", "tests/test_response.py::test_file_stream_response[decode", "tests/test_response.py::test_file_stream_response[python.png]", "tests/test_response.py::test_file_stream_response_custom_filename[test.file-my_file.txt]", "tests/test_response.py::test_file_stream_response_custom_filename[decode", "tests/test_response.py::test_file_stream_response_custom_filename[python.png-logo.png]", "tests/test_response.py::test_file_stream_head_response[test.file]", "tests/test_response.py::test_file_stream_head_response[decode", "tests/test_response.py::test_file_stream_response_range[1024-0-1024-test.file]", "tests/test_response.py::test_file_stream_response_range[1024-0-1024-decode", "tests/test_response.py::test_file_stream_response_range[1024-0-1024-python.png]", "tests/test_response.py::test_file_stream_response_range[4096-1024-8192-test.file]", "tests/test_response.py::test_file_stream_response_range[4096-1024-8192-decode", "tests/test_response.py::test_file_stream_response_range[4096-1024-8192-python.png]", "tests/test_response.py::test_raw_response", "tests/test_response.py::test_empty_response", "tests/test_response.py::test_direct_response_stream", "tests/test_response.py::test_two_respond_calls", "tests/test_response.py::test_multiple_responses", "tests/test_response.py::test_file_response_headers[test.file]", "tests/test_response.py::test_file_response_headers[decode", "tests/test_response.py::test_file_response_headers[python.png]", "tests/test_response.py::test_file_validate", "tests/test_response.py::test_file_validating_invalid_header[test.file]", "tests/test_response.py::test_file_validating_invalid_header[decode", "tests/test_response.py::test_file_validating_invalid_header[python.png]", "tests/test_response.py::test_file_validating_304_response_file_route[test.file]", "tests/test_response.py::test_file_validating_304_response_file_route[decode", "tests/test_response.py::test_file_validating_304_response_file_route[python.png]", "tests/test_response.py::test_file_validating_304_response[test.file]", "tests/test_response.py::test_file_validating_304_response[decode", "tests/test_response.py::test_file_validating_304_response[python.png]", "tests/test_response.py::test_stream_response_with_default_headers" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-20 19:01:13+00:00
mit
5,330
sanic-org__sanic-2837
diff --git a/sanic/cookies/request.py b/sanic/cookies/request.py index 456c8872..06eab4f1 100644 --- a/sanic/cookies/request.py +++ b/sanic/cookies/request.py @@ -73,12 +73,17 @@ def parse_cookie(raw: str) -> Dict[str, List[str]]: cookies: Dict[str, List[str]] = {} for token in raw.split(";"): - name, __, value = token.partition("=") + name, sep, value = token.partition("=") name = name.strip() value = value.strip() - if not name: - continue + # Support cookies =value or plain value with no name + # https://github.com/httpwg/http-extensions/issues/159 + if not sep: + if not name: + # Empty value like ;; or a cookie header with no value + continue + name, value = "", name if COOKIE_NAME_RESERVED_CHARS.search(name): # no cov continue diff --git a/sanic/models/protocol_types.py b/sanic/models/protocol_types.py index 61924a6c..a402cf1f 100644 --- a/sanic/models/protocol_types.py +++ b/sanic/models/protocol_types.py @@ -3,7 +3,7 @@ from __future__ import annotations import sys from asyncio import BaseTransport -from typing import TYPE_CHECKING, Any, AnyStr, Optional +from typing import TYPE_CHECKING, Any, Optional, Union if TYPE_CHECKING: @@ -19,10 +19,10 @@ else: from typing import Protocol class HTMLProtocol(Protocol): - def __html__(self) -> AnyStr: + def __html__(self) -> Union[str, bytes]: ... - def _repr_html_(self) -> AnyStr: + def _repr_html_(self) -> Union[str, bytes]: ... class Range(Protocol):
sanic-org/sanic
a5a9658896984ddad484e168d4cb5c96e589fbad
diff --git a/tests/test_cookies.py b/tests/test_cookies.py index 547cdd42..976ddabd 100644 --- a/tests/test_cookies.py +++ b/tests/test_cookies.py @@ -7,12 +7,28 @@ import pytest from sanic import Request, Sanic from sanic.compat import Header from sanic.cookies import Cookie, CookieJar -from sanic.cookies.request import CookieRequestParameters +from sanic.cookies.request import CookieRequestParameters, parse_cookie from sanic.exceptions import ServerError from sanic.response import text from sanic.response.convenience import json +def test_request_cookies(): + cdict = parse_cookie("foo=one; foo=two; abc = xyz;;bare;=bare2") + assert cdict == { + "foo": ["one", "two"], + "abc": ["xyz"], + "": ["bare", "bare2"], + } + c = CookieRequestParameters(cdict) + assert c.getlist("foo") == ["one", "two"] + assert c.getlist("abc") == ["xyz"] + assert c.getlist("") == ["bare", "bare2"] + assert ( + c.getlist("bare") == None + ) # [] might be sensible but we got None for now + + # ------------------------------------------------------------ # # GET # ------------------------------------------------------------ # diff --git a/tests/test_graceful_shutdown.py b/tests/test_graceful_shutdown.py index d125ba3d..7b1ceb62 100644 --- a/tests/test_graceful_shutdown.py +++ b/tests/test_graceful_shutdown.py @@ -1,6 +1,8 @@ import asyncio import logging +import pytest + from pytest import LogCaptureFixture from sanic.response import empty @@ -9,6 +11,7 @@ from sanic.response import empty PORT = 42101 [email protected](reason="This test runs fine locally, but fails on CI") def test_no_exceptions_when_cancel_pending_request( app, caplog: LogCaptureFixture ):
Cookie totally breaks if the client sets a bare cookie ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug A cookie may be not in the `key=value` format. For example. if the JS code runs `document.cookie = "bad"`, it becomes: ![image](https://github.com/sanic-org/sanic/assets/6646473/c9a1f53c-62bf-4516-9003-49fed08773dc) I don't know how to call it. I will use the term "bare cookie" in this report. In the following requests with a bare cookie, the Cookie HTTP header becomes: `Cookie: key=value; bad` ![image](https://github.com/sanic-org/sanic/assets/6646473/536bdf38-61ad-4f31-bb78-6c7844433298) It seems that Sanic cannot parse the header with bare cookies, and will throw all cookies (including the legimit `key=value` pair) away. See the code snippet below. ### Code snippet ```python from sanic import Sanic from sanic.response import html, text app = Sanic("test") app.config.AUTO_EXTEND = False @app.get("/") async def route1(request): return html('<script>document.cookie="key=value"; document.cookie="bad"; location.href="/fire";</script>') @app.get("/fire") async def route2(request): return text(f''' headers = {request.headers.get("Cookie")} key = {request.cookies.get("key", "none")} ''') if __name__ == '__main__': app.run(port=4321, debug=True) ``` Then visit `http://127.0.0.1:4321/` in Chrome. The page shows: ``` headers = key=value; bad key = none ``` ### Expected Behavior The page should show: ``` headers = key=value; bad key = value ``` ### How do you run Sanic? As a script (`app.run` or `Sanic.serve`) ### Operating System Windows ### Sanic Version 22.12.0 ### Additional context I am using the latest stable Chrome (117.0.5938.150) to reproduce this.
0.0
a5a9658896984ddad484e168d4cb5c96e589fbad
[ "tests/test_cookies.py::test_request_cookies" ]
[ "tests/test_cookies.py::test_cookies", "tests/test_cookies.py::test_cookies_asgi", "tests/test_cookies.py::test_false_cookies_encoded[False-False]", "tests/test_cookies.py::test_false_cookies_encoded[True-True]", "tests/test_cookies.py::test_false_cookies[False-False]", "tests/test_cookies.py::test_false_cookies[True-True]", "tests/test_cookies.py::test_http2_cookies", "tests/test_cookies.py::test_cookie_options", "tests/test_cookies.py::test_cookie_deletion", "tests/test_cookies.py::test_cookie_reserved_cookie", "tests/test_cookies.py::test_cookie_illegal_key_format", "tests/test_cookies.py::test_cookie_set_unknown_property", "tests/test_cookies.py::test_cookie_set_same_key", "tests/test_cookies.py::test_cookie_max_age[0]", "tests/test_cookies.py::test_cookie_max_age[300]", "tests/test_cookies.py::test_cookie_max_age[301]", "tests/test_cookies.py::test_cookie_bad_max_age[30.0]", "tests/test_cookies.py::test_cookie_bad_max_age[30.1]", "tests/test_cookies.py::test_cookie_bad_max_age[test]", "tests/test_cookies.py::test_cookie_expires[expires0]", "tests/test_cookies.py::test_cookie_expires_illegal_instance_type[Fri,", "tests/test_cookies.py::test_request_with_duplicate_cookie_key[foo=one;", "tests/test_cookies.py::test_request_with_duplicate_cookie_key[foo=one;foo=two]", "tests/test_cookies.py::test_cookie_jar_cookies", "tests/test_cookies.py::test_cookie_jar_has_cookie", "tests/test_cookies.py::test_cookie_jar_get_cookie", "tests/test_cookies.py::test_cookie_jar_add_cookie_encode", "tests/test_cookies.py::test_cookie_jar_old_school_cookie_encode", "tests/test_cookies.py::test_cookie_jar_delete_cookie_encode", "tests/test_cookies.py::test_cookie_jar_old_school_delete_encode", "tests/test_cookies.py::test_bad_cookie_prarms", "tests/test_cookies.py::test_cookie_accessors", "tests/test_cookies.py::test_cookie_accessor_hyphens", "tests/test_cookies.py::test_cookie_passthru", "tests/test_graceful_shutdown.py::test_completes_request" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-10-14 18:31:12+00:00
mit
5,331
sanic-org__sanic-2858
diff --git a/sanic/server/protocols/websocket_protocol.py b/sanic/server/protocols/websocket_protocol.py index 52a33bf8..7e026d8d 100644 --- a/sanic/server/protocols/websocket_protocol.py +++ b/sanic/server/protocols/websocket_protocol.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Optional, Sequence, cast +from typing import Optional, Sequence, cast try: # websockets < 11.0 @@ -8,19 +8,18 @@ except ImportError: # websockets >= 11.0 from websockets.protocol import State # type: ignore from websockets.server import ServerProtocol # type: ignore +from websockets import http11 +from websockets.datastructures import Headers as WSHeaders from websockets.typing import Subprotocol from sanic.exceptions import SanicException from sanic.log import logger +from sanic.request import Request from sanic.server import HttpProtocol from ..websockets.impl import WebsocketImplProtocol -if TYPE_CHECKING: - from websockets import http11 - - OPEN = State.OPEN CLOSING = State.CLOSING CLOSED = State.CLOSED @@ -94,6 +93,13 @@ class WebSocketProtocol(HttpProtocol): else: return super().close_if_idle() + @staticmethod + def sanic_request_to_ws_request(request: Request): + return http11.Request( + path=request.path, + headers=WSHeaders(request.headers), + ) + async def websocket_handshake( self, request, subprotocols: Optional[Sequence[str]] = None ): @@ -117,7 +123,7 @@ class WebSocketProtocol(HttpProtocol): state=OPEN, logger=logger, ) - resp: "http11.Response" = ws_proto.accept(request) + resp = ws_proto.accept(self.sanic_request_to_ws_request(request)) except Exception: msg = ( "Failed to open a WebSocket connection.\n"
sanic-org/sanic
0663f11d2096db133c1c963c66fd070f2ada1fea
diff --git a/tests/test_ws_handlers.py b/tests/test_ws_handlers.py index 62362924..25932ed4 100644 --- a/tests/test_ws_handlers.py +++ b/tests/test_ws_handlers.py @@ -1,3 +1,6 @@ +import base64 +import secrets + from typing import Any, Callable, Coroutine import pytest @@ -70,6 +73,23 @@ def test_ws_handler( assert ws_proxy.client_received == ["test 1", "test 2"] +def test_ws_handler_invalid_upgrade(app: Sanic): + @app.websocket("/ws") + async def ws_echo_handler(request: Request, ws: Websocket): + async for msg in ws: + await ws.send(msg) + + ws_key = base64.b64encode(secrets.token_bytes(16)).decode("utf-8") + invalid_upgrade_headers = { + "Upgrade": "websocket", + # "Connection": "Upgrade", + "Sec-WebSocket-Key": ws_key, + "Sec-WebSocket-Version": "13", + } + _, response = app.test_client.get("/ws", headers=invalid_upgrade_headers) + assert response.status == 426 + + def test_ws_handler_async_for( app: Sanic, simple_ws_mimic_client: MimicClientType,
Websocket invalid upgrade exception handling b0rkage ### Is there an existing issue for this? - [X] I have searched the existing issues ### Describe the bug A client apparently sent no Upgrade header to a websocket endpoint, leading to an error as it should. An ugly traceback is printed on terminal even though the error eventually gets handled correctly it would seem. It would appear that the websockets module attempts to attach its exception on `request._exception` field which Sanic's Request doesn't have a slot for. This could be hidden if Sanic later used `raise BadRequest(...) from None` rather than `raise SanicException(...)`, suppressing the chain and giving a non-500 error for what really is no server error. Not sure though if that would from this context ever reach the client anyway but at least it could avoid a traceback in server log. If anyone wants to investigate and make a PR, feel free to (I am currently busy and cannot do that unfortunately). ```python Traceback (most recent call last): File "/home/user/.local/lib/python3.10/site-packages/websockets/server.py", line 111, in accept ) = self.process_request(request) File "/home/user/.local/lib/python3.10/site-packages/websockets/server.py", line 218, in process_request raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) websockets.exceptions.InvalidUpgrade: missing Upgrade header During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/sanic/sanic/server/protocols/websocket_protocol.py", line 120, in websocket_handshake resp: "http11.Response" = ws_proto.accept(request) File "/home/user/.local/lib/python3.10/site-packages/websockets/server.py", line 122, in accept request._exception = exc AttributeError: 'Request' object has no attribute '_exception' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "handle_request", line 97, in handle_request File "/home/user/sanic/sanic/app.py", line 1047, in _websocket_handler ws = await protocol.websocket_handshake(request, subprotocols) File "/home/user/sanic/sanic/server/protocols/websocket_protocol.py", line 126, in websocket_handshake raise SanicException(msg, status_code=500) sanic.exceptions.SanicException: Failed to open a WebSocket connection. See server log for more information. ``` ### Code snippet _No response_ ### Expected Behavior 400 Bad Request error reaching the client and being more silent on server side. Including the message of **missing Upgrade header** would be helpful for debugging (e.g. in case Nginx proxy config forgot to forward that header). ### How do you run Sanic? Sanic CLI ### Operating System Linux ### Sanic Version Almost 23.03.0 (a git version slightly before release) ### Additional context _No response_
0.0
0663f11d2096db133c1c963c66fd070f2ada1fea
[ "tests/test_ws_handlers.py::test_ws_handler_invalid_upgrade" ]
[ "tests/test_ws_handlers.py::test_ws_handler", "tests/test_ws_handlers.py::test_ws_handler_async_for", "tests/test_ws_handlers.py::test_request_url[]", "tests/test_ws_handlers.py::test_request_url[proxy]", "tests/test_ws_handlers.py::test_request_url[servername]", "tests/test_ws_handlers.py::test_ws_signals", "tests/test_ws_handlers.py::test_ws_signals_exception" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-26 08:39:32+00:00
mit
5,332
santosderek__Vitality-145
diff --git a/vitality/user.py b/vitality/user.py index f8fb88e..8c60b92 100644 --- a/vitality/user.py +++ b/vitality/user.py @@ -1,5 +1,18 @@ class User: - def __init__(self, _id: str, username: str, password: str, name: str = None, location: str = None, phone: int = None): + def __init__(self, + _id: str, + username: str, + password: str, + name: str = None, + location: str = None, + phone: int = None, + body_type: str = None, + body_fat: str = None, + height: str = None, + weight: str = None, + exp: str = None, + goal_weight: str = None, + goal_body_fat: str = None): """Constructor for Trainee class.""" self.__dict__.update(dict( _id=_id, @@ -7,7 +20,14 @@ class User: password=password, name=name, location=location, - phone=phone + phone=phone, + body_type=body_type, + body_fat=body_fat, + height=height, + weight=weight, + exp=exp, + goal_weight=goal_weight, + goal_body_fat=goal_body_fat )) def as_dict(self):
santosderek/Vitality
f51456b3cb9f37ef1b19e7051c0d176afbe923d8
diff --git a/tests/test_user.py b/tests/test_trainee.py similarity index 68% rename from tests/test_user.py rename to tests/test_trainee.py index 22f405b..076f32b 100644 --- a/tests/test_user.py +++ b/tests/test_trainee.py @@ -15,7 +15,14 @@ class TestUser(unittest.TestCase): "name": "first last", "location" : "Earth", "phone" : 1234567890, - 'trainers' : [] + 'trainers' : [], + "body_type": None, + "body_fat": None, + "height": None, + "weight": None, + "exp": None, + "goal_weight": None, + "goal_body_fat": None } self.assertTrue(new_dict == comp_dict) diff --git a/tests/test_trainer.py b/tests/test_trainer.py index dad1a3c..502f4f7 100644 --- a/tests/test_trainer.py +++ b/tests/test_trainer.py @@ -7,23 +7,32 @@ class TestTrainer(unittest.TestCase): def test_as_dict(self): new_trainer = Trainer( - 0, - "test", - "password", - "None", - "first last", - "Earth", - 1234567890) + _id="0", + username="test", + password="password", + trainees=[], + name="first last", + location="Earth", + phone=1234567890 + ) new_dict = new_trainer.as_dict() + print(new_trainer.as_dict()) comp_dict = { - "_id": 0, + "_id": "0", "username": "test", "password": "password", - "trainees": "None", + "trainees": [], "name": "first last", "location": "Earth", - "phone": 1234567890 + "phone": 1234567890, + "body_type": None, + "body_fat": None, + "height": None, + "weight": None, + "exp": None, + "goal_weight": None, + "goal_body_fat": None } self.assertTrue(new_dict == comp_dict)
Update the User class **Is your feature request related to a problem? Please describe.** Update the user class to include all missing values from the Marvel Prototype. https://marvelapp.com/prototype/ba49981/screen/73696982 Please also run all test functions to make sure they all pass. **Describe the solution you'd like (If needed)** User class must contain and should all be optional: - Body Type - Body Fat - Height - Weight - Experience Points - Goal Weight - Goal Body Fat
0.0
f51456b3cb9f37ef1b19e7051c0d176afbe923d8
[ "tests/test_trainee.py::TestUser::test_as_dict", "tests/test_trainer.py::TestTrainer::test_as_dict" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-11-07 22:32:32+00:00
mit
5,333
santoshphilip__eppy-284
diff --git a/eppy/bunch_subclass.py b/eppy/bunch_subclass.py index 445576f..ba78e47 100644 --- a/eppy/bunch_subclass.py +++ b/eppy/bunch_subclass.py @@ -100,6 +100,7 @@ def addfunctions(abunch): "height": fh.height, # not working correctly "width": fh.width, # not working correctly "azimuth": fh.azimuth, + "true_azimuth": fh.true_azimuth, "tilt": fh.tilt, "coords": fh.getcoords, # needed for debugging } diff --git a/eppy/function_helpers.py b/eppy/function_helpers.py index c455986..140e569 100644 --- a/eppy/function_helpers.py +++ b/eppy/function_helpers.py @@ -57,6 +57,15 @@ def azimuth(ddtt): return g_surface.azimuth(coords) +def true_azimuth(ddtt): + """azimuth of the surface""" + idf = ddtt.theidf + building_north_axis = idf.idfobjects["building".upper()][0].North_Axis + coords = getcoords(ddtt) + surface_azimuth = g_surface.azimuth(coords) + return g_surface.true_azimuth(building_north_axis, surface_azimuth) + + def tilt(ddtt): """tilt of the surface""" coords = getcoords(ddtt) diff --git a/eppy/geometry/surface.py b/eppy/geometry/surface.py index 69211f6..8d2bfb9 100644 --- a/eppy/geometry/surface.py +++ b/eppy/geometry/surface.py @@ -131,6 +131,12 @@ def azimuth(poly): return angle2vecs(vec_azi, vec_n) +def true_azimuth(building_north_axis, surface_azimuth): + """True azimuth of a polygon poly""" + building_north_axis = 0 if building_north_axis == "" else building_north_axis + return (building_north_axis + surface_azimuth) % 360 + + def tilt(poly): """Tilt of a polygon poly""" num = len(poly) - 1
santoshphilip/eppy
98e58583dce6c0fcec9c7b1ff1142bae0a67ddc7
diff --git a/eppy/tests/geometry_tests/test_surface.py b/eppy/tests/geometry_tests/test_surface.py index c57fec7..6d5b32c 100644 --- a/eppy/tests/geometry_tests/test_surface.py +++ b/eppy/tests/geometry_tests/test_surface.py @@ -106,6 +106,19 @@ def test_azimuth(): assert almostequal(answer, result, places=3) == True +def test_true_azimuth(): + """test the true azimuth of a polygon poly""" + data = ( + ("", 180, 180), + # building_north_axis, surface_azimuth, answer, + (20, 0, 20), + (240, 180, 60), + ) + for building_north_axis, surface_azimuth, answer in data: + result = surface.true_azimuth(building_north_axis, surface_azimuth) + assert almostequal(answer, result, places=3) == True + + def test_tilt(): """test the tilt of a polygon poly""" data = (
surface.azimuth does not take into account the building.North_Axis problem: surface.azimuth does not take into account the building.North_Axis As a step to resolving this issue, we need a function def true_azimuth(building_north_axis, surface_azimuth) # return "the azimuth based on surface.azimuth and building.North_Axis" The location of this function should be - eppy - geometry - surface.true_azimuth The unit tests should be in - eppy - tests - test_surface.py This issue is assigned to @airallergy @airallergy, see https://github.com/santoshphilip/eppy/blob/master/CONTRIBUTING.md and use the second method where you fork the repository and then do a pull request
0.0
98e58583dce6c0fcec9c7b1ff1142bae0a67ddc7
[ "eppy/tests/geometry_tests/test_surface.py::test_true_azimuth" ]
[ "eppy/tests/geometry_tests/test_surface.py::test_area", "eppy/tests/geometry_tests/test_surface.py::test_height", "eppy/tests/geometry_tests/test_surface.py::test_width", "eppy/tests/geometry_tests/test_surface.py::test_azimuth", "eppy/tests/geometry_tests/test_surface.py::test_tilt" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-06-05 03:58:34+00:00
mit
5,334