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
cdent__gabbi-327
diff --git a/docs/source/format.rst b/docs/source/format.rst index 1217255..847c93c 100644 --- a/docs/source/format.rst +++ b/docs/source/format.rst @@ -181,6 +181,11 @@ Response Expectations ``response_strings`` A list of string fragments expected to be present in the response body. + If the value is wrapped in ``/.../`` + the response body will be searched + for the value as a regular + expression. + ``response_json_paths`` A dictionary of JSONPath rules paired with expected matches. Using this rule requires that the content being diff --git a/gabbi/handlers/base.py b/gabbi/handlers/base.py index 1bbafe0..980eebb 100644 --- a/gabbi/handlers/base.py +++ b/gabbi/handlers/base.py @@ -66,6 +66,15 @@ class ResponseHandler: """ pass + def is_regex(self, value): + """Check if the value is formatted to looks like a regular expression. + + Meaning it starts and ends with "/". + """ + return ( + value.startswith('/') and value.endswith('/') and len(value) > 1 + ) + def _register(self): """Register this handler on the provided test class.""" self.response_handler = None diff --git a/gabbi/handlers/core.py b/gabbi/handlers/core.py index 97a1d87..cc80b1d 100644 --- a/gabbi/handlers/core.py +++ b/gabbi/handlers/core.py @@ -22,8 +22,18 @@ class StringResponseHandler(base.ResponseHandler): test_key_value = [] def action(self, test, expected, value=None): - expected = test.replace_template(expected) - test.assert_in_or_print_output(expected, test.output) + is_regex = self.is_regex(expected) + expected = test.replace_template(expected, escape_regex=is_regex) + + if is_regex: + # Trim off / + expected = expected[1:-1] + test.assertRegex( + test.output, expected, + 'Expect resonse body %s to match /%s/' % + (test.output, expected)) + else: + test.assert_in_or_print_output(expected, test.output) class ForbiddenHeadersResponseHandler(base.ResponseHandler): @@ -56,9 +66,7 @@ class HeadersResponseHandler(base.ResponseHandler): response = test.response header_value = str(value) - is_regex = (header_value.startswith('/') and - header_value.endswith('/') and - len(header_value) > 1) + is_regex = self.is_regex(header_value) header_value = test.replace_template(header_value, escape_regex=is_regex) diff --git a/gabbi/handlers/jsonhandler.py b/gabbi/handlers/jsonhandler.py index 34dc7ae..2ee49d5 100644 --- a/gabbi/handlers/jsonhandler.py +++ b/gabbi/handlers/jsonhandler.py @@ -118,10 +118,7 @@ class JSONHandler(base.ContentHandler): 'match %s' % (rhs_path, value)) # If expected is a string, check to see if it is a regex. - is_regex = (isinstance(value, str) and - value.startswith('/') and - value.endswith('/') and - len(value) > 1) + is_regex = isinstance(value, str) and self.is_regex(value) expected = (rhs_match or test.replace_template(value, escape_regex=is_regex)) match = lhs_match
cdent/gabbi
6939357f81ff7802a42c9f9e3fdfe0677dbf3cc8
diff --git a/gabbi/tests/gabbits_intercept/regex.yaml b/gabbi/tests/gabbits_intercept/regex.yaml index 9a0c055..1c01c63 100644 --- a/gabbi/tests/gabbits_intercept/regex.yaml +++ b/gabbi/tests/gabbits_intercept/regex.yaml @@ -1,4 +1,4 @@ -# Confirm regex handling in response and json path headers +# Confirm regex handling in response headers, strings and json path handlers tests: - name: regex header test url: /cow?alpha=1 @@ -19,3 +19,30 @@ tests: $.alpha: /ow$/ $.beta: /(?!cow).*/ $.gamma: /\d+/ + +- name: regex string test json + PUT: /cow + request_headers: + content-type: application/json + data: + alpha: cow + beta: pig + gamma: 1 + response_strings: + - '/"alpha": "cow",/' + +- name: regex string test multiline + GET: /presenter + response_strings: + - '/Hello World/' + - '/dolor sit/' + +- name: regex string test splat + GET: /presenter + response_strings: + - '/dolor.*amet/' + +- name: regex string test mix + GET: /presenter + response_strings: + - '/[Hh]el{2}o [Ww]orld/'
Support regex in response_strings Many of the other test handlers support regex in the value, but `response_strings` does not. This should probably fixed, but it has the potential to cause errors in existing tests so we may want to consider it as a version 3 to signal the change.
0.0
6939357f81ff7802a42c9f9e3fdfe0677dbf3cc8
[ "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_string_test_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_string_test_multiline]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_string_test_splat]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_string_test_mix]" ]
[ "gabbi/tests/test_data_to_string.py::TestDataToString::testHappyPath", "gabbi/tests/test_data_to_string.py::TestDataToString::testNoContentType", "gabbi/tests/test_data_to_string.py::TestDataToString::testNoHandler", "gabbi/tests/test_driver.py::DriverTest::test_build_require_ssl", "gabbi/tests/test_driver.py::DriverTest::test_build_requires_host_or_intercept", "gabbi/tests/test_driver.py::DriverTest::test_build_url_target", "gabbi/tests/test_driver.py::DriverTest::test_build_url_target_forced_ssl", "gabbi/tests/test_driver.py::DriverTest::test_build_url_use_prior_test", "gabbi/tests/test_driver.py::DriverTest::test_build_with_url_provides_host", "gabbi/tests/test_driver.py::DriverTest::test_driver_loads_three_tests", "gabbi/tests/test_driver.py::DriverTest::test_driver_prefix", "gabbi/tests/test_fixtures.py::FixtureTest::test_fixture_informs_on_exception", "gabbi/tests/test_fixtures.py::FixtureTest::test_fixture_starts_and_stop", "gabbi/tests/test_handlers.py::HandlersTest::test_empty_response_handler", "gabbi/tests/test_handlers.py::HandlersTest::test_resonse_headers_stringify", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_data", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_header", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_noregex_path_match", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_noregex_path_nomatch", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex_path_match", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex_path_nomatch", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_substitute_esc_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_substitute_noregex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_substitute_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_dict_type", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_data", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_path", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_from_disk_json_path", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_from_disk_json_path_fail", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_regex_number", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_regex_path_match", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_regex_path_nomatch", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_substitution_esc_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_substitution_noregex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_substitution_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_yamlhandler", "gabbi/tests/test_handlers.py::HandlersTest::test_response_string_list_type", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail_big_output", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail_big_payload", "gabbi/tests/test_handlers.py::TestJSONHandlerAccept::test_many_content_types", "gabbi/tests/test_history.py::HistoryTest::test_cookie_replace_history", "gabbi/tests/test_history.py::HistoryTest::test_cookie_replace_prior", "gabbi/tests/test_history.py::HistoryTest::test_cookie_replace_prior_regex", "gabbi/tests/test_history.py::HistoryTest::test_header_replace_prior", "gabbi/tests/test_history.py::HistoryTest::test_header_replace_with_history", "gabbi/tests/test_history.py::HistoryTest::test_header_replace_with_history_regex", "gabbi/tests/test_history.py::HistoryTest::test_location_replace_history", "gabbi/tests/test_history.py::HistoryTest::test_location_replace_prior", "gabbi/tests/test_history.py::HistoryTest::test_location_replace_prior_regex", "gabbi/tests/test_history.py::HistoryTest::test_response_replace_prior", "gabbi/tests/test_history.py::HistoryTest::test_response_replace_prior_regex", "gabbi/tests/test_history.py::HistoryTest::test_response_replace_with_history", "gabbi/tests/test_history.py::HistoryTest::test_url_replace_history", "gabbi/tests/test_history.py::HistoryTest::test_url_replace_prior", "gabbi/tests/test_history.py::HistoryTest::test_url_replace_prior_regex", "gabbi/tests/test_inner_fixture.py::test_pytest[gabbi.tests.test_inner_fixture:inner_get_one]", "gabbi/tests/test_inner_fixture.py::test_pytest[gabbi.tests.test_inner_fixture:inner_get_two]", "gabbi/tests/test_inner_fixture.py::test_pytest[gabbi.tests.test_inner_fixture:inner_get_three]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_load_data_dictionary]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_load_data_list]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_load_json_file]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_load_image_file]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_json_value_from_disk]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_partial_json_from_disk]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_post_data_for_next]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:data_post_data_from_prior_response]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:method-shortcut_simple_post]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:method-shortcut_post_with_query]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:method-shortcut_simple_get]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:method-shortcut_arbitrary_method]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_post_some_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_post_some_more_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_post_even_more_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_post_even_more_json_quote_different]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_use_raw_json_from_response]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_post_a_raw_int_as_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_repost_that_raw_int]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_backref_json_fail_start]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_get_a_historical_response]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:backref_get_a_historical_response_via_jsonpath]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-left-side_left_side_json_one]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-left-side_expand_left_side]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-left-side_expand_environ_left_side]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-left-side_set_key_and_value]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-left-side_check_key_and_value]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:fixture_just_to_see]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:fixture_just_to_see_one]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:fixture_just_to_see_two]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:fixture_just_to_see_three]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:forbiddenheaders_header_not_there_basic]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_put_no_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_post_no_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_patch_no_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_put_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_post_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:contenttype_patch_content-type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:cookie_get_a_cookie]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:cookie_use_that_cookie_in_a_url]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:cookie_use_a_historical_cookie]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_default_casts]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_cast_to_string]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_json_set_up]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_send_casted_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_historic_casted_json]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:casting_internal_json_fine]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:jsonbody_test_fully_body]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:jsonbody_test_empty_dict]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:jsonbody_test_empty_list]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:disable-response-handler_get_some_not_json_gloss]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:verbosity_confirm_notempty]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:host-header_ssl_no_host]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:host-header_ssl_with_host]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:host-header_ssl_with_capitalised_host]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:host-header_host_without_ssl]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:poll_poller]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:poll_create_a_thing]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:poll_loop_location]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_simple_param]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_joined_params]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_multi_params]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_replacers_in_params]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_unicode]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:queryparams_url_in_param]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_get_simple_page]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_inheritance_of_defaults]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_bogus_method]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_query_returned]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_simple_post]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_use_prior_location]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_use_a_historical_location]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_checklimit]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_post_a_body]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_get_location_from_headers]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_get_historical_location_from_headers]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_post_a_body_with_query]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_get_ssl_page]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_test_binary_handling]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_confirm_environ]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_test_pluggable_response]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:self_json_derived_content_type]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-extensions_test_len]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-extensions_test_sort]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-extensions_test_filtered]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_get_a_url_the_first_time]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_get_that_same_url_again]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_get_it_a_third_time]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_add_some_query_params]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_now_last_url_does_not_have_those_query_params]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_last_with_adjusted_parameters]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_get_a_historical_url]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:last-url_get_prior_url]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_post_data]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_use_data]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_from_environ]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_with_list]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_object_with_list]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_post_extra_data]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_check_posted_data]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_post_again_and_check_the_results]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_post_again_and_check_the_results_(reversed)]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:coerce_string_internal_replace]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_header_test]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:regex_regex_jsonpath_test]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-right-side_json_encoded_value_from_disk]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-right-side_json_parital_from_disk]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:json-right-side_json_partial_both_sides]", "gabbi/tests/test_intercept.py::test_pytest[gabbi.tests.test_intercept:header-key_header_named_http]", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_basic_match", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_embedded_list_handling", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_filtered_list", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_len_object_list", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_len_simple_list", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_list_handling", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_sorted_object_list", "gabbi/tests/test_jsonpath.py::JSONPathTest::test_sorted_simple_list", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:google_google]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:google_follow_redirects]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:google_google_full_url]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:google_google_russia]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:google_follow_redirects_full_url]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:host-header_ssl_no_host]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:host-header_ssl_with_host]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:host-header_host_without_ssl]", "gabbi/tests/test_live.py::test_pytest[gabbi.tests.test_live:host-header_wrong_host_without_ssl]", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file_in_directory", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file_in_parent_dir", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file_in_root", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file_not_within_test_directory", "gabbi/tests/test_load_data_file.py::DataFileTest::test_load_file_within_test_directory", "gabbi/tests/test_parse_url.py::UrlParseTest::test_add_query_params", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_http", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_https", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_https_no_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_default_port_int", "gabbi/tests/test_parse_url.py::UrlParseTest::test_extend_query_params", "gabbi/tests/test_parse_url.py::UrlParseTest::test_extend_query_params_full_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_https_port_80_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_full_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_no_double_colon_wacky_ssl", "gabbi/tests/test_parse_url.py::UrlParseTest::test_ipv6_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_full", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_prefix", "gabbi/tests/test_parse_url.py::UrlParseTest::test_parse_url", "gabbi/tests/test_parse_url.py::UrlParseTest::test_with_ssl", "gabbi/tests/test_replacers.py::EnvironReplaceTest::test_environ_boolean", "gabbi/tests/test_replacers.py::TestReplaceHeaders::test_empty_headers", "gabbi/tests/test_runner.py::RunnerTest::test_custom_response_handler", "gabbi/tests/test_runner.py::RunnerTest::test_data_dir_good", "gabbi/tests/test_runner.py::RunnerTest::test_exit_code", "gabbi/tests/test_runner.py::RunnerTest::test_input_files", "gabbi/tests/test_runner.py::RunnerTest::test_quiet_is_quiet", "gabbi/tests/test_runner.py::RunnerTest::test_stdin_data_dir", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing", "gabbi/tests/test_runner.py::RunnerTest::test_target_url_parsing_standard_port", "gabbi/tests/test_runner.py::RunnerTest::test_unsafe_yaml", "gabbi/tests/test_runner.py::RunnerTest::test_verbose_output_formatting", "gabbi/tests/test_runner.py::RunnerTest::test_verbosity_arg_all", "gabbi/tests/test_runner.py::RunnerTest::test_verbosity_arg_body", "gabbi/tests/test_runner.py::RunnerTest::test_verbosity_arg_headers", "gabbi/tests/test_runner.py::RunnerTest::test_verbosity_arg_none", "gabbi/tests/test_suite.py::SuiteTest::test_suite_catches_fixture_fail", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_dict_on_invalid_key", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_inner_list_required", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_method_url_pair_duplication_format_error", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_method_url_pair_format_error", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_name_key_required", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_response_handlers_same_test_key_yaml_first", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_response_handlers_same_test_key_yaml_last", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_tests_key_required", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_unsupported_key_errors", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_upper_dict_required", "gabbi/tests/test_suitemaker.py::SuiteMakerTest::test_url_key_required", "gabbi/tests/test_syntax_warning.py::DriverTest::test_driver_warnings_on_files", "gabbi/tests/test_unsafe_yaml.py::test_pytest[gabbi.tests.test_unsafe_yaml:nan_test_nan]", "gabbi/tests/test_use_prior_test.py::UsePriorTest::test_use_prior_default_true", "gabbi/tests/test_use_prior_test.py::UsePriorTest::test_use_prior_false", "gabbi/tests/test_use_prior_test.py::UsePriorTest::test_use_prior_true", "gabbi/tests/test_utils.py::BinaryTypesTest::test_binary", "gabbi/tests/test_utils.py::BinaryTypesTest::test_not_binary", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_default", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_error_default", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_extra", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_nocharset_default", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_override_default", "gabbi/tests/test_utils.py::ParseContentTypeTest::test_parse_simple", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_bad_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_both", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_default_charset", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_multiple_params", "gabbi/tests/test_utils.py::ExtractContentTypeTest::test_extract_content_type_with_charset", "gabbi/tests/test_utils.py::ColorizeTest::test_colorize_missing_color", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_already_bracket", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_full", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ipv6_ssl_weird_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_no_double_colon", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_not_ssl_on_443", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_port_and_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_prefix", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_preserve_query", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_simple", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl", "gabbi/tests/test_utils.py::CreateURLTest::test_create_url_ssl_on_80", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_host_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_hostport_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_localhost", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ipv6_url_long", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_no_port", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_plain_url_with_port", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_simple_hostport_with_prefix", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port80_url", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_port_url", "gabbi/tests/test_utils.py::UtilsHostInfoFromTarget::test_ssl_url", "gabbi/tests/test_yaml_disk_loading_jsonhandler.py::test_pytest[gabbi.tests.test_yaml_disk_loading_jsonhandler:yaml-from-disk_yaml_encoded_value_from_disk]", "gabbi/tests/test_yaml_disk_loading_jsonhandler.py::test_pytest[gabbi.tests.test_yaml_disk_loading_jsonhandler:yaml-from-disk_json_encoded_value_from_disk]", "gabbi/tests/test_yaml_disk_loading_jsonhandler.py::test_pytest[gabbi.tests.test_yaml_disk_loading_jsonhandler:yaml-from-disk_yaml_parital_from_disk]", "gabbi/tests/test_yaml_disk_loading_jsonhandler.py::test_pytest[gabbi.tests.test_yaml_disk_loading_jsonhandler:yaml-from-disk_yaml_partial_both_sides]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-03-02 15:05:04+00:00
apache-2.0
1,527
cekit__cekit-220
diff --git a/bash_completion/cekit b/bash_completion/cekit index efdb39c..e1465c3 100755 --- a/bash_completion/cekit +++ b/bash_completion/cekit @@ -20,6 +20,7 @@ _cekit_build_options() options+='--build-osbs-user ' options+='--build-osbs-nowait ' options+='--build-osbs-stage ' + options+='--build-osbs-target ' options+='--build-tech-preview ' echo "$options" } @@ -73,6 +74,7 @@ _cekit_complete() options+='--verbose ' options+='--version ' options+='--config ' + options+='--redhat ' COMPREPLY=( $( compgen -W "$options" -- $cur ) ) return diff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py index b61a34c..f4c1372 100644 --- a/cekit/builders/osbs.py +++ b/cekit/builders/osbs.py @@ -18,6 +18,7 @@ class OSBSBuilder(Builder): self._user = params.get('user') self._nowait = params.get('nowait', False) self._release = params.get('release', False) + self._target = params.get('target') self._stage = params.get('stage', False) @@ -119,9 +120,14 @@ class OSBSBuilder(Builder): def build(self): cmd = [self._rhpkg] + if self._user: cmd += ['--user', self._user] cmd.append("container-build") + + if self._target: + cmd += ['--target', self._target] + if self._nowait: cmd += ['--nowait'] diff --git a/cekit/cli.py b/cekit/cli.py index 54646be..55f9dd6 100644 --- a/cekit/cli.py +++ b/cekit/cli.py @@ -104,6 +104,10 @@ class Cekit(object): action='store_true', help='use rhpkg-stage instead of rhpkg') + build_group.add_argument('--build-osbs-target', + dest='build_osbs_target', + help='overrides the default rhpkg target') + build_group.add_argument('--build-tech-preview', action='store_true', help='perform tech preview build') @@ -200,7 +204,8 @@ class Cekit(object): 'release': self.args.build_osbs_release, 'tags': self.args.tags, 'pull': self.args.build_pull, - 'redhat': tools.cfg['common']['redhat'] + 'redhat': tools.cfg['common']['redhat'], + 'target': self.args.build_osbs_target } builder = Builder(self.args.build_engine, diff --git a/cekit/generator/base.py b/cekit/generator/base.py index e55f7dc..b39cb7e 100644 --- a/cekit/generator/base.py +++ b/cekit/generator/base.py @@ -51,6 +51,7 @@ class Generator(object): self.image = Image(descriptor, os.path.dirname(os.path.abspath(descriptor_path))) self.target = target + self._params = params if overrides: self.image = self.override(overrides) diff --git a/docs/build.rst b/docs/build.rst index 8702b58..78d1f6d 100644 --- a/docs/build.rst +++ b/docs/build.rst @@ -25,6 +25,7 @@ You can execute an container image build by running: * ``--build-osbs-stage`` -- use ``rhpkg-stage`` tool instead of ``rhpkg`` * ``--build-osbs-release`` [#f2]_ -- perform a OSBS release build * ``--build-osbs-user`` -- alternative user passed to `rhpkg --user` +* ``--build-osbs-target`` -- overrides the default ``rhpkg`` target * ``--build-osbs-nowait`` -- run `rhpkg container-build` with `--nowait` option specified * ``--build-tech-preview`` [#f2]_ -- updates image descriptor ``name`` key to contain ``-tech-preview`` suffix in family part of the image name
cekit/cekit
da759627a7591993df8eb24778e2dd9ea39ae917
diff --git a/tests/test_builder.py b/tests/test_builder.py index 88ba3ec..b3dd769 100644 --- a/tests/test_builder.py +++ b/tests/test_builder.py @@ -114,6 +114,17 @@ def test_osbs_builder_run_rhpkg_user(mocker): check_call.assert_called_once_with(['rhpkg', '--user', 'Foo', 'container-build', '--scratch']) +def test_osbs_builder_run_rhpkg_target(mocker): + params = {'target': 'Foo', + 'redhat': True} + + check_call = mocker.patch.object(subprocess, 'check_call') + builder = create_osbs_build_object(mocker, 'osbs', params) + builder.build() + + check_call.assert_called_once_with(['rhpkg', 'container-build', '--target', 'Foo', '--scratch']) + + def test_docker_builder_defaults(): params = {'tags': ['foo', 'bar']} builder = Builder('docker', 'tmp', params) diff --git a/tests/test_unit_args.py b/tests/test_unit_args.py index 1e221f1..fdb2042 100644 --- a/tests/test_unit_args.py +++ b/tests/test_unit_args.py @@ -90,6 +90,15 @@ def test_args_config(mocker): assert Cekit().parse().args.config == 'whatever' +def test_args_target(mocker): + mocker.patch.object(sys, 'argv', ['cekit', + 'build', + '--target', + 'foo']) + + assert Cekit().parse().args.target == 'foo' + + def test_args_redhat(mocker): mocker.patch.object(sys, 'argv', ['cekit', '--redhat',
Add support for overriding target in OSBS builder We should be able to override the build target using the `--target` parameter to `rhpkg`.
0.0
da759627a7591993df8eb24778e2dd9ea39ae917
[ "tests/test_builder.py::test_osbs_builder_run_rhpkg_target" ]
[ "tests/test_builder.py::test_osbs_builder_defaults", "tests/test_builder.py::test_osbs_builder_redhat", "tests/test_builder.py::test_osbs_builder_use_rhpkg_staget", "tests/test_builder.py::test_osbs_builder_nowait", "tests/test_builder.py::test_osbs_builder_user", "tests/test_builder.py::test_osbs_builder_run_rhpkg_stage", "tests/test_builder.py::test_osbs_builder_run_rhpkg", "tests/test_builder.py::test_osbs_builder_run_rhpkg_nowait", "tests/test_builder.py::test_osbs_builder_run_rhpkg_user", "tests/test_builder.py::test_docker_builder_run", "tests/test_builder.py::test_buildah_builder_run", "tests/test_builder.py::test_buildah_builder_run_pull", "tests/test_unit_args.py::test_args_command[generate]", "tests/test_unit_args.py::test_args_command[build]", "tests/test_unit_args.py::test_args_command[test]", "tests/test_unit_args.py::test_args_not_valid_command", "tests/test_unit_args.py::test_args_tags[tags0-build_tags0-expected0]", "tests/test_unit_args.py::test_args_tags[tags1-build_tags1-expected1]", "tests/test_unit_args.py::test_args_tags[tags2-build_tags2-expected2]", "tests/test_unit_args.py::test_args_tags[tags3-build_tags3-expected3]", "tests/test_unit_args.py::test_args_build_pull", "tests/test_unit_args.py::test_args_build_engine[osbs]", "tests/test_unit_args.py::test_args_build_engine[docker]", "tests/test_unit_args.py::test_args_build_engine[buildah]", "tests/test_unit_args.py::test_args_osbs_stage", "tests/test_unit_args.py::test_args_osbs_stage_false", "tests/test_unit_args.py::test_args_invalid_build_engine", "tests/test_unit_args.py::test_args_osbs_user", "tests/test_unit_args.py::test_args_config_default", "tests/test_unit_args.py::test_args_config", "tests/test_unit_args.py::test_args_target", "tests/test_unit_args.py::test_args_redhat", "tests/test_unit_args.py::test_args_redhat_default", "tests/test_unit_args.py::test_args_osbs_nowait", "tests/test_unit_args.py::test_args_osbs_no_nowait" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-04 12:31:36+00:00
mit
1,528
cekit__cekit-226
diff --git a/bash_completion/cekit b/bash_completion/cekit index e1465c3..ec29995 100755 --- a/bash_completion/cekit +++ b/bash_completion/cekit @@ -7,6 +7,7 @@ _cekit_global_options() options+='--overrides ' options+='--target ' options+='--descriptor ' + options+='--work-dir ' echo "$options" } @@ -53,6 +54,10 @@ _cekit_complete() _filedir -d return + elif [[ '--work-dir' == $prev ]]; then + _filedir -d + return + elif [[ 'build generate' =~ .*$prev.* ]]; then local options options+=$(_cekit_global_options) diff --git a/cekit/cli.py b/cekit/cli.py index 55f9dd6..922d488 100644 --- a/cekit/cli.py +++ b/cekit/cli.py @@ -54,6 +54,11 @@ class Cekit(object): action='store_true', help='Set default options for Red Hat internal infrasructure.') + parser.add_argument('--work-dir', + dest='work_dir', + help="Location of cekit working directory, it's " + "used to store dist-git repos.") + test_group = parser.add_argument_group('test', "Arguments valid for the 'test' target") @@ -165,6 +170,8 @@ class Cekit(object): if self.args.redhat: tools.cfg['common']['redhat'] = True + if self.args.work_dir: + tools.cfg['common']['work_dir'] = self.args.work_dir # We need to construct Generator first, because we need overrides # merged in diff --git a/docs/build.rst b/docs/build.rst index 78d1f6d..1a466e6 100644 --- a/docs/build.rst +++ b/docs/build.rst @@ -20,6 +20,7 @@ You can execute an container image build by running: * ``--tag`` -- an image tag used to build image (can be specified multiple times) * ``--redhat`` -- build image using Red Hat defaults. See :ref:`Configuration section for Red Hat specific options<redhat_config>` for additional details. +* ``--work-dir`` -- sets Cekit works directory where dist_git repositories are cloned into See :ref:`Configuration section for work_dir<workdir_config>` * ``--build-engine`` -- a builder engine to use ``osbs``, ``buildah`` or ``docker`` [#f1]_ * ``--build-pull`` -- ask a builder engine to check and fetch latest base image * ``--build-osbs-stage`` -- use ``rhpkg-stage`` tool instead of ``rhpkg`` diff --git a/docs/configuration.rst b/docs/configuration.rst index dc1a6ca..645cc78 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -18,12 +18,20 @@ Below you can find description of available sections together with options descr ``common`` ------------ +.. _workdir_config: + ``work_dir`` ^^^^^^^^^^^^ Contains location of Cekit working directory, which is used to store some persistent data like dist_git repositories. +.. code:: yaml + + [common] + work_dir=/tmp + + ``ssl_verify`` ^^^^^^^^^^^^^^
cekit/cekit
7067fb770515c44b28d661fddb5d0f25f706baf3
diff --git a/tests/test_unit_args.py b/tests/test_unit_args.py index fdb2042..6c5a555 100644 --- a/tests/test_unit_args.py +++ b/tests/test_unit_args.py @@ -81,6 +81,15 @@ def test_args_config_default(mocker): assert Cekit().parse().args.config == '~/.cekit/config' +def test_args_workd_dir(mocker): + mocker.patch.object(sys, 'argv', ['cekit', + 'generate', + '--work-dir', + 'foo']) + + assert Cekit().parse().args.work_dir == 'foo' + + def test_args_config(mocker): mocker.patch.object(sys, 'argv', ['cekit', '--config',
Make it possible to specify where dist-git repositories should be cloned It is important so we do not reuse the same directories when running in parallel.
0.0
7067fb770515c44b28d661fddb5d0f25f706baf3
[ "tests/test_unit_args.py::test_args_workd_dir" ]
[ "tests/test_unit_args.py::test_args_command[generate]", "tests/test_unit_args.py::test_args_command[build]", "tests/test_unit_args.py::test_args_command[test]", "tests/test_unit_args.py::test_args_not_valid_command", "tests/test_unit_args.py::test_args_tags[tags0-build_tags0-expected0]", "tests/test_unit_args.py::test_args_tags[tags1-build_tags1-expected1]", "tests/test_unit_args.py::test_args_tags[tags2-build_tags2-expected2]", "tests/test_unit_args.py::test_args_tags[tags3-build_tags3-expected3]", "tests/test_unit_args.py::test_args_build_pull", "tests/test_unit_args.py::test_args_build_engine[osbs]", "tests/test_unit_args.py::test_args_build_engine[docker]", "tests/test_unit_args.py::test_args_build_engine[buildah]", "tests/test_unit_args.py::test_args_osbs_stage", "tests/test_unit_args.py::test_args_osbs_stage_false", "tests/test_unit_args.py::test_args_invalid_build_engine", "tests/test_unit_args.py::test_args_osbs_user", "tests/test_unit_args.py::test_args_config_default", "tests/test_unit_args.py::test_args_config", "tests/test_unit_args.py::test_args_target", "tests/test_unit_args.py::test_args_redhat", "tests/test_unit_args.py::test_args_redhat_default", "tests/test_unit_args.py::test_args_osbs_nowait", "tests/test_unit_args.py::test_args_osbs_no_nowait" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-17 10:40:18+00:00
mit
1,529
cekit__cekit-336
diff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py index 674c81b..7c4e950 100644 --- a/cekit/builders/osbs.py +++ b/cekit/builders/osbs.py @@ -11,6 +11,7 @@ from cekit.config import Config from cekit.builder import Builder from cekit.descriptor.resource import _PlainResource from cekit.errors import CekitError +from cekit.tools import Chdir logger = logging.getLogger('cekit') config = Config() @@ -336,16 +337,3 @@ class DistGit(object): logger.info("Changes are not pushed, exiting") sys.exit(0) - -class Chdir(object): - """ Context manager for changing the current working directory """ - - def __init__(self, newPath): - self.newPath = os.path.expanduser(newPath) - - def __enter__(self): - self.savedPath = os.getcwd() - os.chdir(self.newPath) - - def __exit__(self, etype, value, traceback): - os.chdir(self.savedPath) diff --git a/cekit/tools.py b/cekit/tools.py index 3542e73..cfceefe 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -83,3 +83,16 @@ def get_brew_url(md5): ex.output) raise ex return url + +class Chdir(object): + """ Context manager for changing the current working directory """ + + def __init__(self, newPath): + self.newPath = os.path.expanduser(newPath) + + def __enter__(self): + self.savedPath = os.getcwd() + os.chdir(self.newPath) + + def __exit__(self, etype, value, traceback): + os.chdir(self.savedPath) \ No newline at end of file
cekit/cekit
b5cc9546adb0a4285628f407abf43c0c5f660470
diff --git a/cekit/test/runner.py b/cekit/test/runner.py index 4acc63d..5aa41ed 100644 --- a/cekit/test/runner.py +++ b/cekit/test/runner.py @@ -3,7 +3,7 @@ import getpass import logging import subprocess - +from cekit.tools import Chdir from cekit.errors import CekitError logger = logging.getLogger('cekit') @@ -58,6 +58,8 @@ class TestRunner(object): try: from behave.__main__ import main as behave_main - behave_main(args) + + with Chdir(os.path.join(self.target, 'test')): + behave_main(args) except: raise CekitError("Test execution failed, please consult output above") diff --git a/tests/test_addhelp.py b/tests/test_addhelp.py index 59e133f..eb3a1f6 100644 --- a/tests/test_addhelp.py +++ b/tests/test_addhelp.py @@ -9,7 +9,7 @@ import sys import shutil import yaml import pytest -from cekit.builders.osbs import Chdir +from cekit.tools import Chdir from cekit.cli import Cekit image_descriptor = { diff --git a/tests/test_expose_services.py b/tests/test_expose_services.py index 2873d16..f4c51fa 100644 --- a/tests/test_expose_services.py +++ b/tests/test_expose_services.py @@ -9,7 +9,7 @@ import socket import sys import yaml -from cekit.builders.osbs import Chdir +from cekit.tools import Chdir from cekit.cli import Cekit image_descriptor = { diff --git a/tests/test_validate.py b/tests/test_validate.py index 34528db..a83a44a 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -5,7 +5,7 @@ import sys import yaml import pytest -from cekit.builders.osbs import Chdir +from cekit.tools import Chdir from cekit.errors import CekitError from cekit.cli import Cekit
Test results are no longer output to target directory results and output directories are now collocated with the image.yaml file, where they used to be in target/test
0.0
b5cc9546adb0a4285628f407abf43c0c5f660470
[ "tests/test_addhelp.py::test_addhelp_mutex_cmdline", "tests/test_addhelp.py::test_config_override_help_template", "tests/test_addhelp.py::test_no_override_help_template", "tests/test_addhelp.py::test_image_override_help_template", "tests/test_addhelp.py::test_image_override_config_help_template", "tests/test_addhelp.py::test_confNone_cmdlineNone", "tests/test_addhelp.py::test_confFalse_cmdlineNone", "tests/test_addhelp.py::test_confTrue_cmdlineNone", "tests/test_addhelp.py::test_confNone_cmdlineTrue", "tests/test_addhelp.py::test_confFalse_cmdlineTrue", "tests/test_addhelp.py::test_confTrue_cmdlineTrue", "tests/test_addhelp.py::test_confNone_cmdlineFalse", "tests/test_addhelp.py::test_confFalse_cmdlineFalse", "tests/test_addhelp.py::test_confTrue_cmdlineFalse", "tests/test_expose_services.py::test_expose_services_label_not_generated_wo_redhat", "tests/test_expose_services.py::test_expose_services_label_generated", "tests/test_expose_services.py::test_expose_services_label_no_ports_not_generated", "tests/test_expose_services.py::test_expose_services_label_not_generated_without_expose", "tests/test_expose_services.py::test_expose_services_label_not_overridden", "tests/test_expose_services.py::test_expose_services_generated_default_protocol_tcp", "tests/test_expose_services.py::test_expose_services_generated_specify_protocol", "tests/test_expose_services.py::test_expose_services_not_generated_no_service", "tests/test_expose_services.py::test_expose_services_service_included", "tests/test_validate.py::test_image_generate_with_multiple_overrides", "tests/test_validate.py::test_module_override", "tests/test_validate.py::test_local_module_injection", "tests/test_validate.py::test_local_module_not_injected", "tests/test_validate.py::test_run_override_user", "tests/test_validate.py::test_run_override_artifact", "tests/test_validate.py::test_run_path_artifact_brew", "tests/test_validate.py::test_run_path_artifact_target", "tests/test_validate.py::test_execution_order", "tests/test_validate.py::test_override_modules_child", "tests/test_validate.py::test_override_modules_flat", "tests/test_validate.py::test_execution_order_flat" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-05 13:43:51+00:00
mit
1,530
cekit__cekit-358
diff --git a/cekit/templates/template.jinja b/cekit/templates/template.jinja index 1f8a5c9..1da28a0 100644 --- a/cekit/templates/template.jinja +++ b/cekit/templates/template.jinja @@ -13,12 +13,12 @@ rm{% for repo in repositories %} /etc/yum.repos.d/{{ repo.filename }}{% endfor % {%- endmacro %} {% macro repo_install(pkg_manager, rpm) -%} {% if pkg_manager in ['microdnf', 'yum'] %} -{{ pkg_manager }} install -y {{ rpm }} +{{ pkg_manager }} --setopt=tsflags=nodocs install -y {{ rpm }} {% endif %} {%- endmacro %} {% macro pkg_install(pkg_manager, packages) -%} {% if pkg_manager in ['microdnf', 'yum'] %} -{{ pkg_manager }} install -y {%- for package in packages %} {{ package }}{% endfor %} \ +{{ pkg_manager }} --setopt=tsflags=nodocs install -y {%- for package in packages %} {{ package }}{% endfor %} \ && rpm -q{% for package in packages %} {{ package }}{% endfor %} {% endif %} {%- endmacro %}
cekit/cekit
f3605e7fe1ec74eeb0ee89ce41836448ea75bf13
diff --git a/tests/test_dockerfile.py b/tests/test_dockerfile.py index bb902c4..16b37a8 100644 --- a/tests/test_dockerfile.py +++ b/tests/test_dockerfile.py @@ -17,6 +17,7 @@ basic_config = {'release': 1, config = Config() config.cfg['common'] = {'redhat': True} + def print_test_name(value): if str(value).startswith('test'): return value @@ -86,7 +87,7 @@ odcs_fake_resp = b"""Result: ('test_cekit_label_version', {}, r'.*io.cekit.version="%s".*' % cekit_version)], - ids=print_test_name) + ids=print_test_name) def test_dockerfile_rendering(tmpdir, name, desc_part, exp_regex): target = str(tmpdir.mkdir('target')) @@ -104,7 +105,7 @@ def test_dockerfile_rendering(tmpdir, name, desc_part, exp_regex): {}, r'JBOSS_IMAGE_NAME=\"testimage-tech-preview\"'), ('test_with_family', {'name': 'testimage/test'}, r'JBOSS_IMAGE_NAME=\"testimage-tech-preview/test\"')], - ids=print_test_name) + ids=print_test_name) def test_dockerfile_rendering_tech_preview(tmpdir, name, desc_part, exp_regex): target = str(tmpdir.mkdir('target')) params = {'redhat': True, 'tech_preview': True} @@ -121,7 +122,7 @@ def test_dockerfile_docker_odcs_pulp(tmpdir, mocker): target = str(tmpdir.mkdir('target')) desc_part = {'packages': {'content_sets': { 'x86_64': 'foo'}, - 'install': ['a']}} + 'install': ['a']}} generator = prepare_generator(target, desc_part, 'image') generator.init() @@ -140,7 +141,8 @@ def test_dockerfile_docker_odcs_rpm(tmpdir, mocker): generator = prepare_generator(target, desc_part, 'image') generator.init() generator.generate() - regex_dockerfile(target, 'RUN yum install -y foo-repo.rpm') + regex_dockerfile(target, 'RUN yum --setopt=tsflags=nodocs install -y foo-repo.rpm') + def test_dockerfile_docker_odcs_rpm_microdnf(tmpdir, mocker): mocker.patch.object(subprocess, 'check_output', return_value=odcs_fake_resp) @@ -154,10 +156,11 @@ def test_dockerfile_docker_odcs_rpm_microdnf(tmpdir, mocker): generator = prepare_generator(target, desc_part, 'image', 'docker', [], params) generator.init() generator.generate() - regex_dockerfile(target, 'RUN microdnf install -y foo-repo.rpm') - regex_dockerfile(target, 'RUN microdnf install -y a b') + regex_dockerfile(target, 'RUN microdnf --setopt=tsflags=nodocs install -y foo-repo.rpm') + regex_dockerfile(target, 'RUN microdnf --setopt=tsflags=nodocs install -y a b') regex_dockerfile(target, 'rpm -q a b') + def test_dockerfile_osbs_odcs_pulp(tmpdir, mocker): mocker.patch.object(subprocess, 'check_output', return_value=odcs_fake_resp) mocker.patch.object(Repository, 'fetch') @@ -166,8 +169,8 @@ def test_dockerfile_osbs_odcs_pulp(tmpdir, mocker): target = str(tmpdir.mkdir('target')) os.makedirs(os.path.join(target, 'image')) desc_part = {'packages': {'content_sets': { - 'x86_64': 'foo'}, - 'install': ['a']}} + 'x86_64': 'foo'}, + 'install': ['a']}} generator = prepare_generator(target, desc_part, 'image', 'osbs') generator.init() @@ -187,7 +190,7 @@ def test_dockerfile_osbs_odcs_pulp_no_redhat(tmpdir, mocker): target = str(tmpdir.mkdir('target')) desc_part = {'packages': {'repositories': [{'name': 'foo', 'odcs': { - 'pulp': 'rhel-7-server-rpms' + 'pulp': 'rhel-7-server-rpms' }}, ], 'install': ['a']}} @@ -220,7 +223,7 @@ def test_dockerfile_osbs_url_only(tmpdir, mocker): target = str(tmpdir.mkdir('target')) desc_part = {'packages': {'repositories': [{'name': 'foo', 'url': { - 'repository': 'foo' + 'repository': 'foo' }}, ], 'install': ['a']}} @@ -243,7 +246,7 @@ def test_dockerfile_osbs_odcs_rpm(tmpdir, mocker): generator = prepare_generator(target, desc_part, 'image', 'osbs') generator.init() generator.generate() - regex_dockerfile(target, 'RUN yum install -y foo-repo.rpm') + regex_dockerfile(target, 'RUN yum --setopt=tsflags=nodocs install -y foo-repo.rpm') def test_dockerfile_osbs_odcs_rpm_microdnf(tmpdir, mocker): @@ -258,8 +261,8 @@ def test_dockerfile_osbs_odcs_rpm_microdnf(tmpdir, mocker): generator = prepare_generator(target, desc_part, 'image', 'osbs', [], params) generator.init() generator.generate() - regex_dockerfile(target, 'RUN microdnf install -y foo-repo.rpm') - regex_dockerfile(target, 'RUN microdnf install -y a') + regex_dockerfile(target, 'RUN microdnf --setopt=tsflags=nodocs install -y foo-repo.rpm') + regex_dockerfile(target, 'RUN microdnf --setopt=tsflags=nodocs install -y a') regex_dockerfile(target, 'rpm -q a')
Remove documentation by default When installing packages, in order to reduce the size of the images, they could be installed with the `--setopt=tsflags=nodocs` by default. Suggestion taken from [Container Best Practices](http://docs.projectatomic.io/container-best-practices/#_removing_documentation) E.g. ``` packages: repositories: - name: base id: rhel-7-server-rpms install: - java-1.8.0-openjdk ``` Would lead to ``` RUN yum install -y --setopt=tsflags=nodocs java-1.8.0-openjdk \ && yum clean all && rm -rf /var/cache/yum && \ rpm -q java-1.8.0-openjdk ```
0.0
f3605e7fe1ec74eeb0ee89ce41836448ea75bf13
[ "tests/test_dockerfile.py::test_dockerfile_docker_odcs_rpm", "tests/test_dockerfile.py::test_dockerfile_docker_odcs_rpm_microdnf", "tests/test_dockerfile.py::test_dockerfile_osbs_odcs_rpm", "tests/test_dockerfile.py::test_dockerfile_osbs_odcs_rpm_microdnf" ]
[ "tests/test_dockerfile.py::test_dockerfile_rendering[test_run_user-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_default_run_user-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_custom_cmd-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_entrypoint-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_workdir-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_volumes-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_ports-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_env-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_execute-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_execute_user-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_concrt_label_version-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering[test_cekit_label_version-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering_tech_preview[test_without_family-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_rendering_tech_preview[test_with_family-\\x08-\\x08]", "tests/test_dockerfile.py::test_dockerfile_docker_odcs_pulp", "tests/test_dockerfile.py::test_dockerfile_osbs_odcs_pulp", "tests/test_dockerfile.py::test_dockerfile_osbs_odcs_pulp_no_redhat", "tests/test_dockerfile.py::test_dockerfile_osbs_id_redhat_false", "tests/test_dockerfile.py::test_dockerfile_osbs_url_only" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-01-17 14:04:39+00:00
mit
1,531
cekit__cekit-373
diff --git a/cekit/template_helper.py b/cekit/template_helper.py index 9e61cd0..d0eccc9 100644 --- a/cekit/template_helper.py +++ b/cekit/template_helper.py @@ -10,6 +10,25 @@ class TemplateHelper(object): def module(self, to_install): return self._module_registry.get_module(to_install.name, to_install.version) + def packages_to_install(self, image): + """ + Method that returns list of packages to be installed by any of + modules or directly in the image + """ + all_modules = [] + packages = [] + + if 'modules' in image and 'install' in image.modules: + all_modules += [self.module(m) for m in image.modules.install] + + all_modules.append(image) + + for module in all_modules: + if 'packages' in module and 'install' in module.packages: + packages += module.packages.install + + return packages + def filename(self, source): """Simple helper to return the file specified name""" diff --git a/cekit/templates/template.jinja b/cekit/templates/template.jinja index 1da28a0..dd5870f 100644 --- a/cekit/templates/template.jinja +++ b/cekit/templates/template.jinja @@ -22,11 +22,65 @@ rm{% for repo in repositories %} /etc/yum.repos.d/{{ repo.filename }}{% endfor % && rpm -q{% for package in packages %} {{ package }}{% endfor %} {% endif %} {%- endmacro %} +{% macro repo_make_cache(pkg_manager) -%} + {% if pkg_manager in ['microdnf', 'yum'] %} +{{ pkg_manager }} makecache + {% endif %} +{%- endmacro %} {% macro repo_clear_cache(pkg_manager) -%} {% if pkg_manager in ['microdnf', 'yum'] %} {{ pkg_manager }} clean all && [ ! -d /var/cache/yum ] || rm -rf /var/cache/yum {% endif %} {%- endmacro %} +{% macro process_module(module) %} +# begin {{ module.name }}:{{ module.version }} +{% if module.packages and module.packages.install %} + +# Install required RPMs and ensure that the packages were installed +USER root +RUN {{ pkg_install(pkg_manager, module.packages.install) }} +{% endif %} +{% if helper.envs(module.envs)|length > 0 %} + +# Environment variables +ENV \ + {% for env in helper.envs(module.envs)|sort(attribute='name') %} + {{ env.name }}="{{ env.value }}" {% if loop.index < loop.length %}\{% endif %} + + {% endfor %} +{% endif %} +{% if module.labels|length > 0 %} + +# Labels +LABEL \ + {% for label in module.labels|sort(attribute='name') %} + {{ label.name }}="{{ label.value }}" {% if loop.index < loop.length %} \{% endif %} + + {% endfor %} +{% endif %} +{% if helper.ports(module.ports)|length > 0 %} + +# Exposed ports +EXPOSE {%- for port in helper.ports(module.ports) %} {{ port }}{% endfor %} +{% endif %} +{%- if module.execute|length > 0 %} + +# Custom scripts +{% for exec in module.execute %} +USER {{ exec.user }} +RUN [ "bash", "-x", "/tmp/scripts/{{ exec.directory }}/{{ exec.script }}" ] +{% endfor %} +{% endif %} +{%- if module.volumes|length > 0 %} + +# Volumes +{% for volume in module.volumes %} +VOLUME ["{{ volume['path'] }}"] +{% endfor %} +{% endif %} + +# end {{ module.name }}:{{ module.version }} +{%- endmacro %} # Copyright 2017 Red Hat # @@ -62,9 +116,9 @@ RUN {{ repo_install(pkg_manager, repo.rpm) }} {% endif %} {% endfor %} {% endif %} -{% if packages.repositories_injected or packages.repositories %} -RUN yum makecache +{% if helper.packages_to_install(image) %} +RUN {{ repo_make_cache(pkg_manager) }} {% endif %} # Add scripts used to configure the image @@ -78,55 +132,7 @@ COPY \ {% endfor %} /tmp/artifacts/ {% endif %} -{% macro process_module(module) %} -# begin {{ module.name }}:{{ module.version }} -{% if module.packages and module.packages.install %} - -# Install required RPMs and ensure that the packages were installed -USER root -RUN {{ pkg_install(pkg_manager, module.packages.install) }} -{% endif %} -{% if helper.envs(module.envs)|length > 0 %} - -# Environment variables -ENV \ - {% for env in helper.envs(module.envs)|sort(attribute='name') %} - {{ env.name }}="{{ env.value }}" {% if loop.index < loop.length %}\{% endif %} - - {% endfor %} -{% endif %} -{% if module.labels|length > 0 %} - -# Labels -LABEL \ - {% for label in module.labels|sort(attribute='name') %} - {{ label.name }}="{{ label.value }}" {% if loop.index < loop.length %} \{% endif %} - - {% endfor %} -{% endif %} -{% if helper.ports(module.ports)|length > 0 %} - -# Exposed ports -EXPOSE {%- for port in helper.ports(module.ports) %} {{ port }}{% endfor %} -{% endif %} -{%- if module.execute|length > 0 %} - -# Custom scripts -{% for exec in module.execute %} -USER {{ exec.user }} -RUN [ "bash", "-x", "/tmp/scripts/{{ exec.directory }}/{{ exec.script }}" ] -{% endfor %} -{% endif %} -{%- if module.volumes|length > 0 %} - -# Volumes -{% for volume in module.volumes %} -VOLUME ["{{ volume['path'] }}"] -{% endfor %} -{% endif %} -# end {{ module.name }}:{{ module.version }} -{% endmacro %} {% for to_install in image.modules.install %} {{ process_module(helper.module(to_install)) }} {% endfor %} @@ -135,16 +141,18 @@ VOLUME ["{{ volume['path'] }}"] USER root RUN [ ! -d /tmp/scripts ] || rm -rf /tmp/scripts RUN [ ! -d /tmp/artifacts ] || rm -rf /tmp/artifacts -{% if packages.repositories_injected or packages.repositories %} + +{% if helper.packages_to_install(image) %} +# Clear package manager metadata RUN {{ repo_clear_cache(pkg_manager) }} -{% if packages.repositories_injected %} +{% endif %} +{% if packages.repositories_injected %} # Remove custom repo files RUN {{ repo_remove(pkg_manager, packages.repositories_injected) }} {% endif %} -{% endif %} -# run user +# Run user USER {{ run['user'] }} {% if 'workdir' in run %}
cekit/cekit
92f0cc5494eb43e939a4cc6060cb705ffb550772
diff --git a/tests/modules/repo_packages/packages_module/module.yaml b/tests/modules/repo_packages/packages_module/module.yaml new file mode 100644 index 0000000..2bc0502 --- /dev/null +++ b/tests/modules/repo_packages/packages_module/module.yaml @@ -0,0 +1,6 @@ +schema_version: 1 +name: packages_module +packages: + install: + - kernel + - java \ No newline at end of file diff --git a/tests/modules/repo_packages/packages_module_1/module.yaml b/tests/modules/repo_packages/packages_module_1/module.yaml new file mode 100644 index 0000000..7739e5b --- /dev/null +++ b/tests/modules/repo_packages/packages_module_1/module.yaml @@ -0,0 +1,6 @@ +schema_version: 1 +name: packages_module_1 +packages: + install: + - wget + - mc \ No newline at end of file diff --git a/tests/test_validate.py b/tests/test_validate.py index 1a03a4c..5ba28b5 100644 --- a/tests/test_validate.py +++ b/tests/test_validate.py @@ -614,7 +614,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child_of_child/script_d" ] # end child_of_child:None - # begin child2_of_child:None # Custom scripts @@ -622,7 +621,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child2_of_child/scripti_e" ] # end child2_of_child:None - # begin child3_of_child:None # Custom scripts @@ -630,7 +628,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child3_of_child/script_f" ] # end child3_of_child:None - # begin child:None # Environment variables @@ -642,7 +639,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child/script_b" ] # end child:None - # begin child_2:None # Custom scripts @@ -650,7 +646,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child_2/script_c" ] # end child_2:None - # begin child_of_child3:None # Custom scripts @@ -658,7 +653,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child_of_child3/script_g" ] # end child_of_child3:None - # begin child2_of_child3:None # Custom scripts @@ -666,11 +660,9 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/child2_of_child3/script_h" ] # end child2_of_child3:None - # begin child_3:None # end child_3:None - # begin master:None # Environment variables @@ -726,8 +718,10 @@ def test_override_modules_flat(tmpdir, mocker): yaml.dump(img_desc, fd, default_flow_style=False) run_cekit(image_dir) + assert check_dockerfile_text(image_dir, 'foo="mod_2"') - + assert not check_dockerfile_text(image_dir, "RUN yum makecache") + assert not check_dockerfile_text(image_dir, "RUN yum clean all") def test_execution_order_flat(tmpdir, mocker): mocker.patch.object(sys, 'argv', ['cekit', @@ -766,7 +760,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/mod_1/c" ] # end mod_1:None - # begin mod_2:None # Environment variables @@ -782,7 +775,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/mod_2/c" ] # end mod_2:None - # begin mod_3:None # Custom scripts @@ -794,7 +786,6 @@ USER root RUN [ "bash", "-x", "/tmp/scripts/mod_3/c" ] # end mod_3:None - # begin mod_4:None # Custom scripts @@ -808,7 +799,75 @@ RUN [ "bash", "-x", "/tmp/scripts/mod_4/c" ] # end mod_4:None """ assert check_dockerfile_text(image_dir, expected_modules_order) + assert not check_dockerfile_text(image_dir, "RUN yum makecache") + assert not check_dockerfile_text(image_dir, "RUN yum clean all") + +def test_package_related_commands_packages_in_module(tmpdir, mocker): + mocker.patch.object(sys, 'argv', ['cekit', + '-v', + 'generate']) + + image_dir = str(tmpdir.mkdir('source')) + copy_repos(image_dir) + + img_desc = image_descriptor.copy() + img_desc['modules']['install'] = [{'name': 'packages_module'}, {'name': 'packages_module_1'}] + img_desc['modules']['repositories'] = [{'name': 'modules', + 'path': 'tests/modules/repo_packages'}] + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(img_desc, fd, default_flow_style=False) + + run_cekit(image_dir) + + expected_packages_order_install = """ +# begin packages_module:None + +# Install required RPMs and ensure that the packages were installed +USER root +RUN yum --setopt=tsflags=nodocs install -y kernel java \\ + && rpm -q kernel java + +# end packages_module:None +# begin packages_module_1:None + +# Install required RPMs and ensure that the packages were installed +USER root +RUN yum --setopt=tsflags=nodocs install -y wget mc \\ + && rpm -q wget mc + +# end packages_module_1:None +""" + + assert check_dockerfile_text(image_dir, "RUN yum makecache") + assert check_dockerfile_text(image_dir, expected_packages_order_install) + assert check_dockerfile_text(image_dir, "RUN yum clean all && [ ! -d /var/cache/yum ] || rm -rf /var/cache/yum") + +def test_package_related_commands_packages_in_image(tmpdir, mocker): + mocker.patch.object(sys, 'argv', ['cekit', + '-v', + 'generate']) + + image_dir = str(tmpdir.mkdir('source')) + copy_repos(image_dir) + + img_desc = image_descriptor.copy() + img_desc['packages'] = {'install': ['wget', 'mc']} + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(img_desc, fd, default_flow_style=False) + + run_cekit(image_dir) + + expected_packages_install = """ +# Install required RPMs and ensure that the packages were installed +USER root +RUN yum --setopt=tsflags=nodocs install -y wget mc \\ + && rpm -q wget mc +""" + assert check_dockerfile_text(image_dir, "RUN yum makecache") + assert check_dockerfile_text(image_dir, expected_packages_install) def test_nonexisting_image_descriptor(mocker, tmpdir, caplog): mocker.patch.object(sys, 'argv', ['cekit',
Make sure we execute cleanup after installing any packages We need to ensure that YUM/DNF cleanup is executed when we install any packages. Related to #83 and probably to #343 too.
0.0
92f0cc5494eb43e939a4cc6060cb705ffb550772
[ "tests/test_validate.py::test_execution_order", "tests/test_validate.py::test_execution_order_flat", "tests/test_validate.py::test_package_related_commands_packages_in_module", "tests/test_validate.py::test_package_related_commands_packages_in_image" ]
[ "tests/test_validate.py::test_content_sets_file_container_file", "tests/test_validate.py::test_content_sets_file_container_embedded", "tests/test_validate.py::test_content_sets_embedded_container_embedded", "tests/test_validate.py::test_content_sets_embedded_container_file", "tests/test_validate.py::test_image_generate_with_multiple_overrides", "tests/test_validate.py::test_module_override", "tests/test_validate.py::test_local_module_injection", "tests/test_validate.py::test_local_module_not_injected", "tests/test_validate.py::test_run_override_user", "tests/test_validate.py::test_run_override_artifact", "tests/test_validate.py::test_run_path_artifact_brew", "tests/test_validate.py::test_run_path_artifact_target", "tests/test_validate.py::test_override_modules_child", "tests/test_validate.py::test_override_modules_flat", "tests/test_validate.py::test_nonexisting_image_descriptor", "tests/test_validate.py::test_nonexisting_override_file", "tests/test_validate.py::test_incorrect_override_file" ]
{ "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-01-25 12:53:38+00:00
mit
1,532
cekit__cekit-417
diff --git a/cekit/tools.py b/cekit/tools.py index e5f8e52..624434a 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -83,6 +83,20 @@ def get_brew_url(md5): get_build_cmd = ['brew', 'call', '--json-output', 'getBuild', 'buildInfo=%s' % build_id] logger.debug("Executing '%s'" % " ".join(get_build_cmd)) build = yaml.safe_load(subprocess.check_output(get_build_cmd)) + + build_states = ['BUILDING', 'COMPLETE', 'DELETED', 'FAILED', 'CANCELED'] + + # State 1 means: COMPLETE which is the only success state. Other states are: + # + # 'BUILDING': 0 + # 'COMPLETE': 1 + # 'DELETED': 2 + # 'FAILED': 3 + # 'CANCELED': 4 + if build['state'] != 1: + raise CekitError( + "Artifact with checksum {} was found in Koji metadata but the build is in incorrect state ({}) making the artifact not available for downloading anymore".format(md5, build_states[build['state']])) + package = build['package_name'] release = build['release']
cekit/cekit
93fc5628cbbf65bc31c40e0a6a42f0f2ff1ee2bf
diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index 4ea9fdb..421b7e9 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -139,7 +139,7 @@ def test_merge_run_cmd(): assert override['user'] == 'foo' -def brew_call(*args, **kwargs): +def brew_call_ok(*args, **kwargs): if 'listArchives' in args[0]: return """ [ @@ -155,19 +155,53 @@ def brew_call(*args, **kwargs): return """ { "package_name": "package_name", - "release": "release" + "release": "release", + "state": 1 + } + """ + return "" + + +def brew_call_removed(*args, **kwargs): + if 'listArchives' in args[0]: + return """ + [ + { + "build_id": "build_id", + "filename": "filename", + "group_id": "group_id", + "artifact_id": "artifact_id", + "version": "version", + } + ]""" + if 'getBuild' in args[0]: + return """ + { + "package_name": "package_name", + "release": "release", + "state": 2 } """ return "" def test_get_brew_url(mocker): - mocker.patch('subprocess.check_output', side_effect=brew_call) + mocker.patch('subprocess.check_output', side_effect=brew_call_ok) url = tools.get_brew_url('aa') assert url == "http://download.devel.redhat.com/brewroot/packages/package_name/" + \ "version/release/maven/group_id/artifact_id/version/filename" +def test_get_brew_url_when_build_was_removed(mocker): + mocker.patch('subprocess.check_output', side_effect=brew_call_removed) + + with pytest.raises(CekitError) as excinfo: + tools.get_brew_url('aa') + + assert 'Artifact with checksum aa was found in Koji metadata but the build is in incorrect state (DELETED) making the artifact not available for downloading anymore' in str( + excinfo.value) + + @contextmanager def mocked_dependency_handler(mocker, data="ID=fedora\nNAME=somefedora\nVERSION=123"): dh = None
Handle deleted artifacts in koji When an artifact is deleted we should not try to fetch it. Instead the build should be terminated.
0.0
93fc5628cbbf65bc31c40e0a6a42f0f2ff1ee2bf
[ "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed" ]
[ "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-03-04 11:03:39+00:00
mit
1,533
cekit__cekit-429
diff --git a/cekit/descriptor/resource.py b/cekit/descriptor/resource.py index b506057..2917776 100644 --- a/cekit/descriptor/resource.py +++ b/cekit/descriptor/resource.py @@ -156,16 +156,19 @@ class Resource(Descriptor): def __substitute_cache_url(self, url): cache = config.get('common', 'cache_url') + if not cache: return url for algorithm in SUPPORTED_HASH_ALGORITHMS: if algorithm in self: - logger.debug("Using %s to fetch artifacts from cacher." - % algorithm) - return (cache.replace('#filename#', self.name) - .replace('#algorithm#', algorithm) - .replace('#hash#', self[algorithm])) + logger.debug("Using {} checksum to fetch artifacts from cacher".format(algorithm)) + + url = cache.replace('#filename#', self.name).replace( + '#algorithm#', algorithm).replace('#hash#', self[algorithm]) + + logger.debug("Using cache url '{}'".format(url)) + return url def _download_file(self, url, destination, use_cache=True): @@ -312,26 +315,30 @@ class _PlainResource(Resource): self.target = self.target_file_name() def _copy_impl(self, target): - + # First of all try to download the file using cacher if specified if config.get('common', 'cache_url'): - logger.debug("Trying to download artifact %s from remote cache" % self.name) - # If cacher URL is set, use it try: - self._download_file(self.url, target) + self._download_file(None, target) return target - except: - logger.warning("Could not download artifact %s from the remote cache" % self.name) + except Exception as e: + logger.debug(str(e)) + logger.warning("Could not download '{}' artifact using cacher".format(self.name)) md5 = self.get('md5') + # Next option is to download it from Brew directly but only if the md5 checkum + # is provided and we are running with the --redhat switch if md5 and config.get('common', 'redhat'): - logger.debug("Trying to download artifact %s from Brew directly" % self.name) + logger.debug("Trying to download artifact '{}' from Brew directly".format(self.name)) try: - self.url = get_brew_url(md5) - self._download_file(self.url, target, use_cache=False) + # Generate the URL + url = get_brew_url(md5) + # Use the URL to download the file + self._download_file(url, target, use_cache=False) return target - except: - logger.warning("Could not download artifact %s from Brew" % self.name) + except Exception as e: + logger.debug(str(e)) + logger.warning("Could not download artifact '{}' from Brew".format(self.name)) - raise CekitError("Artifact %s could not be found" % self.name) + raise CekitError("Artifact {} could not be found".format(self.name))
cekit/cekit
e966acf8d03e6252aa5d866bc70f147588e0005a
diff --git a/tests/test_unit_resource.py b/tests/test_unit_resource.py index b140573..feba92b 100644 --- a/tests/test_unit_resource.py +++ b/tests/test_unit_resource.py @@ -70,6 +70,7 @@ def test_fetching_with_ssl_verify(mocker): mock_urlopen = get_mock_urlopen(mocker) res = Resource({'name': 'file', 'url': 'https:///dummy'}) + try: res.copy() except: @@ -88,6 +89,7 @@ def test_fetching_disable_ssl_verify(mocker): get_mock_ssl(mocker, ctx) res = Resource({'name': 'file', 'url': 'https:///dummy'}) + try: res.copy() except: @@ -153,7 +155,9 @@ def test_fetching_file_exists_no_hash_fetched_again(mocker): with open('file', 'w') as f: # noqa: F841 pass + res = Resource({'name': 'file', 'url': 'http:///dummy'}) + with pytest.raises(CekitError): # url is not valid so we get error, but we are not interested # in it. We just need to check that we attempted to downlad. @@ -253,6 +257,63 @@ def test_url_resource_download_cleanup_after_failure(mocker, tmpdir, caplog): os_remove_mock.assert_called_with(targetfile) +def test_copy_plain_resource_with_cacher(mocker, tmpdir): + config.cfg['common']['cache_url'] = '#filename#,#algorithm#,#hash#' + config.cfg['common']['work_dir'] = str(tmpdir) + + urlopen_class_mock = mocker.patch('cekit.descriptor.resource.urlopen') + mock_urlopen = urlopen_class_mock.return_value + mock_urlopen.getcode.return_value = 200 + mock_urlopen.read.side_effect = [b"one", b"two", None] + + ctx = get_ctx(mocker) + get_mock_ssl(mocker, ctx) + + with open('file', 'w') as f: # noqa: F841 + pass + + res = Resource({'name': 'foo', + 'md5': '5b9164ad6f496d9dee12ec7634ce253f'}) + + substitute_cache_url_mock = mocker.patch.object( + res, '_Resource__substitute_cache_url', return_value='http://cache/abc') + + res.copy(str(tmpdir)) + + substitute_cache_url_mock.assert_called_once_with(None) + urlopen_class_mock.assert_called_with('http://cache/abc', context=ctx) + + +def test_copy_plain_resource_from_brew(mocker, tmpdir): + config.cfg['common']['work_dir'] = str(tmpdir) + config.cfg['common']['redhat'] = True + + urlopen_class_mock = mocker.patch('cekit.descriptor.resource.urlopen') + mock_urlopen = urlopen_class_mock.return_value + mock_urlopen.getcode.return_value = 200 + mock_urlopen.read.side_effect = [b"one", b"two", None] + + ctx = get_ctx(mocker) + get_mock_ssl(mocker, ctx) + + with open('file', 'w') as f: # noqa: F841 + pass + + res = Resource({'name': 'foo', + 'md5': '5b9164ad6f496d9dee12ec7634ce253f'}) + + mocker.spy(res, '_Resource__substitute_cache_url') + + mock_get_brew_url = mocker.patch( + 'cekit.descriptor.resource.get_brew_url', return_value='http://cache/abc') + + res.copy(str(tmpdir)) + + mock_get_brew_url.assert_called_once_with('5b9164ad6f496d9dee12ec7634ce253f') + res._Resource__substitute_cache_url.call_count == 0 + urlopen_class_mock.assert_called_with('http://cache/abc', context=ctx) + + def test_overide_resource_remove_chksum(): image = Image(yaml.safe_load(""" from: foo
Plain artifacts and cache_url does not work well together ``` 2019-02-20 19:56:43,514 cekit INFO Preparing resource 'hawkular-javaagent' 2019-02-20 19:56:43,540 cekit DEBUG Trying to download artifact hawkular-javaagent from remote cache Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/cekit/descriptor/resource.py", line 309, in _copy_impl self._download_file(self.url, target) AttributeError: '_PlainResource' object has no attribute 'url' ```
0.0
e966acf8d03e6252aa5d866bc70f147588e0005a
[ "tests/test_unit_resource.py::test_copy_plain_resource_with_cacher" ]
[ "tests/test_unit_resource.py::test_repository_dir_is_constructed_properly", "tests/test_unit_resource.py::test_git_clone", "tests/test_unit_resource.py::test_fetching_with_ssl_verify", "tests/test_unit_resource.py::test_fetching_disable_ssl_verify", "tests/test_unit_resource.py::test_fetching_bad_status_code", "tests/test_unit_resource.py::test_fetching_file_exists_but_used_as_is", "tests/test_unit_resource.py::test_fetching_file_exists_fetched_again", "tests/test_unit_resource.py::test_fetching_file_exists_no_hash_fetched_again", "tests/test_unit_resource.py::test_generated_url_without_cacher", "tests/test_unit_resource.py::test_resource_verify", "tests/test_unit_resource.py::test_generated_url_with_cacher", "tests/test_unit_resource.py::test_path_resource_absolute", "tests/test_unit_resource.py::test_path_resource_relative", "tests/test_unit_resource.py::test_path_local_existing_resource_no_cacher_use", "tests/test_unit_resource.py::test_path_local_non_existing_resource_with_cacher_use", "tests/test_unit_resource.py::test_url_resource_download_cleanup_after_failure", "tests/test_unit_resource.py::test_copy_plain_resource_from_brew", "tests/test_unit_resource.py::test_overide_resource_remove_chksum" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-03-11 15:05:19+00:00
mit
1,534
cekit__cekit-446
diff --git a/cekit/cli.py b/cekit/cli.py index 6de2472..5fd8f2f 100644 --- a/cekit/cli.py +++ b/cekit/cli.py @@ -258,7 +258,7 @@ def run_command(ctx, clazz): def run_test(ctx, tester): if tester == 'behave': - from cekit.test.behave import BehaveTester as tester_impl + from cekit.test.behave_tester import BehaveTester as tester_impl LOGGER.info("Using Behave tester to test the image") else: raise CekitError("Tester engine {} is not supported".format(tester)) @@ -287,7 +287,7 @@ def run_build(ctx, builder): run_command(ctx, builder_impl) -class Cekit(object): # pylint: disable=useless-object-inheritance +class Cekit(object): """ Main application """ def __init__(self, params): diff --git a/docs/conf.py b/docs/conf.py index 84e7e0c..d960cef 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,6 +19,7 @@ def setup(app): extensions = ['sphinx.ext.autosectionlabel', 'sphinx.ext.todo'] # http://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html#confval-autosectionlabel_prefix_document autosectionlabel_prefix_document = True +autosectionlabel_maxdepth = 4 # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/docs/descriptor/artifacts.rst b/docs/descriptor/artifacts.rst index 4f84646..6b3ac87 100644 --- a/docs/descriptor/artifacts.rst +++ b/docs/descriptor/artifacts.rst @@ -2,24 +2,95 @@ Artifacts --------- It's common for images to require external artifacts like jar files, installers, etc. -In most cases you will want to add files into the image and use them during image build process. +In most cases you will want to add some files into the image and use them during image build process. -Artifacts section is meant exactly for this. *CEKit will automatically -fetch any artifacts* specified in this section and check their consistency by computing checksum of -the downloaded file and comparing it with the desired value. Currently supported algorithms are: md5, sha1 and sha256. If no algorithm is provided, artifact will be fetched **every** time. +Artifacts section is meant exactly for this. CEKit will *automatically* +fetch any artifacts specified in this section. -All artifacts are automatically cached during an image build. To learn more about cache please take a look at :ref:`artifacts_caching` +If for some reason automatic fetching of artifacts is not an option for you, +yoy should define artifacts as plain artifacts and use the ``cekit-cache`` +command to add the artifact to local cache, making it available for the build +process automatically. See :doc:`/caching` chapter. +Artifact features +^^^^^^^^^^^^^^^^^^^^ + +Checksums + All artifacts will be checked for consistency by computing checksum of + the downloaded file and comparing it with the desired value. Currently supported algorithms + are: ``md5``, ``sha1`` and ``sha256``. + + You can define multiple checksums for a single artifact. All specfied checksums will + be validated. + + If no algorithm is provided, artifacts will be fetched **every time**. + + This can be useful when building images with snapshot content. In this case you are not + concerned about the consistency but rather focusing on rapid + development. We advice that you define checksum when your content becomes stable. + +Caching + All artifacts are automatically cached during an image build. To learn more about caching please take a look at :doc:`/caching` chapter. + + +Common artifact keys +^^^^^^^^^^^^^^^^^^^^ + +``name`` + Used to define unique identifier of the artifact. + + The ``name`` key is very important. It's role is to provide a unique identifier for the artifact. + If it's not provided, it will be computed from the resource definition, but we **strongly suggest** + to provide the ``name`` keys always. + + Value of this key does not need to be a filename, because it's just an identifier used + to refer the artifact. Using meaningful and unique identifiers is important in case when + you want to use :doc:`/overrides`. It will make it much easier to refer the artifact + and thus override it. + +``target`` + The output name for fetched resources will match the ``target`` attribute. If it is not defined + then base name of the ``name`` attribute will be used. If it's not provided either then base name + of the path/URL will be used. + + Below you can find a few examples. + + .. code-block:: yaml -The output name for downloaded resources will match the ``target`` attribute, which defaults to -the base name of the file/URL. + artifacts: + - name: jboss-eap-distribution + path: jboss-eap-6.4.0.zip + target: jboss-eap.zip + Target file name: ``jboss-eap.zip``. + .. code-block:: yaml -.. note:: + artifacts: + - name: jboss-eap-distribution + path: jboss-eap-6.4.0.zip - For artifacts that are not publicly available CEKit provides a way to - add a description detailing a location from which the artifact can be obtained. + Target file name: ``jboss-eap-distribution``. + + .. code-block:: yaml + + artifacts: + - path: jboss-eap-6.4.0.zip + + Target file name: ``jboss-eap-6.4.0.zip``. + +``md5``, ``sha1``, ``sha256`` + Checksum algorithms. These keys can be provided to make sure the fetched artifact + is valid. + + See section above about checksums. + +``description`` + Describes the artifact. This is an optional key that can be used to add more information + about the artifact. + + Adding description to artifacts makes it much easier to understand what artifact + it is just by looking at the image/module descriptor. .. code-block:: yaml @@ -30,17 +101,27 @@ the base name of the file/URL. If CEKit is not able to download an artifact and this artifact has a ``description`` defined -- the build will fail but a message with the description will be printed together with information on where to place - the manually downloaded artifact. + the manually downloaded artifact so that the build could be resumed. +Artifact types +^^^^^^^^^^^^^^^^^^^^ + +CEKit supports following artifact types: +* Plain artifacts +* URL artifacts +* Path artifacts Plain artifacts -^^^^^^^^^^^^^^^^^^^^ +****************** + +This is an abstract way of defining artifacts. The only required keys are ``name`` and checksum. +This type of artifacts is used to define artifacts that are not available publicly and instead +provided by some (internal) systems. -This is the easiest way of defining an artifact. You are just specifying its name and **md5** checksum. -This approach relies on :ref:`artifacts_caching` to provide the artifact in cache. This section should be used to show that a particular artifact is needed for the image but its not publicly available. +This approach relies on :doc:`/caching` to provide the artifact. -.. code:: yaml +.. code-block:: yaml artifacts: - name: jolokia-1.3.6-bin.tar.gz @@ -49,15 +130,18 @@ This approach relies on :ref:`artifacts_caching` to provide the artifact in cach .. note:: - See :ref:`Red Hat Environment<redhat_env>` for a description how Plain Artifacts are affected by Red - Hat switch. + See :doc:`/redhat` for description how plain artifacts are used in the + Red Hat environment. URL artifacts -^^^^^^^^^^^^^^^^^^ +****************** -This way of defining repository ask CEKit to download and artifact from a specified URL. +This is the simplest way of defining artifacts. You need to provide the ``url`` key which is the URL from where the +artifact should be fetched from. +.. tip:: + You should always specify checksums to make sure the downloaded artifact is correct. .. code-block:: yaml @@ -66,14 +150,11 @@ This way of defining repository ask CEKit to download and artifact from a specif url: https://github.com/rhuss/jolokia/releases/download/v1.3.6/jolokia-1.3.6-bin.tar.gz md5: 75e5b5ba0b804cd9def9f20a70af649f - - - Path artifacts -^^^^^^^^^^^^^^^^^^^ +****************** -This way of defining artifact is mostly used in development overrides and enables you to inject -an artifact from a local filesystem. +This way of defining artifacts is mostly used in development :doc:`overrides</overrides>` and enables you to inject +artifacts from a local filesystem. .. code-block:: yaml @@ -84,11 +165,12 @@ an artifact from a local filesystem. .. note:: - If you are using relative ``path`` to define an artifact, path is considered relative to an - image descriptor which introduced that artifact. + If you are using relative ``path`` to define an artifact, path is considered relative to an + image descriptor which introduced that artifact. - **Example**: If an artifact is defined inside */foo/bar/image.yaml* with a path: *baz/1.zip* - the artifact will be resolved as */foo/bar/baz/1.zip* + Example + If an artifact is defined inside ``/foo/bar/image.yaml`` with a path: ``baz/1.zip`` + the artifact will be resolved as ``/foo/bar/baz/1.zip`` diff --git a/docs/descriptor/image.rst b/docs/descriptor/image.rst index 91cfc48..64876c7 100644 --- a/docs/descriptor/image.rst +++ b/docs/descriptor/image.rst @@ -3,6 +3,7 @@ Image descriptor Image descriptor contains all information CEKit needs to build and test a container image. .. contents:: + :backlinks: none .. include:: name.rst .. include:: version.rst diff --git a/docs/installation/instructions.rst b/docs/installation/instructions.rst index eb69a06..93748d1 100644 --- a/docs/installation/instructions.rst +++ b/docs/installation/instructions.rst @@ -3,48 +3,53 @@ Installation instructions .. contents:: -We provide RPM packages for Fedora, CentOS, RHEL distribution. -CEKit installation on other platforms is still possible via ``pip`` +We provide RPM packages for Fedora, CentOS/RHEL distribution. +CEKit installation on other platforms is still possible via ``pip``. -On RHEL derivatives we strongly suggest installing CEKit using the YUM/DNF package -manager. We provide a `COPR repository for CEKit <https://copr.fedorainfracloud.org/coprs/g/cekit/cekit/>`_ -which contains everything needed to install CEKit. +RPM packages are distributed via regular repositories in case of Fedora +and the EPEL repository for CentOS/RHEL. .. warning:: + Currently packaged version is a snapshot release of the upcoming CEKit 3.0. - Make sure you read the :doc:`dependencies chapter</installation/dependencies>` of this documentation which contains important +.. tip:: + You can see latest submitted package updates `submitted in Bodhi <https://bodhi.fedoraproject.org/updates/?packages=cekit>`_. + +.. warning:: + + Make sure you read the :doc:`dependencies </installation/dependencies>` chapter which contains important information about how CEKit dependencies are handled! Fedora ------------------- -Supported versions: 27+. +.. note:: + Supported versions: 29+. -For Fedora we provide a custom Copr repository. To `enable the "cekit" repository <https://docs.pagure.org/copr.copr/how_to_enable_repo.html>`_ and install CEKit on your system, please run: +CEKit is available from regular Fedora repositories. .. code-block:: bash - dnf install dnf-plugins-core - dnf copr enable @cekit/cekit - dnf install python3-cekit + dnf install cekit CentOS / RHEL ------------------- -Supported versions: 7.x +.. note:: + Supported versions: 7.x -For RHEL / CentOS we provide custom Copr repository. To enable the repository and install -CEKit on your system please run: +CEKit is available from the `EPEL repository <https://fedoraproject.org/wiki/EPEL>`_. .. code-block:: bash - curl https://copr.fedorainfracloud.org/coprs/g/cekit/cekit/repo/epel-7/group_cekit-cekit-epel-7.repo -o /etc/yum.repos.d/cekit-epel-7.repo - yum install python2-cekit + yum install epel-release + yum install cekit Other systems ------------------- -We strongly advise to use `Virtualenv <https://virtualenv.pypa.io/en/stable/>`_ to install CEKit. Please consult your package manager for the correct package name. +We strongly advise to use `Virtualenv <https://virtualenv.pypa.io/en/stable/>`_ to install CEKit. +Please consult your package manager for the correct package name. To create custom Python virtual environment please run following commands on your system: @@ -63,7 +68,8 @@ To create custom Python virtual environment please run following commands on you .. note:: - Every time you want to use CEKit you must activate CEKit Python virtual environment by executing ``source ~/cekit/bin/activate`` + Every time you want to use CEKit you must activate CEKit Python virtual environment by + executing ``source ~/cekit/bin/activate`` If you don't want to (or cannot) use Virtualenv, the best idea is to install CEKit in the user's home with the ``--user`` prefix: @@ -72,12 +78,6 @@ If you don't want to (or cannot) use Virtualenv, the best idea is to install CEK pip install -U cekit --user -.. .. include:: dependencies.rst - -.. .. include:: upgrade.rst - -.. .. toctree:: -.. :titlesonly: - -.. dependencies -.. upgrade \ No newline at end of file +.. note:: + In this case you may need to add ``~/.local/bin/`` directory to your ``$PATH`` environment variable to + be able to run the ``cekit`` command. \ No newline at end of file diff --git a/docs/installation/upgrade.rst b/docs/installation/upgrade.rst index 6f1aa49..d78eff0 100644 --- a/docs/installation/upgrade.rst +++ b/docs/installation/upgrade.rst @@ -3,26 +3,49 @@ Upgrading .. note:: - If you are running on Fedora / CentOS / RHEL you should be using RPM and our `COPR repository for CEKit <https://copr.fedorainfracloud.org/coprs/g/cekit/cekit/>`_. We assume, that you have this repository enabled on your system. + If you run on Fedora / CentOS / RHEL you should be using RPMs + from regular repositories. Please see :doc:`installation instructions </installation/instructions>`. + +Upgrade from CEKit 2.x +----------------------- + +Previous CEKit releases were provided via the `COPR repository <https://copr.fedorainfracloud.org/coprs/g/cekit/cekit/>`_ +which is now **deprecated**. The COPR repository **won't be updated anymore** with new releases. + +Fedora packages are not compatible with packages that come from the +`deprecated COPR repository <https://copr.fedorainfracloud.org/coprs/g/cekit/cekit/>`_, +you need to uninstall any packages that came from it before upgrading. + +.. tip:: + You can use ``dnf repolist`` to get the repository id (should be ``group_cekit-cekit`` by default) + which can be used for querying installed packages and removing them: + + .. code-block:: bash + + dnf list installed | grep @group_cekit-cekit | cut -f 1 -d ' ' | xargs sudo dnf remove {}\; + +Once all packages that came from the COPR repository you can follow the :doc:`installation instructions </installation/instructions>`. Fedora -------------------- .. code-block:: bash - dnf update python3-cekit + dnf update cekit CentOS / RHEL -------------------- .. code-block:: bash - yum update python2-cekit + yum update cekit Other systems ------------- +Use the ``pip -U`` switch to upgrade the installed module. + .. code-block:: bash pip install -U cekit --user diff --git a/docs/redhat.rst b/docs/redhat.rst index 8ed2031..86f5807 100644 --- a/docs/redhat.rst +++ b/docs/redhat.rst @@ -43,14 +43,27 @@ injected into the image you are building and you can successfully build an image Artifacts --------- -In Red Hat environment we are using Brew to build our packages and artifacts. CEKit provides an integration layer with Brew and enables to use artifact directly from Brew. To enable this set :ref:`redhat configuration option<redhat_config>` to True and define artifact **only** by specifying its ``md5`` checksum. +In Red Hat environment we are using Brew to build our packages and artifacts. +CEKit provides an integration layer with Brew and enables to use artifact +directly from Brew. To enable this set :ref:`redhat configuration option<redhat_config>` +to ``True`` (or use ``--redhat`` switch) and define plain artifacts which have ``md5`` checksum. +.. warning:: + Using different checksum thn ``md5`` will not work! -*Example:* Following artifact will be fetched directly from brew for Docker build and uses `Brew/OSBS inegration <https://osbs.readthedocs.io/en/latest/users.html#fetch-artifacts-url-yaml>`_ for OSBS build. +CEKit will fetch artifacts automatically from Brew, adding them to local cache. -.. code:: yaml +Depending on the selected builders, different preparations +will be performed to make it ready for the build process: - artifacts: - - md5: d31c6b1525e6d2d24062ef26a9f639a8 - name: jolokia-jvm-1.5.0.redhat-1-agent.jar +* for Docker/Buildah/Podman builder it will be available directly, +* for OSBS builder it uses the `Brew/OSBS integration <https://osbs.readthedocs.io/en/latest/users.html#fetch-artifacts-url-yaml>`_. +Example + .. code-block:: yaml + + artifacts: + - name: jolokia-jvm-1.5.0.redhat-1-agent.jar + md5: d31c6b1525e6d2d24062ef26a9f639a8 + + This is everything required to fetch the artifact.
cekit/cekit
980fc1874dfeebe25f56c3edd84e29f9aa6d2529
diff --git a/cekit/test/runner.py b/cekit/test/behave_runner.py similarity index 75% rename from cekit/test/runner.py rename to cekit/test/behave_runner.py index e43c2db..3fc5ef6 100644 --- a/cekit/test/runner.py +++ b/cekit/test/behave_runner.py @@ -1,27 +1,34 @@ import getpass import logging import os -import subprocess from cekit.errors import CekitError from cekit.tools import Chdir +try: + from behave.__main__ import main as behave_main +except ImportError: + pass + logger = logging.getLogger('cekit') -class TestRunner(object): +class BehaveTestRunner(object): def __init__(self, target): - """Check if behave and docker is installed properly""" self.target = os.path.abspath(target) - try: - # check that we have behave installed - from behave.__main__ import main as behave_main - except subprocess.CalledProcessError as ex: - raise CekitError("Test Runner needs 'behave' installed, '%s'" % - ex.output) - except Exception as ex: - raise CekitError( - "Test Runner needs behave installed!", ex) + + @staticmethod + def dependencies(): + deps = {} + + deps['python-behave'] = { + 'library': 'behave', + 'package': 'python2-behave', + 'fedora': { + 'package': 'python3-behave'} + } + + return deps def run(self, image, run_tags, test_names): """Run test suite""" @@ -57,8 +64,6 @@ class TestRunner(object): args.append("~ci ") try: - from behave.__main__ import main as behave_main - with Chdir(os.path.join(self.target, 'test')): logger.debug("behave args: {}".format(args)) if behave_main(args) != 0: diff --git a/cekit/test/behave.py b/cekit/test/behave_tester.py similarity index 68% rename from cekit/test/behave.py rename to cekit/test/behave_tester.py index cf71059..e7aef6b 100644 --- a/cekit/test/behave.py +++ b/cekit/test/behave_tester.py @@ -3,15 +3,15 @@ import os from cekit.builder import Command from cekit.generator.base import Generator -from cekit.test.collector import TestCollector -from cekit.test.runner import TestRunner +from cekit.test.collector import BehaveTestCollector +from cekit.test.behave_runner import BehaveTestRunner LOGGER = logging.getLogger('cekit') class BehaveTester(Command): """ - Tested implementation for the Behave framework + Tester implementation for the Behave framework """ def __init__(self, common_params, params): @@ -21,8 +21,9 @@ class BehaveTester(Command): self.params = params self.collected = False - self.test_collector = TestCollector(os.path.dirname(self.common_params.descriptor), + self.test_collector = BehaveTestCollector(os.path.dirname(self.common_params.descriptor), self.common_params.target) + self.test_runner = BehaveTestRunner(self.common_params.target) self.generator = None @@ -43,8 +44,10 @@ class BehaveTester(Command): if self.collected: # Handle test dependencies, if any - LOGGER.debug("Checking CEKit test dependencies...") + LOGGER.debug("Checking CEKit test collector dependencies...") self.dependency_handler.handle(self.test_collector) + LOGGER.debug("Checking CEKit test runner dependencies...") + self.dependency_handler.handle(self.test_runner) def run(self): if not self.collected: @@ -57,6 +60,10 @@ class BehaveTester(Command): if self.params.wip: test_tags = ['@wip'] - runner = TestRunner(self.common_params.target) - runner.run(self.params.image, test_tags, - test_names=self.params.names) + image = self.params.image + + if not image: + image = self.generator.get_tags()[0] + + self.test_runner.run(image, test_tags, + test_names=self.params.names) diff --git a/cekit/test/collector.py b/cekit/test/collector.py index db71fdc..6514939 100644 --- a/cekit/test/collector.py +++ b/cekit/test/collector.py @@ -7,7 +7,7 @@ import sys logger = logging.getLogger('cekit') -class TestCollector(object): +class BehaveTestCollector(object): def __init__(self, descriptor_dir, target_dir): self.collected = False self.descriptor_dir = os.path.abspath(descriptor_dir) diff --git a/tests/test_integ_test_behave.py b/tests/test_integ_test_behave.py new file mode 100644 index 0000000..b429772 --- /dev/null +++ b/tests/test_integ_test_behave.py @@ -0,0 +1,72 @@ +# -*- encoding: utf-8 -*- + +import os +import shutil +import tempfile + +import pytest +import yaml + +from click.testing import CliRunner + +from cekit.cli import cli +from cekit.tools import Chdir + + +image_descriptor = { + 'schema_version': 1, + 'from': 'alpine:3.9', + 'name': 'test/image', + 'version': '1.0', + 'labels': [{'name': 'foo', 'value': 'bar'}, {'name': 'labela', 'value': 'a'}], + 'envs': [{'name': 'baz', 'value': 'qux'}, {'name': 'enva', 'value': 'a'}], + 'run': {'cmd': ['tail', '-f', '/dev/null']}, +} + + [email protected](scope="module", name="test_image_dir") +def build_test_image_dir(): + image_dir = tempfile.mkdtemp(prefix="tmp-cekit-test") + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(image_descriptor, fd, default_flow_style=False) + + with Chdir(image_dir): + result = CliRunner().invoke(cli, ["-v", "build", "docker"], catch_exceptions=False) + + assert result.exit_code == 0 + + return image_dir + + [email protected](autouse=True) +def clean_target_directory(test_image_dir): + shutil.rmtree(os.path.join(test_image_dir, 'target'), ignore_errors=True) + + +def test_execute_simple_behave_test(test_image_dir): + feature = """@test +Feature: Basic tests + + Scenario: Check that the labels are correctly set + Given image is built + Then the image should contain label foo with value bar + And the image should contain label labela with value a + """ + + features_dir = os.path.join(test_image_dir, 'tests', 'features') + + os.makedirs(features_dir) + + with open(os.path.join(features_dir, 'basic.feature'), 'w') as fd: + fd.write(feature) + + with Chdir(test_image_dir): + result = CliRunner().invoke(cli, ["-v", "test", "behave"], catch_exceptions=False) + + print(result.output) + + assert result.exit_code == 0 + assert "1 feature passed, 0 failed, 0 skipped" in result.output + assert "1 scenario passed, 0 failed, 0 skipped" in result.output + assert "3 steps passed, 0 failed, 0 skipped, 0 undefined" in result.output diff --git a/tests/test_unit_args.py b/tests/test_unit_args.py index 96611c3..5488bc5 100644 --- a/tests/test_unit_args.py +++ b/tests/test_unit_args.py @@ -118,7 +118,7 @@ def get_class_by_name(clazz): ), ( ['test', '--image', 'image:1.0', 'behave'], - 'cekit.test.behave.BehaveTester', + 'cekit.test.behave_tester.BehaveTester', { 'descriptor': 'image.yaml', 'verbose': False, 'work_dir': '~/.cekit', 'config': '~/.cekit/config', 'redhat': False, 'target': 'target' }, diff --git a/tests/test_unit_collector.py b/tests/test_unit_collector.py index 599b317..8877f35 100644 --- a/tests/test_unit_collector.py +++ b/tests/test_unit_collector.py @@ -2,7 +2,7 @@ import os import shutil import pytest -from cekit.test.collector import TestCollector +from cekit.test.collector import BehaveTestCollector desc_dir = "/tmp/desc" target_dir = "/tmp/target_dir" @@ -19,8 +19,8 @@ def prepare_dirs(): def test_collect_test_from_image_repo(prepare_dirs, mocker): - mocker.patch.object(TestCollector, '_fetch_steps') - collector = TestCollector(desc_dir, target_dir) + mocker.patch.object(BehaveTestCollector, '_fetch_steps') + collector = BehaveTestCollector(desc_dir, target_dir) features_file = os.path.join(desc_dir, 'tests', @@ -41,8 +41,8 @@ def test_collect_test_from_image_repo(prepare_dirs, mocker): def test_collect_test_from_repository_root(prepare_dirs, mocker): - mocker.patch.object(TestCollector, '_fetch_steps') - collector = TestCollector(desc_dir, target_dir) + mocker.patch.object(BehaveTestCollector, '_fetch_steps') + collector = BehaveTestCollector(desc_dir, target_dir) features_file = os.path.join(target_dir, 'repo', @@ -65,8 +65,8 @@ def test_collect_test_from_repository_root(prepare_dirs, mocker): def test_collect_test_from_module(prepare_dirs, mocker): - mocker.patch.object(TestCollector, '_fetch_steps') - collector = TestCollector(desc_dir, target_dir) + mocker.patch.object(BehaveTestCollector, '_fetch_steps') + collector = BehaveTestCollector(desc_dir, target_dir) features_file = os.path.join(target_dir, 'image', @@ -90,9 +90,9 @@ def test_collect_test_from_module(prepare_dirs, mocker): def test_collect_return_false(prepare_dirs, mocker): - mocker.patch.object(TestCollector, '_fetch_steps') + mocker.patch.object(BehaveTestCollector, '_fetch_steps') - collector = TestCollector(desc_dir, target_dir) + collector = BehaveTestCollector(desc_dir, target_dir) assert not collector.collect('1', steps_url)
Update documentation for artifacts definition Make it clear what keys are required and what are optional.
0.0
980fc1874dfeebe25f56c3edd84e29f9aa6d2529
[ "tests/test_unit_args.py::test_args_command[args10-cekit.test.behave_tester.BehaveTester-common_params10-params10]" ]
[ "tests/test_unit_args.py::test_args_command[args0-cekit.builders.docker_builder.DockerBuilder-common_params0-params0]", "tests/test_unit_args.py::test_args_command[args1-cekit.builders.docker_builder.DockerBuilder-common_params1-params1]", "tests/test_unit_args.py::test_args_command[args2-cekit.builders.docker_builder.DockerBuilder-common_params2-params2]", "tests/test_unit_args.py::test_args_command[args3-cekit.builders.docker_builder.DockerBuilder-common_params3-params3]", "tests/test_unit_args.py::test_args_command[args4-cekit.builders.docker_builder.DockerBuilder-None-params4]", "tests/test_unit_args.py::test_args_command[args5-cekit.builders.docker_builder.DockerBuilder-None-params5]", "tests/test_unit_args.py::test_args_command[args6-cekit.builders.osbs.OSBSBuilder-None-params6]", "tests/test_unit_args.py::test_args_command[args7-cekit.builders.osbs.OSBSBuilder-None-params7]", "tests/test_unit_args.py::test_args_command[args8-cekit.builders.osbs.OSBSBuilder-None-params8]", "tests/test_unit_args.py::test_args_command[args9-cekit.builders.osbs.OSBSBuilder-None-params9]", "tests/test_unit_args.py::test_args_command[args11-cekit.builders.docker_builder.DockerBuilder-None-params11]", "tests/test_unit_args.py::test_args_command[args12-cekit.builders.osbs.OSBSBuilder-None-params12]", "tests/test_unit_args.py::test_args_command[args13-cekit.builders.docker_builder.DockerBuilder-None-params13]", "tests/test_unit_args.py::test_args_command[args14-cekit.builders.buildah.BuildahBuilder-None-params14]", "tests/test_unit_collector.py::test_collect_test_from_image_repo", "tests/test_unit_collector.py::test_collect_test_from_repository_root", "tests/test_unit_collector.py::test_collect_test_from_module", "tests/test_unit_collector.py::test_collect_return_false" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-03-19 12:15:24+00:00
mit
1,535
cekit__cekit-452
diff --git a/cekit/tools.py b/cekit/tools.py index 04a779c..4c9bd05 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -158,7 +158,8 @@ class DependencyHandler(object): with open(os_release_path, 'r') as f: content = f.readlines() - self.os_release = dict(l.strip().split('=') for l in content) + self.os_release = dict([l.strip().split('=') + for l in content if not l.isspace() and not l.strip().startswith('#')]) # Remove the quote character, if it's there for key in self.os_release.keys():
cekit/cekit
b97aded6a433222d79fcbbc4823c33f82c56a473
diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index b146a0e..859d5c5 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -9,6 +9,43 @@ from cekit.descriptor import Descriptor, Image, Module, Overrides, Run from cekit.errors import CekitError from cekit import tools +rhel_7_os_release = '''NAME="Red Hat Enterprise Linux Server" +VERSION="7.7 (Maipo)" +ID="rhel" +ID_LIKE="fedora" +VARIANT="Server" +VARIANT_ID="server" +# Some comment +VERSION_ID="7.7" +PRETTY_NAME="Red Hat Enterprise Linux Server 7.7 Beta (Maipo)" +ANSI_COLOR="0;31" +CPE_NAME="cpe:/o:redhat:enterprise_linux:7.7:beta:server" +HOME_URL="https://www.redhat.com/" +BUG_REPORT_URL="https://bugzilla.redhat.com/" + +REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 7" +REDHAT_BUGZILLA_PRODUCT_VERSION=7.7 +REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux" +REDHAT_SUPPORT_PRODUCT_VERSION="7.7 Beta"''' + +rhel_8_os_release = '''NAME="Red Hat Enterprise Linux" + # Poor comment +VERSION="8.0 (Ootpa)" +ID="rhel" +ID_LIKE="fedora" +VERSION_ID="8.0" +PLATFORM_ID="platform:el8" +PRETTY_NAME="Red Hat Enterprise Linux 8.0 (Ootpa)" +ANSI_COLOR="0;31" +CPE_NAME="cpe:/o:redhat:enterprise_linux:8.0:GA" +HOME_URL="https://www.redhat.com/" +BUG_REPORT_URL="https://bugzilla.redhat.com/" + +REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8" +REDHAT_BUGZILLA_PRODUCT_VERSION=8.0 +REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux" +REDHAT_SUPPORT_PRODUCT_VERSION="8.0"''' + class MockedDescriptor(Descriptor): def __init__(self, descriptor): @@ -52,39 +89,39 @@ def test_merging_description_override(): def test_merging_plain_descriptors(): desc1 = MockedDescriptor({'name': 'foo', - 'a': 1, - 'b': 2}) + 'a': 1, + 'b': 2}) desc2 = MockedDescriptor({'name': 'foo', - 'b': 5, - 'c': 3}) + 'b': 5, + 'c': 3}) expected = MockedDescriptor({'name': 'foo', - 'a': 1, - 'b': 2, - 'c': 3}) + 'a': 1, + 'b': 2, + 'c': 3}) assert expected == _merge_descriptors(desc1, desc2) assert expected.items() == _merge_descriptors(desc1, desc2).items() def test_merging_emdedded_descriptors(): desc1 = MockedDescriptor({'name': 'a', - 'a': 1, - 'b': {'name': 'b', - 'b1': 10, - 'b2': 20}}) + 'a': 1, + 'b': {'name': 'b', + 'b1': 10, + 'b2': 20}}) desc2 = MockedDescriptor({'b': {'name': 'b', - 'b2': 50, - 'b3': 30}, - 'c': {'name': 'c'}}) + 'b2': 50, + 'b3': 30}, + 'c': {'name': 'c'}}) expected = MockedDescriptor({'name': 'a', - 'a': 1, - 'b': {'name': 'b', - 'b1': 10, - 'b2': 20, - 'b3': 30}, - 'c': {'name': 'c'}}) + 'a': 1, + 'b': {'name': 'b', + 'b1': 10, + 'b2': 20, + 'b3': 30}, + 'c': {'name': 'c'}}) assert expected == _merge_descriptors(desc1, desc2) @@ -105,21 +142,21 @@ def test_merging_plain_list_of_list(): def test_merging_list_of_descriptors(): desc1 = [MockedDescriptor({'name': 1, - 'a': 1, - 'b': 2})] + 'a': 1, + 'b': 2})] desc2 = [MockedDescriptor({'name': 2, - 'a': 123}), + 'a': 123}), MockedDescriptor({'name': 1, - 'b': 3, - 'c': 3})] + 'b': 3, + 'c': 3})] expected = [MockedDescriptor({'name': 2, - 'a': 123}), + 'a': 123}), MockedDescriptor({'name': 1, - 'a': 1, - 'b': 2, - 'c': 3})] + 'a': 1, + 'b': 2, + 'c': 3})] assert expected == _merge_lists(desc1, desc2) @@ -223,6 +260,26 @@ def test_dependency_handler_init_on_unknown_env_with_os_release_file(mocker, cap assert "You are running CEKit on an unknown platform. External dependencies suggestions may not work!" in caplog.text +# https://github.com/cekit/cekit/issues/450 +def test_dependency_handler_on_rhel_7(mocker, caplog): + caplog.set_level(logging.DEBUG, logger="cekit") + + with mocked_dependency_handler(mocker, rhel_7_os_release): + pass + + assert "You are running on known platform: Red Hat Enterprise Linux Server 7.7 (Maipo)" in caplog.text + + +# https://github.com/cekit/cekit/issues/450 +def test_dependency_handler_on_rhel_8(mocker, caplog): + caplog.set_level(logging.DEBUG, logger="cekit") + + with mocked_dependency_handler(mocker, rhel_8_os_release): + pass + + assert "You are running on known platform: Red Hat Enterprise Linux 8.0 (Ootpa)" in caplog.text + + def test_dependency_handler_init_on_known_env(mocker, caplog): caplog.set_level(logging.DEBUG, logger="cekit") @@ -347,8 +404,6 @@ def test_dependency_handler_handle_dependencies_with_platform_specific_package(m handler._check_for_executable.assert_called_once_with( 'xyz', 'xyz-aaa', 'python-fedora-xyz-aaa') - print(caplog.text) - assert "Checking if 'xyz' dependency is provided..." in caplog.text assert "All dependencies provided!" in caplog.text
ValueError: dictionary update sequence element #12 has length 1; 2 is required With [this image source](https://github.com/jmtd/openjdk/tree/rhel8-2k19) (branch rhel8-2k19, commit 503685f9621f91183a1d9fcfcf65cbe8f5745b84) and [this module cloned locally](https://github.com/jmtd/cct_module/tree/rhel82k19) (branch rhel82k1 commit d5e432eeedc503ca2c68744d0167741b0bbd54a9), I get the following when I try `cekit build --overrides-file rhel8-jdk11-overrides.yaml docker`, using cekit develop HEAD=`16489fa42ec264613b91217d1f719c8c702ea1ef`: ``` 2019-03-20 15:40:29,115 cekit WARNING You are running unreleased development version of CEKit, use it only at your own risk! Traceback (most recent call last): File "/home/ce/cekit/develop/bin/cekit", line 11, in <module> load_entry_point('cekit==3.0.dev0', 'console_scripts', 'cekit')() File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 764, in __call__ return self.main(*args, **kwargs) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 717, in main rv = self.invoke(ctx) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/core.py", line 555, in invoke return callback(*args, **kwargs) File "/home/ce/cekit/develop/lib/python2.7/site-packages/click/decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/cli.py", line 106, in build_docker run_build(ctx, 'docker') File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/cli.py", line 280, in run_build run_command(ctx, builder_impl) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/cli.py", line 249, in run_command Cekit(common_params).run(clazz, params) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/cli.py", line 333, in run command = clazz(self.params, params) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/builders/docker_builder.py", line 49, in __init__ super(DockerBuilder, self).__init__('docker', common_params, params) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/builder.py", line 50, in __init__ super(Builder, self).__init__(self.build_engine, Command.TYPE_BUILDER) File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/builder.py", line 20, in __init__ self.dependency_handler = DependencyHandler() File "/home/ce/cekit/develop/lib/python2.7/site-packages/cekit/tools.py", line 161, in __init__ self.os_release = dict(l.strip().split('=') for l in content) ValueError: dictionary update sequence element #12 has length 1; 2 is required ```
0.0
b97aded6a433222d79fcbbc4823c33f82c56a473
[ "tests/test_unit_tools.py::test_dependency_handler_on_rhel_7", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_8" ]
[ "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2019-03-21 09:58:16+00:00
mit
1,536
cekit__cekit-507
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 00a9d47..ece94c5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -2,7 +2,7 @@ name: Bug report about: Found issue? Let us know! title: '' -labels: type/bug +labels: type/bug, status/review assignees: '' --- diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md index 90e6779..1d1f8a8 100644 --- a/.github/ISSUE_TEMPLATE/enhancement.md +++ b/.github/ISSUE_TEMPLATE/enhancement.md @@ -2,7 +2,7 @@ name: Enhancement about: Want to see something new? Let us know! title: '' -labels: type/enhancement +labels: status/review, type/enhancement assignees: '' --- diff --git a/cekit/builders/docker_builder.py b/cekit/builders/docker_builder.py index 8addd4e..74347bf 100644 --- a/cekit/builders/docker_builder.py +++ b/cekit/builders/docker_builder.py @@ -162,7 +162,7 @@ class DockerBuilder(Builder): def _tag(self, docker_client, image_id, tags): for tag in tags: if ':' in tag: - img_repo, img_tag = tag.split(":") + img_repo, img_tag = tag.rsplit(":", 1) docker_client.tag(image_id, img_repo, tag=img_tag) else: docker_client.tag(image_id, tag) diff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py index f735056..808c404 100644 --- a/cekit/builders/osbs.py +++ b/cekit/builders/osbs.py @@ -140,12 +140,11 @@ class OSBSBuilder(Builder): if os.path.exists("container.yaml"): self._merge_container_yaml("container.yaml", os.path.join(self.dist_git_dir, "container.yaml")) - if os.path.exists("content_sets.yml"): - shutil.copy("content_sets.yml", - os.path.join(self.dist_git_dir, "content_sets.yml")) - if os.path.exists("fetch-artifacts-url.yaml"): - shutil.copy("fetch-artifacts-url.yaml", - os.path.join(self.dist_git_dir, "fetch-artifacts-url.yaml")) + + for special_file in ["content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(special_file): + shutil.copy(special_file, + os.path.join(self.dist_git_dir, special_file)) # Copy also every artifact for artifact in self.artifacts: @@ -232,7 +231,7 @@ class OSBSBuilder(Builder): try: subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as ex: - LOGGER.error("Cannot run '%s', ouput: '%s'" % (cmd, ex.output)) + LOGGER.error("Cannot run '%s', output: '%s'" % (cmd, ex.output)) raise CekitError("Cannot update sources.") LOGGER.info("Update finished.") @@ -345,10 +344,10 @@ class DistGit(object): if os.path.exists(self.output): with Chdir(self.output): LOGGER.info("Pulling latest changes in repo %s..." % self.repo) - subprocess.check_output(["git", "fetch"]) - subprocess.check_output( + subprocess.check_call(["git", "fetch"]) + subprocess.check_call( ["git", "checkout", "-f", self.branch], stderr=subprocess.STDOUT) - subprocess.check_output( + subprocess.check_call( ["git", "reset", "--hard", "origin/%s" % self.branch]) LOGGER.debug("Changes pulled") else: @@ -364,7 +363,7 @@ class DistGit(object): cmd += ['--user', user] cmd += ["-q", "clone", "-b", self.branch, self.repo, self.output] LOGGER.debug("Cloning: '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.debug("Repository %s cloned" % self.repo) def clean(self): @@ -382,12 +381,10 @@ class DistGit(object): def add(self): # Add new Dockerfile subprocess.check_call(["git", "add", "Dockerfile"]) - if os.path.exists("container.yaml"): - subprocess.check_call(["git", "add", "container.yaml"]) - if os.path.exists("content_sets.yml"): - subprocess.check_call(["git", "add", "content_sets.yml"]) - if os.path.exists("fetch-artifacts-url.yaml"): - subprocess.check_call(["git", "add", "fetch-artifacts-url.yaml"]) + + for f in ["container.yaml", "content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(f): + subprocess.check_call(["git", "add", f]) for d in ["repos", "modules"]: # we probably do not care about non existing files and other errors here @@ -405,7 +402,7 @@ class DistGit(object): # Commit the change LOGGER.info("Commiting with message: '%s'" % commit_msg) - subprocess.check_output(["git", "commit", "-q", "-m", commit_msg]) + subprocess.check_call(["git", "commit", "-q", "-m", commit_msg]) untracked = subprocess.check_output( ["git", "ls-files", "--others", "--exclude-standard"]).decode("utf8") @@ -438,7 +435,7 @@ class DistGit(object): LOGGER.info("Pushing change to the upstream repository...") cmd = ["git", "push", "-q", "origin", self.branch] LOGGER.debug("Running command '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.info("Change pushed.") else: LOGGER.info("Changes are not pushed, exiting") diff --git a/cekit/tools.py b/cekit/tools.py index 4c9bd05..30a4387 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -64,25 +64,42 @@ def decision(question): def get_brew_url(md5): try: - LOGGER.debug("Getting brew details for an artifact with '%s' md5 sum" % md5) + LOGGER.debug("Getting brew details for an artifact with '{}' md5 sum".format(md5)) list_archives_cmd = ['/usr/bin/brew', 'call', '--json-output', 'listArchives', - 'checksum=%s' % md5, 'type=maven'] - LOGGER.debug("Executing '%s'." % " ".join(list_archives_cmd)) - archive_yaml = yaml.safe_load(subprocess.check_output(list_archives_cmd)) + "checksum={}".format(md5), 'type=maven'] + LOGGER.debug("Executing '{}'.".format(" ".join(list_archives_cmd))) - if not archive_yaml: - raise CekitError("Artifact with md5 checksum %s could not be found in Brew" % md5) + try: + json_archives = subprocess.check_output(list_archives_cmd).strip().decode("utf8") + except subprocess.CalledProcessError as ex: + if ex.output is not None and 'AuthError' in ex.output: + LOGGER.warning( + "Brew authentication failed, please make sure you have a valid Kerberos ticket") + raise CekitError("Could not fetch archives for checksum {}".format(md5), ex) - archive = archive_yaml[0] + archives = yaml.safe_load(json_archives) + + if not archives: + raise CekitError("Artifact with md5 checksum {} could not be found in Brew".format(md5)) + + archive = archives[0] build_id = archive['build_id'] filename = archive['filename'] group_id = archive['group_id'] artifact_id = archive['artifact_id'] version = archive['version'] - get_build_cmd = ['brew', 'call', '--json-output', 'getBuild', 'buildInfo=%s' % build_id] - LOGGER.debug("Executing '%s'" % " ".join(get_build_cmd)) - build = yaml.safe_load(subprocess.check_output(get_build_cmd)) + get_build_cmd = ['brew', 'call', '--json-output', + 'getBuild', "buildInfo={}".format(build_id)] + + LOGGER.debug("Executing '{}'".format(" ".join(get_build_cmd))) + + try: + json_build = subprocess.check_output(get_build_cmd).strip().decode("utf8") + except subprocess.CalledProcessError as ex: + raise CekitError("Could not fetch build {} from Brew".format(build_id), ex) + + build = yaml.safe_load(json_build) build_states = ['BUILDING', 'COMPLETE', 'DELETED', 'FAILED', 'CANCELED']
cekit/cekit
3b9283cb26b35511517ff5c0c3e11f490cba8feb
diff --git a/tests/test_integ_builder_osbs.py b/tests/test_integ_builder_osbs.py new file mode 100644 index 0000000..3ae9568 --- /dev/null +++ b/tests/test_integ_builder_osbs.py @@ -0,0 +1,195 @@ +# -*- encoding: utf-8 -*- + +# pylint: disable=protected-access + +import logging +import os +import subprocess +import yaml + +import pytest + +from click.testing import CliRunner + +from cekit.cli import Cekit, Map, cli +from cekit.tools import Chdir +from cekit.config import Config +from cekit.errors import CekitError +from cekit.builders.osbs import OSBSBuilder +from cekit.tools import Map + +config = Config() + + [email protected](autouse=True) +def reset_config(): + config.cfg['common'] = {} + + +config = Config() +config.cfg['common'] = {'redhat': True} + +image_descriptor = { + 'schema_version': 1, + 'from': 'centos:latest', + 'name': 'test/image', + 'version': '1.0', + 'labels': [{'name': 'foo', 'value': 'bar'}, {'name': 'labela', 'value': 'a'}], + 'osbs': { + 'repository': { + 'name': 'repo', + 'branch': 'branch' + } + } +} + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def run_osbs(descriptor, image_dir, mocker): + # We are mocking it, so do not require it at test time + mocker.patch('cekit.builders.osbs.OSBSBuilder.dependencies', return_value={}) + mocker.patch('cekit.builders.osbs.OSBSBuilder._wait_for_osbs_task') + mocker.patch('cekit.builders.osbs.DistGit.clean') + mocker.patch('cekit.builders.osbs.DistGit.prepare') + mocker.patch('cekit.tools.decision', return_value=True) + + mocker_check_call = mocker.patch.object(subprocess, 'check_output', side_effect=[ + b"true", # git rev-parse --is-inside-work-tree + b"/home/repos/path", # git rev-parse --show-toplevel + b"branch", # git rev-parse --abbrev-ref HEAD + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"", # git ls-files --others --exclude-standard + b"", # git diff-files --name-only + b"ssh://[email protected]/containers/somerepo", # git config --get remote.origin.url + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"1234", # brew call --python... + ]) + + with open(os.path.join(image_dir, 'config'), 'w') as fd: + fd.write("[common]\n") + fd.write("redhat = True") + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(descriptor, fd, default_flow_style=False) + + return run_cekit(image_dir, ['-v', + '--work-dir', image_dir, + '--config', + 'config', + 'build', + 'osbs']) + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def test_osbs_builder_kick_build_without_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + mocker.patch.object(subprocess, 'call', return_value=0) + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + ]) + + assert "No changes made to the code, committing skipped" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +def test_osbs_builder_kick_build_with_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=1) + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'commit', '-q', '-m', + 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb']), + mocker.call(['git', 'push', '-q', 'origin', 'branch']) + ]) + + assert "Commiting with message: 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb'" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +# https://github.com/cekit/cekit/issues/504 +def test_osbs_builder_add_help_file(tmpdir, mocker, caplog): + """ + Checks if help.md file is generated and added to dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=0) + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + descriptor['help'] = {'add': True} + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + assert os.path.exists(str(repo_dir.join('help.md'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'add', 'help.md']), + ]) + + assert "Image was built successfully in OSBS!" in caplog.text diff --git a/tests/test_unit_builder_docker.py b/tests/test_unit_builder_docker.py index 26d6f3b..bdd8378 100644 --- a/tests/test_unit_builder_docker.py +++ b/tests/test_unit_builder_docker.py @@ -134,3 +134,19 @@ def test_docker_client_build_with_failure(mocker, caplog): docker_client_build.assert_called_once_with(path='something/image', pull=None, rm=True) assert "Docker: Step 3/159 : COPY modules /tmp/scripts/" in caplog.text assert "You can look inside the failed image by running 'docker run --rm -ti 81a88b63f47f bash'" in caplog.text + + +# https://github.com/cekit/cekit/issues/508 +def test_docker_tag(mocker): + builder = DockerBuilder(Map({'target': 'something'}), Map({'tags': ['foo', 'bar']})) + + docker_client_mock = mocker.Mock() + + builder._tag(docker_client_mock, "image_id", ["image:latest", "host:5000/repo/image:tag"]) + + assert len(docker_client_mock.tag.mock_calls) == 2 + + docker_client_mock.tag.assert_has_calls([ + mocker.call("image_id", "image", tag="latest"), + mocker.call("image_id", "host:5000/repo/image", tag="tag") + ]) diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index 859d5c5..24ffe42 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -1,5 +1,6 @@ import logging import pytest +import subprocess import yaml from contextlib import contextmanager @@ -187,7 +188,7 @@ def brew_call_ok(*args, **kwargs): "artifact_id": "artifact_id", "version": "version", } - ]""" + ]""".encode("utf8") if 'getBuild' in args[0]: return """ { @@ -195,8 +196,8 @@ def brew_call_ok(*args, **kwargs): "release": "release", "state": 1 } - """ - return "" + """.encode("utf8") + return "".encode("utf8") def brew_call_removed(*args, **kwargs): @@ -210,7 +211,7 @@ def brew_call_removed(*args, **kwargs): "artifact_id": "artifact_id", "version": "version", } - ]""" + ]""".encode("utf8") if 'getBuild' in args[0]: return """ { @@ -218,8 +219,8 @@ def brew_call_removed(*args, **kwargs): "release": "release", "state": 2 } - """ - return "" + """.encode("utf8") + return "".encode("utf8") def test_get_brew_url(mocker): @@ -239,6 +240,22 @@ def test_get_brew_url_when_build_was_removed(mocker): excinfo.value) +# https://github.com/cekit/cekit/issues/502 +def test_get_brew_url_no_kerberos(mocker, caplog): + caplog.set_level(logging.DEBUG, logger="cekit") + + kerberos_error = subprocess.CalledProcessError(1, 'CMD') + kerberos_error.output = "2019-05-06 14:58:44,502 [ERROR] koji: AuthError: unable to obtain a session" + + mocker.patch('subprocess.check_output', side_effect=kerberos_error) + + with pytest.raises(CekitError) as excinfo: + tools.get_brew_url('aa') + + assert 'Could not fetch archives for checksum aa' in str(excinfo.value) + assert "Brew authentication failed, please make sure you have a valid Kerberos ticket" in caplog.text + + @contextmanager def mocked_dependency_handler(mocker, data="ID=fedora\nNAME=somefedora\nVERSION=123"): dh = None
Expired krb sessions don't fail the build ``` 2019-05-01 01:27:34,395 cekit DEBUG Executing '/usr/bin/brew call --json-output listArchives checksum=cd68ad886a759d21f8dd0cb7646601ee type=maven'. 2019-05-01 01:27:35,812 [ERROR] koji: AuthError: unable to obtain a session 2019-05-01 01:27:35,858 cekit ERROR Can't fetch artifacts details from brew: 'b'''. ``` Resolved by running kinit again. I think it should fail hard here.
0.0
3b9283cb26b35511517ff5c0c3e11f490cba8feb
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_with_push", "tests/test_integ_builder_osbs.py::test_osbs_builder_add_help_file", "tests/test_unit_builder_docker.py::test_docker_tag", "tests/test_unit_tools.py::test_get_brew_url_no_kerberos" ]
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_without_push", "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_7", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_8", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-06 13:07:58+00:00
mit
1,537
cekit__cekit-509
diff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py index f735056..808c404 100644 --- a/cekit/builders/osbs.py +++ b/cekit/builders/osbs.py @@ -140,12 +140,11 @@ class OSBSBuilder(Builder): if os.path.exists("container.yaml"): self._merge_container_yaml("container.yaml", os.path.join(self.dist_git_dir, "container.yaml")) - if os.path.exists("content_sets.yml"): - shutil.copy("content_sets.yml", - os.path.join(self.dist_git_dir, "content_sets.yml")) - if os.path.exists("fetch-artifacts-url.yaml"): - shutil.copy("fetch-artifacts-url.yaml", - os.path.join(self.dist_git_dir, "fetch-artifacts-url.yaml")) + + for special_file in ["content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(special_file): + shutil.copy(special_file, + os.path.join(self.dist_git_dir, special_file)) # Copy also every artifact for artifact in self.artifacts: @@ -232,7 +231,7 @@ class OSBSBuilder(Builder): try: subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as ex: - LOGGER.error("Cannot run '%s', ouput: '%s'" % (cmd, ex.output)) + LOGGER.error("Cannot run '%s', output: '%s'" % (cmd, ex.output)) raise CekitError("Cannot update sources.") LOGGER.info("Update finished.") @@ -345,10 +344,10 @@ class DistGit(object): if os.path.exists(self.output): with Chdir(self.output): LOGGER.info("Pulling latest changes in repo %s..." % self.repo) - subprocess.check_output(["git", "fetch"]) - subprocess.check_output( + subprocess.check_call(["git", "fetch"]) + subprocess.check_call( ["git", "checkout", "-f", self.branch], stderr=subprocess.STDOUT) - subprocess.check_output( + subprocess.check_call( ["git", "reset", "--hard", "origin/%s" % self.branch]) LOGGER.debug("Changes pulled") else: @@ -364,7 +363,7 @@ class DistGit(object): cmd += ['--user', user] cmd += ["-q", "clone", "-b", self.branch, self.repo, self.output] LOGGER.debug("Cloning: '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.debug("Repository %s cloned" % self.repo) def clean(self): @@ -382,12 +381,10 @@ class DistGit(object): def add(self): # Add new Dockerfile subprocess.check_call(["git", "add", "Dockerfile"]) - if os.path.exists("container.yaml"): - subprocess.check_call(["git", "add", "container.yaml"]) - if os.path.exists("content_sets.yml"): - subprocess.check_call(["git", "add", "content_sets.yml"]) - if os.path.exists("fetch-artifacts-url.yaml"): - subprocess.check_call(["git", "add", "fetch-artifacts-url.yaml"]) + + for f in ["container.yaml", "content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(f): + subprocess.check_call(["git", "add", f]) for d in ["repos", "modules"]: # we probably do not care about non existing files and other errors here @@ -405,7 +402,7 @@ class DistGit(object): # Commit the change LOGGER.info("Commiting with message: '%s'" % commit_msg) - subprocess.check_output(["git", "commit", "-q", "-m", commit_msg]) + subprocess.check_call(["git", "commit", "-q", "-m", commit_msg]) untracked = subprocess.check_output( ["git", "ls-files", "--others", "--exclude-standard"]).decode("utf8") @@ -438,7 +435,7 @@ class DistGit(object): LOGGER.info("Pushing change to the upstream repository...") cmd = ["git", "push", "-q", "origin", self.branch] LOGGER.debug("Running command '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.info("Change pushed.") else: LOGGER.info("Changes are not pushed, exiting")
cekit/cekit
6b82c4adc0e2e1d2ddda66305c1c9abe7b91f407
diff --git a/tests/test_integ_builder_osbs.py b/tests/test_integ_builder_osbs.py new file mode 100644 index 0000000..3ae9568 --- /dev/null +++ b/tests/test_integ_builder_osbs.py @@ -0,0 +1,195 @@ +# -*- encoding: utf-8 -*- + +# pylint: disable=protected-access + +import logging +import os +import subprocess +import yaml + +import pytest + +from click.testing import CliRunner + +from cekit.cli import Cekit, Map, cli +from cekit.tools import Chdir +from cekit.config import Config +from cekit.errors import CekitError +from cekit.builders.osbs import OSBSBuilder +from cekit.tools import Map + +config = Config() + + [email protected](autouse=True) +def reset_config(): + config.cfg['common'] = {} + + +config = Config() +config.cfg['common'] = {'redhat': True} + +image_descriptor = { + 'schema_version': 1, + 'from': 'centos:latest', + 'name': 'test/image', + 'version': '1.0', + 'labels': [{'name': 'foo', 'value': 'bar'}, {'name': 'labela', 'value': 'a'}], + 'osbs': { + 'repository': { + 'name': 'repo', + 'branch': 'branch' + } + } +} + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def run_osbs(descriptor, image_dir, mocker): + # We are mocking it, so do not require it at test time + mocker.patch('cekit.builders.osbs.OSBSBuilder.dependencies', return_value={}) + mocker.patch('cekit.builders.osbs.OSBSBuilder._wait_for_osbs_task') + mocker.patch('cekit.builders.osbs.DistGit.clean') + mocker.patch('cekit.builders.osbs.DistGit.prepare') + mocker.patch('cekit.tools.decision', return_value=True) + + mocker_check_call = mocker.patch.object(subprocess, 'check_output', side_effect=[ + b"true", # git rev-parse --is-inside-work-tree + b"/home/repos/path", # git rev-parse --show-toplevel + b"branch", # git rev-parse --abbrev-ref HEAD + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"", # git ls-files --others --exclude-standard + b"", # git diff-files --name-only + b"ssh://[email protected]/containers/somerepo", # git config --get remote.origin.url + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"1234", # brew call --python... + ]) + + with open(os.path.join(image_dir, 'config'), 'w') as fd: + fd.write("[common]\n") + fd.write("redhat = True") + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(descriptor, fd, default_flow_style=False) + + return run_cekit(image_dir, ['-v', + '--work-dir', image_dir, + '--config', + 'config', + 'build', + 'osbs']) + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def test_osbs_builder_kick_build_without_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + mocker.patch.object(subprocess, 'call', return_value=0) + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + ]) + + assert "No changes made to the code, committing skipped" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +def test_osbs_builder_kick_build_with_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=1) + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'commit', '-q', '-m', + 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb']), + mocker.call(['git', 'push', '-q', 'origin', 'branch']) + ]) + + assert "Commiting with message: 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb'" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +# https://github.com/cekit/cekit/issues/504 +def test_osbs_builder_add_help_file(tmpdir, mocker, caplog): + """ + Checks if help.md file is generated and added to dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=0) + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + descriptor['help'] = {'add': True} + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + assert os.path.exists(str(repo_dir.join('help.md'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'add', 'help.md']), + ]) + + assert "Image was built successfully in OSBS!" in caplog.text
help.md not added with OSBS builder If I add the following to my image definition ```help: add: true``` I can see the help.md generated and added in `target/image` with the "docker" builder, but it does not turn up in my dist-git repository with the osbs builder.
0.0
6b82c4adc0e2e1d2ddda66305c1c9abe7b91f407
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_with_push", "tests/test_integ_builder_osbs.py::test_osbs_builder_add_help_file" ]
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_without_push" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-07 11:28:22+00:00
mit
1,538
cekit__cekit-510
diff --git a/cekit/builders/docker_builder.py b/cekit/builders/docker_builder.py index 8addd4e..74347bf 100644 --- a/cekit/builders/docker_builder.py +++ b/cekit/builders/docker_builder.py @@ -162,7 +162,7 @@ class DockerBuilder(Builder): def _tag(self, docker_client, image_id, tags): for tag in tags: if ':' in tag: - img_repo, img_tag = tag.split(":") + img_repo, img_tag = tag.rsplit(":", 1) docker_client.tag(image_id, img_repo, tag=img_tag) else: docker_client.tag(image_id, tag) diff --git a/cekit/builders/osbs.py b/cekit/builders/osbs.py index f735056..808c404 100644 --- a/cekit/builders/osbs.py +++ b/cekit/builders/osbs.py @@ -140,12 +140,11 @@ class OSBSBuilder(Builder): if os.path.exists("container.yaml"): self._merge_container_yaml("container.yaml", os.path.join(self.dist_git_dir, "container.yaml")) - if os.path.exists("content_sets.yml"): - shutil.copy("content_sets.yml", - os.path.join(self.dist_git_dir, "content_sets.yml")) - if os.path.exists("fetch-artifacts-url.yaml"): - shutil.copy("fetch-artifacts-url.yaml", - os.path.join(self.dist_git_dir, "fetch-artifacts-url.yaml")) + + for special_file in ["content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(special_file): + shutil.copy(special_file, + os.path.join(self.dist_git_dir, special_file)) # Copy also every artifact for artifact in self.artifacts: @@ -232,7 +231,7 @@ class OSBSBuilder(Builder): try: subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as ex: - LOGGER.error("Cannot run '%s', ouput: '%s'" % (cmd, ex.output)) + LOGGER.error("Cannot run '%s', output: '%s'" % (cmd, ex.output)) raise CekitError("Cannot update sources.") LOGGER.info("Update finished.") @@ -345,10 +344,10 @@ class DistGit(object): if os.path.exists(self.output): with Chdir(self.output): LOGGER.info("Pulling latest changes in repo %s..." % self.repo) - subprocess.check_output(["git", "fetch"]) - subprocess.check_output( + subprocess.check_call(["git", "fetch"]) + subprocess.check_call( ["git", "checkout", "-f", self.branch], stderr=subprocess.STDOUT) - subprocess.check_output( + subprocess.check_call( ["git", "reset", "--hard", "origin/%s" % self.branch]) LOGGER.debug("Changes pulled") else: @@ -364,7 +363,7 @@ class DistGit(object): cmd += ['--user', user] cmd += ["-q", "clone", "-b", self.branch, self.repo, self.output] LOGGER.debug("Cloning: '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.debug("Repository %s cloned" % self.repo) def clean(self): @@ -382,12 +381,10 @@ class DistGit(object): def add(self): # Add new Dockerfile subprocess.check_call(["git", "add", "Dockerfile"]) - if os.path.exists("container.yaml"): - subprocess.check_call(["git", "add", "container.yaml"]) - if os.path.exists("content_sets.yml"): - subprocess.check_call(["git", "add", "content_sets.yml"]) - if os.path.exists("fetch-artifacts-url.yaml"): - subprocess.check_call(["git", "add", "fetch-artifacts-url.yaml"]) + + for f in ["container.yaml", "content_sets.yml", "fetch-artifacts-url.yaml", "help.md"]: + if os.path.exists(f): + subprocess.check_call(["git", "add", f]) for d in ["repos", "modules"]: # we probably do not care about non existing files and other errors here @@ -405,7 +402,7 @@ class DistGit(object): # Commit the change LOGGER.info("Commiting with message: '%s'" % commit_msg) - subprocess.check_output(["git", "commit", "-q", "-m", commit_msg]) + subprocess.check_call(["git", "commit", "-q", "-m", commit_msg]) untracked = subprocess.check_output( ["git", "ls-files", "--others", "--exclude-standard"]).decode("utf8") @@ -438,7 +435,7 @@ class DistGit(object): LOGGER.info("Pushing change to the upstream repository...") cmd = ["git", "push", "-q", "origin", self.branch] LOGGER.debug("Running command '%s'" % ' '.join(cmd)) - subprocess.check_output(cmd) + subprocess.check_call(cmd) LOGGER.info("Change pushed.") else: LOGGER.info("Changes are not pushed, exiting")
cekit/cekit
6b82c4adc0e2e1d2ddda66305c1c9abe7b91f407
diff --git a/tests/test_integ_builder_osbs.py b/tests/test_integ_builder_osbs.py new file mode 100644 index 0000000..3ae9568 --- /dev/null +++ b/tests/test_integ_builder_osbs.py @@ -0,0 +1,195 @@ +# -*- encoding: utf-8 -*- + +# pylint: disable=protected-access + +import logging +import os +import subprocess +import yaml + +import pytest + +from click.testing import CliRunner + +from cekit.cli import Cekit, Map, cli +from cekit.tools import Chdir +from cekit.config import Config +from cekit.errors import CekitError +from cekit.builders.osbs import OSBSBuilder +from cekit.tools import Map + +config = Config() + + [email protected](autouse=True) +def reset_config(): + config.cfg['common'] = {} + + +config = Config() +config.cfg['common'] = {'redhat': True} + +image_descriptor = { + 'schema_version': 1, + 'from': 'centos:latest', + 'name': 'test/image', + 'version': '1.0', + 'labels': [{'name': 'foo', 'value': 'bar'}, {'name': 'labela', 'value': 'a'}], + 'osbs': { + 'repository': { + 'name': 'repo', + 'branch': 'branch' + } + } +} + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def run_osbs(descriptor, image_dir, mocker): + # We are mocking it, so do not require it at test time + mocker.patch('cekit.builders.osbs.OSBSBuilder.dependencies', return_value={}) + mocker.patch('cekit.builders.osbs.OSBSBuilder._wait_for_osbs_task') + mocker.patch('cekit.builders.osbs.DistGit.clean') + mocker.patch('cekit.builders.osbs.DistGit.prepare') + mocker.patch('cekit.tools.decision', return_value=True) + + mocker_check_call = mocker.patch.object(subprocess, 'check_output', side_effect=[ + b"true", # git rev-parse --is-inside-work-tree + b"/home/repos/path", # git rev-parse --show-toplevel + b"branch", # git rev-parse --abbrev-ref HEAD + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"", # git ls-files --others --exclude-standard + b"", # git diff-files --name-only + b"ssh://[email protected]/containers/somerepo", # git config --get remote.origin.url + b"3b9283cb26b35511517ff5c0c3e11f490cba8feb", # git rev-parse HEAD + b"1234", # brew call --python... + ]) + + with open(os.path.join(image_dir, 'config'), 'w') as fd: + fd.write("[common]\n") + fd.write("redhat = True") + + with open(os.path.join(image_dir, 'image.yaml'), 'w') as fd: + yaml.dump(descriptor, fd, default_flow_style=False) + + return run_cekit(image_dir, ['-v', + '--work-dir', image_dir, + '--config', + 'config', + 'build', + 'osbs']) + + +def run_cekit(cwd, + parameters=['build', '--dry-run', 'docker'], + message=None): + with Chdir(cwd): + result = CliRunner().invoke(cli, parameters, catch_exceptions=False) + if message: + assert message in result.output + + return result + + +def test_osbs_builder_kick_build_without_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + mocker.patch.object(subprocess, 'call', return_value=0) + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + ]) + + assert "No changes made to the code, committing skipped" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +def test_osbs_builder_kick_build_with_push(tmpdir, mocker, caplog): + """ + Does not push sources to dist-git. This is the case when the + generated files are the same as already existing in dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=1) + + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'commit', '-q', '-m', + 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb']), + mocker.call(['git', 'push', '-q', 'origin', 'branch']) + ]) + + assert "Commiting with message: 'Sync with path, commit 3b9283cb26b35511517ff5c0c3e11f490cba8feb'" in caplog.text + assert "Image was built successfully in OSBS!" in caplog.text + + +# https://github.com/cekit/cekit/issues/504 +def test_osbs_builder_add_help_file(tmpdir, mocker, caplog): + """ + Checks if help.md file is generated and added to dist-git + """ + + caplog.set_level(logging.DEBUG, logger="cekit") + + source_dir = tmpdir.mkdir('source') + repo_dir = source_dir.mkdir('osbs').mkdir('repo') + + mocker.patch.object(subprocess, 'call', return_value=0) + mock_check_call = mocker.patch.object(subprocess, 'check_call') + + descriptor = image_descriptor.copy() + descriptor['help'] = {'add': True} + + run_osbs(descriptor, str(source_dir), mocker) + + assert os.path.exists(str(repo_dir.join('Dockerfile'))) is True + assert os.path.exists(str(repo_dir.join('help.md'))) is True + + mock_check_call.assert_has_calls( + [ + mocker.call(['git', 'add', 'Dockerfile']), + mocker.call(['git', 'add', 'help.md']), + ]) + + assert "Image was built successfully in OSBS!" in caplog.text diff --git a/tests/test_unit_builder_docker.py b/tests/test_unit_builder_docker.py index 26d6f3b..bdd8378 100644 --- a/tests/test_unit_builder_docker.py +++ b/tests/test_unit_builder_docker.py @@ -134,3 +134,19 @@ def test_docker_client_build_with_failure(mocker, caplog): docker_client_build.assert_called_once_with(path='something/image', pull=None, rm=True) assert "Docker: Step 3/159 : COPY modules /tmp/scripts/" in caplog.text assert "You can look inside the failed image by running 'docker run --rm -ti 81a88b63f47f bash'" in caplog.text + + +# https://github.com/cekit/cekit/issues/508 +def test_docker_tag(mocker): + builder = DockerBuilder(Map({'target': 'something'}), Map({'tags': ['foo', 'bar']})) + + docker_client_mock = mocker.Mock() + + builder._tag(docker_client_mock, "image_id", ["image:latest", "host:5000/repo/image:tag"]) + + assert len(docker_client_mock.tag.mock_calls) == 2 + + docker_client_mock.tag.assert_has_calls([ + mocker.call("image_id", "image", tag="latest"), + mocker.call("image_id", "host:5000/repo/image", tag="tag") + ])
docker build cannot handle more than one colon passed to the --tag option **Describe the bug** When passing more than one colon in the value for docker --tag, cekit will throw an error. This bug does not exist in 2.7, but does in 3.0. **To reproduce** This will fail: `cekit build --overrides-file branch-overrides.yaml docker --tag 172.30.1.1:5000/dward/rhdm74-kieserver:7.4.0` However, this will pass: `cekit build --overrides-file branch-overrides.yaml docker --tag 172.30.1.1/dward/rhdm74-kieserver:7.4.0` as will this: `cekit build --overrides-file branch-overrides.yaml docker --tag dward/rhdm74-kieserver:7.4.0` It's the colon for the port that is unexpected. **Expected behavior** No matter how many colons are in it, cekit should be able to tag the docker-built image with the tag provided. **Logs** Traceback (most recent call last): ``` File "/home/dward/Packages/cekit/3.0/bin/cekit", line 10, in <module> sys.exit(cli()) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 764, in __call__ return self.main(*args, **kwargs) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 717, in main rv = self.invoke(ctx) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/core.py", line 555, in invoke return callback(*args, **kwargs) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/click/decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/cli.py", line 106, in build_docker run_build(ctx, 'docker') File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/cli.py", line 282, in run_build run_command(ctx, builder_impl) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/cli.py", line 251, in run_command Cekit(common_params).run(clazz, params) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/cli.py", line 341, in run command.execute() File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/builder.py", line 60, in execute self.run() File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/builders/docker_builder.py", line 189, in run self._tag(docker_client, image_id, tags) File "/home/dward/Packages/cekit/3.0/lib/python3.7/site-packages/cekit/builders/docker_builder.py", line 165, in _tag img_repo, img_tag = tag.split(":") ValueError: too many values to unpack (expected 2) ``` This is the key part: **img_repo, img_tag = tag.split(":") ValueError: too many values to unpack (expected 2)** **Environment information:** - Operating system: Fedora 29 (Linux 5.0.10-200.fc29.x86_64) - CEKit version: Result of `cekit --version` 3.0.1 (pip3)
0.0
6b82c4adc0e2e1d2ddda66305c1c9abe7b91f407
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_with_push", "tests/test_integ_builder_osbs.py::test_osbs_builder_add_help_file", "tests/test_unit_builder_docker.py::test_docker_tag" ]
[ "tests/test_integ_builder_osbs.py::test_osbs_builder_kick_build_without_push" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-08 14:54:34+00:00
mit
1,539
cekit__cekit-523
diff --git a/cekit/generator/base.py b/cekit/generator/base.py index 3029050..318c38a 100644 --- a/cekit/generator/base.py +++ b/cekit/generator/base.py @@ -2,6 +2,7 @@ import logging import os +import re import platform import shutil @@ -116,6 +117,11 @@ class Generator(object): # was used to build the image image_labels.append(Label({'name': 'io.cekit.version', 'value': cekit_version})) + for label in image_labels: + if len(label.value) > 128: + # breaks the line each time it reaches 128 characters + label.value = "\\\n".join(re.findall("(?s).{,128}", label.value))[:] + # If we define the label in the image descriptor # we should *not* override it with value from # the root's key
cekit/cekit
715f6335931ade5883ef1829b6c857f9bbd4fa91
diff --git a/tests/test_unit_generator_docker.py b/tests/test_unit_generator_docker.py index 69c863f..bb2adf6 100644 --- a/tests/test_unit_generator_docker.py +++ b/tests/test_unit_generator_docker.py @@ -8,10 +8,12 @@ import os from contextlib import contextmanager import pytest +import yaml from cekit.config import Config from cekit.errors import CekitError from cekit.generator.docker import DockerGenerator +from cekit.descriptor import Image odcs_fake_resp = { @@ -104,6 +106,22 @@ def test_prepare_content_sets_should_not_fail_when_cs_is_empty(tmpdir): assert generator._prepare_content_sets({}) is False +def test_large_labels_should_break_lines(tmpdir): + image = Image(yaml.safe_load(""" + from: foo + name: test/foo + version: 1.9 + labels: + - name: 'the.large.label' + value: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pretium finibus lorem vitae pellentesque. Maecenas tincidunt amet. + """), 'foo') + with docker_generator(tmpdir) as generator: + generator.image = image + with cekit_config(redhat=True): + generator.add_build_labels() + assert image.labels[0].value == "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pretium finibus lorem vitae pellentesque. Maecenas tincidunt amet\\\n.\\\n" + + def test_prepare_content_sets_should_fail_when_cs_are_note_defined_for_current_platform(tmpdir, mocker): mocker.patch('cekit.generator.base.platform.machine', return_value="current_platform")
Labels with a very large value break container builds **Describe the bug** If the image.yaml descriptor has a very huge label value it will make cekit build fails (tested with docker and osbs and podman). Apparently, the label string value are being parsed to bytes somewhere and this issue happens: https://pastebin.com/fG2EdUKP I tried to do this, but the build failed with "Docker unknown instruction": `if line != build_log[-1]: if isinstance(line, bytes): line = line.decode('utf-8') ` With podman, this issue happens: > Error: error building at step {Env:[USER_NAME=apb USER_UID=1001 BASE_DIR=/opt/apb HOME=/opt/apb PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin container=oci JBOSS_IMAGE_NAME=rhpam-7/rhpam-apb JBOSS_IMAGE_VERSION=1.1] Command:label Args:[] Flags:[] Attrs:map[] Message:LABEL Original:LABEL }: LABEL requires at least one argument **To reproduce** use a image.yaml file descriptor with this label: https://pastebin.com/CbbxgMGm **Logs** Paste any logs you have, use CEKit verbose output: `cekit -v`. https://pastebin.com/fG2EdUKP **Environment information:** - Operating system: Fedora 29 - CEKit version: 3.0.1 **Additional context** This label is a requirement to work with APB (ansible playbook bundle)
0.0
715f6335931ade5883ef1829b6c857f9bbd4fa91
[ "tests/test_unit_generator_docker.py::test_large_labels_should_break_lines" ]
[ "tests/test_unit_generator_docker.py::test_prepare_content_sets_should_not_fail_when_cs_is_none", "tests/test_unit_generator_docker.py::test_prepare_content_sets_should_not_fail_when_cs_is_empty", "tests/test_unit_generator_docker.py::test_prepare_content_sets_should_fail_when_cs_are_note_defined_for_current_platform" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-05-27 14:00:59+00:00
mit
1,540
cekit__cekit-532
diff --git a/cekit/tools.py b/cekit/tools.py index cba0a21..32e6567 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -122,7 +122,7 @@ def get_brew_url(md5): url = 'http://download.devel.redhat.com/brewroot/packages/' + package + '/' + \ version.replace('-', '_') + '/' + release + '/maven/' + \ group_id.replace('.', '/') + '/' + \ - artifact_id.replace('.', '/') + '/' + version + '/' + filename + artifact_id + '/' + version + '/' + filename except subprocess.CalledProcessError as ex: LOGGER.error("Can't fetch artifacts details from brew: '%s'." % ex.output)
cekit/cekit
9455ee0b01c68cddb5aaad1fa1dbe8a85f0fb1f3
diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index 24ffe42..117de4d 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -180,23 +180,114 @@ def test_merge_run_cmd(): def brew_call_ok(*args, **kwargs): if 'listArchives' in args[0]: return """ - [ - { - "build_id": "build_id", - "filename": "filename", - "group_id": "group_id", - "artifact_id": "artifact_id", - "version": "version", - } - ]""".encode("utf8") + [ + { + "build_id": 179262, + "version": "20100527", + "type_name": "jar", + "artifact_id": "oauth", + "type_id": 1, + "checksum": "91c7c70579f95b7ddee95b2143a49b41", + "extra": null, + "filename": "oauth-20100527.jar", + "type_description": "Jar file", + "metadata_only": false, + "type_extensions": "jar war rar ear sar kar jdocbook jdocbook-style plugin", + "btype": "maven", + "checksum_type": 0, + "btype_id": 2, + "group_id": "net.oauth.core", + "buildroot_id": null, + "id": 105858, + "size": 44209 + } + ]""".encode("utf8") if 'getBuild' in args[0]: return """ - { - "package_name": "package_name", - "release": "release", - "state": 1 - } - """.encode("utf8") + { + "package_name": "net.oauth.core-oauth", + "extra": null, + "creation_time": "2011-09-12 05:38:16.978647", + "completion_time": "2011-09-12 05:38:16.978647", + "package_id": 18782, + "id": 179262, + "build_id": 179262, + "epoch": null, + "source": null, + "state": 1, + "version": "20100527", + "completion_ts": 1315805896.97865, + "owner_id": 1515, + "owner_name": "hfnukal", + "nvr": "net.oauth.core-oauth-20100527-1", + "start_time": null, + "creation_event_id": 4204830, + "start_ts": null, + "volume_id": 8, + "creation_ts": 1315805896.97865, + "name": "net.oauth.core-oauth", + "task_id": null, + "volume_name": "rhel-7", + "release": "1" + } + """.encode("utf8") + return "".encode("utf8") + + +def brew_call_ok_with_dot(*args, **kwargs): + if 'listArchives' in args[0]: + return """ + [ + { + "build_id": 410568, + "version": "1.0.4", + "type_name": "jar", + "artifact_id": "javax.json", + "type_id": 1, + "checksum": "569870f975deeeb6691fcb9bc02a9555", + "extra": null, + "filename": "javax.json-1.0.4.jar", + "type_description": "Jar file", + "metadata_only": false, + "type_extensions": "jar war rar ear sar kar jdocbook jdocbook-style plugin", + "btype": "maven", + "checksum_type": 0, + "btype_id": 2, + "group_id": "org.glassfish", + "buildroot_id": null, + "id": 863130, + "size": 85147 + } + ]""".encode("utf8") + if 'getBuild' in args[0]: + return """ + { + "package_name": "org.glassfish-javax.json", + "extra": null, + "creation_time": "2015-01-10 16:28:59.105878", + "completion_time": "2015-01-10 16:28:59.105878", + "package_id": 49642, + "id": 410568, + "build_id": 410568, + "epoch": null, + "source": null, + "state": 1, + "version": "1.0.4", + "completion_ts": 1420907339.10588, + "owner_id": 2679, + "owner_name": "pgallagh", + "nvr": "org.glassfish-javax.json-1.0.4-1", + "start_time": null, + "creation_event_id": 10432034, + "start_ts": null, + "volume_id": 8, + "creation_ts": 1420907339.10588, + "name": "org.glassfish-javax.json", + "task_id": null, + "volume_name": "rhel-7", + "release": "1" + } + """.encode("utf8") return "".encode("utf8") @@ -226,8 +317,7 @@ def brew_call_removed(*args, **kwargs): def test_get_brew_url(mocker): mocker.patch('subprocess.check_output', side_effect=brew_call_ok) url = tools.get_brew_url('aa') - assert url == "http://download.devel.redhat.com/brewroot/packages/package_name/" + \ - "version/release/maven/group_id/artifact_id/version/filename" + assert url == "http://download.devel.redhat.com/brewroot/packages/net.oauth.core-oauth/20100527/1/maven/net/oauth/core/oauth/20100527/oauth-20100527.jar" def test_get_brew_url_when_build_was_removed(mocker): @@ -256,6 +346,13 @@ def test_get_brew_url_no_kerberos(mocker, caplog): assert "Brew authentication failed, please make sure you have a valid Kerberos ticket" in caplog.text +# https://github.com/cekit/cekit/issues/531 +def test_get_brew_url_with_artifact_containing_dot(mocker): + mocker.patch('subprocess.check_output', side_effect=brew_call_ok_with_dot) + url = tools.get_brew_url('aa') + assert url == "http://download.devel.redhat.com/brewroot/packages/org.glassfish-javax.json/1.0.4/1/maven/org/glassfish/javax.json/1.0.4/javax.json-1.0.4.jar" + + @contextmanager def mocked_dependency_handler(mocker, data="ID=fedora\nNAME=somefedora\nVERSION=123"): dh = None
Dots in artifact names cause issues in generating proper fetch-artifacts-url.yaml file **Describe the bug** When an artifact contains dot in the name and it is used in the fetch-artifacts-url.yaml, the generated URL is wrong and instead of preserving the dot it is converted to a slash. Example artifact that is causeing troubles: ``` /usr/bin/brew call --json-output listArchives checksum=569870f975deeeb6691fcb9bc02a9555 type=maven [ { "build_id": 410568, "version": "1.0.4", "type_name": "jar", "artifact_id": "javax.json", "type_id": 1, "checksum": "569870f975deeeb6691fcb9bc02a9555", "extra": null, "filename": "javax.json-1.0.4.jar", "type_description": "Jar file", "metadata_only": false, "type_extensions": "jar war rar ear sar kar jdocbook jdocbook-style plugin", "btype": "maven", "checksum_type": 0, "btype_id": 2, "group_id": "org.glassfish", "buildroot_id": null, "id": 863130, "size": 85147 } ] ```
0.0
9455ee0b01c68cddb5aaad1fa1dbe8a85f0fb1f3
[ "tests/test_unit_tools.py::test_get_brew_url_with_artifact_containing_dot" ]
[ "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed", "tests/test_unit_tools.py::test_get_brew_url_no_kerberos", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_7", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_8", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-06-03 12:27:14+00:00
mit
1,541
cekit__cekit-579
diff --git a/cekit/tools.py b/cekit/tools.py index a53b9ec..9aaba1e 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -352,6 +352,14 @@ class DependencyHandler(object): self._handle_dependencies( DependencyHandler.EXTERNAL_CORE_DEPENDENCIES) + try: + import certifi # pylint: disable=unused-import + LOGGER.warning(("The certifi library (https://certifi.io/) was found, depending on the operating " + + "system configuration this may result in certificate validation issues")) + LOGGER.warning("Certificate Authority (CA) bundle in use: '{}'".format(certifi.where())) + except ImportError: + pass + def handle(self, o): """ Handles dependencies from selected object. If the object has 'dependencies' method,
cekit/cekit
c145339f0881a46cb94e1289d8f733f7c6604320
diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index 9ac8561..fba8b71 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -1,6 +1,7 @@ import logging import pytest import subprocess +import sys import yaml from contextlib import contextmanager @@ -550,3 +551,25 @@ def test_dependency_handler_check_for_executable_with_executable_fail_with_packa with pytest.raises(CekitError, match=r"^CEKit dependency: 'xyz' was not found, please provide the 'xyz-aaa' executable. To satisfy this requirement you can install the 'package-xyz' package.$"): handler._check_for_executable('xyz', 'xyz-aaa', 'package-xyz') + + +def test_handle_core_dependencies_no_certifi(mocker, caplog): + sys.modules['certifi'] = None + + with mocked_dependency_handler(mocker) as handler: + handler.handle_core_dependencies() + + assert "The certifi library (https://certifi.io/) was found, depending on the operating system configuration this may result in certificate validation issues" not in caplog.text + + +def test_handle_core_dependencies_with_certifi(mocker, caplog): + mock_certifi = mocker.Mock() + mock_certifi.where.return_value = 'a/path.pem' + + sys.modules['certifi'] = mock_certifi + + with mocked_dependency_handler(mocker) as handler: + handler.handle_core_dependencies() + + assert "The certifi library (https://certifi.io/) was found, depending on the operating system configuration this may result in certificate validation issues" in caplog.text + assert "Certificate Authority (CA) bundle in use: 'a/path.pem'" in caplog.text
Try to detect certifi package installs and warn user if custom installation is found The certifi library when installed locally provides a custom certificate store that can override the globally provided setting. We should try to find if certifi is installed and if yes, we should warn the user that certificate-related issues may appear. We probably should do this only when `--redhat` switch is used.
0.0
c145339f0881a46cb94e1289d8f733f7c6604320
[ "tests/test_unit_tools.py::test_handle_core_dependencies_with_certifi" ]
[ "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed", "tests/test_unit_tools.py::test_get_brew_url_no_kerberos", "tests/test_unit_tools.py::test_get_brew_url_with_artifact_containing_dot", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_7", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_8", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package", "tests/test_unit_tools.py::test_handle_core_dependencies_no_certifi" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-07-15 13:46:45+00:00
mit
1,542
cekit__cekit-803
diff --git a/cekit/builders/docker_builder.py b/cekit/builders/docker_builder.py index 903ffa5..38c59c3 100644 --- a/cekit/builders/docker_builder.py +++ b/cekit/builders/docker_builder.py @@ -53,8 +53,8 @@ class DockerBuilder(Builder): deps["python-docker"] = { "library": "docker", - "package": "python-docker-py", - "fedora": {"package": "python3-docker"}, + "package": "python3-docker", + "centos7": {"package": "python36-docker"}, } if params is not None and not params.no_squash: diff --git a/cekit/tools.py b/cekit/tools.py index 34821b1..0cac2de 100644 --- a/cekit/tools.py +++ b/cekit/tools.py @@ -400,6 +400,7 @@ class DependencyHandler(object): def __init__(self): self.os_release = {} self.platform = None + self.version = None os_release_path = "/etc/os-release" @@ -425,6 +426,7 @@ class DependencyHandler(object): or "ID" not in self.os_release or "NAME" not in self.os_release or "VERSION" not in self.os_release + or "VERSION_ID" not in self.os_release ): logger.warning( "You are running CEKit on an unknown platform. External dependencies suggestions may not work!" @@ -432,6 +434,7 @@ class DependencyHandler(object): return self.platform = self.os_release["ID"] + self.version = self.os_release["VERSION_ID"] if self.os_release["ID"] not in DependencyHandler.KNOWN_OPERATING_SYSTEMS: logger.warning( @@ -448,7 +451,7 @@ class DependencyHandler(object): ) ) - def _handle_dependencies(self, dependencies): + def _handle_dependencies(self, dependencies: dict) -> None: """ The dependencies provided is expected to be a dict in following format: @@ -456,7 +459,7 @@ class DependencyHandler(object): PACKAGE_ID: { 'package': PACKAGE_NAME, 'command': COMMAND_TO_TEST_FOR_PACKACGE_EXISTENCE }, } - Additionally every package can contain platform specific information, for example: + Additionally, every package can contain platform specific information, for example: { 'git': { @@ -470,6 +473,7 @@ class DependencyHandler(object): If the platform on which CEKit is currently running is available, it takes precedence before defaults. + The platform may be a simple name like e.g. 'fedora' or combined with the OS version e.g. 'centos7' """ if not dependencies: @@ -489,6 +493,13 @@ class DependencyHandler(object): executable = current_dependency[self.platform].get( "executable", executable ) + platform_release = f"{self.platform}{self.version}" + if platform_release in current_dependency: + package = current_dependency[platform_release].get("package", package) + library = current_dependency[platform_release].get("library", library) + executable = current_dependency[platform_release].get( + "executable", executable + ) logger.debug( "Checking if '{}' dependency is provided...".format(dependency) @@ -527,6 +538,7 @@ class DependencyHandler(object): logger.debug("All dependencies provided!") + # noinspection PyMethodMayBeStatic def _check_for_library(self, library): library_found = False @@ -597,7 +609,7 @@ class DependencyHandler(object): except ImportError: pass - def handle(self, o, params): + def handle(self, o, params) -> None: """ Handles dependencies from selected object. If the object has 'dependencies' method, it will be called to retrieve a set of dependencies to check for.
cekit/cekit
8462a81c711cbade1b59aa84cf5e773ff62bca7d
diff --git a/cekit/test/behave_runner.py b/cekit/test/behave_runner.py index 24cd435..4063c29 100644 --- a/cekit/test/behave_runner.py +++ b/cekit/test/behave_runner.py @@ -23,8 +23,7 @@ class BehaveTestRunner(object): deps["python-behave"] = { "library": "behave", - "package": "python2-behave", - "fedora": {"package": "python3-behave"}, + "package": "python3-behave", } return deps diff --git a/tests/test_unit_tools.py b/tests/test_unit_tools.py index f337365..a2d5779 100644 --- a/tests/test_unit_tools.py +++ b/tests/test_unit_tools.py @@ -590,7 +590,27 @@ def test_get_brew_url_with_artifact_containing_dot(mocker): @contextmanager -def mocked_dependency_handler(mocker, data="ID=fedora\nNAME=somefedora\nVERSION=123"): +def mocked_dependency_handler_centos( + mocker, data="ID=centos\nNAME=somecentos\nVERSION=7 (Core)\nVERSION_ID=7" +): + dh = None + + with mocker.mock_module.patch("cekit.tools.os.path.exists") as exists_mock: + exists_mock.return_value = True + with mocker.mock_module.patch( + "cekit.tools.open", mocker.mock_open(read_data=data) + ): + dh = tools.DependencyHandler() + try: + yield dh + finally: + pass + + +@contextmanager +def mocked_dependency_handler( + mocker, data="ID=fedora\nNAME=somefedora\nVERSION=123 (Test)\nVERSION_ID=123" +): dh = None with mocker.mock_module.patch("cekit.tools.os.path.exists") as exists_mock: @@ -752,6 +772,33 @@ def test_dependency_handler_handle_dependencies_with_executable_and_package_on_k assert "All dependencies provided!" in caplog.text +def test_dependency_handler_handle_dependencies_with_platform_and_version_specific_package( + mocker, caplog +): + caplog.set_level(logging.DEBUG, logger="cekit") + + deps = {} + + deps["xyz"] = { + "executable": "xyz-aaa", + "package": "python-xyz-aaa", + "centos7": {"package": "python-centos-xyz-aaa"}, + } + + with mocked_dependency_handler_centos(mocker) as handler: + mocker.patch.object(handler, "_check_for_executable") + mocker.spy(handler, "_check_for_executable") + handler._handle_dependencies(deps) + + print(caplog.text) + handler._check_for_executable.assert_called_once_with( + "xyz", "xyz-aaa", "python-centos-xyz-aaa" + ) + + assert "Checking if 'xyz' dependency is provided..." in caplog.text + assert "All dependencies provided!" in caplog.text + + def test_dependency_handler_handle_dependencies_with_platform_specific_package( mocker, caplog ):
dependency handling references python2 dependencies Similar to https://github.com/cekit/behave-test-steps/issues/40 there are references to Python2 dependencies e.g. ``` deps["python-docker"] = { "library": "docker", "package": "python-docker-py", "fedora": {"package": "python3-docker"}, } ``` EPEL 7 differs from EPEL 8 in terms of Python 3 packages (but within CEKit they are only recognised as both being under the CentOS platform). This could be partially resolved within CEKit if the package determination in tools.py also allowed <platform><release as well as <platform> e.g. centos7 , so we could then have: ``` deps["python-docker"] = { "library": "docker", "package": "python3-docker", "centos7": {"package": "python36-docker"}, } ```
0.0
8462a81c711cbade1b59aa84cf5e773ff62bca7d
[ "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_and_version_specific_package" ]
[ "tests/test_unit_tools.py::test_merging_description_image", "tests/test_unit_tools.py::test_merging_description_osbs", "tests/test_unit_tools.py::test_merging_description_modules", "tests/test_unit_tools.py::test_merging_description_override", "tests/test_unit_tools.py::test_merging_plain_descriptors", "tests/test_unit_tools.py::test_merging_emdedded_descriptors", "tests/test_unit_tools.py::test_merging_plain_lists", "tests/test_unit_tools.py::test_merging_plain_list_of_list", "tests/test_unit_tools.py::test_merging_list_of_descriptors", "tests/test_unit_tools.py::test_merge_run_cmd", "tests/test_unit_tools.py::test_get_image_version_with_registry", "tests/test_unit_tools.py::test_get_image_version", "tests/test_unit_tools.py::test_get_image_version_with_floating", "tests/test_unit_tools.py::test_get_brew_url", "tests/test_unit_tools.py::test_get_brew_url_when_build_was_removed", "tests/test_unit_tools.py::test_get_brew_url_no_kerberos", "tests/test_unit_tools.py::test_get_brew_url_with_artifact_containing_dot", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_with_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_7", "tests/test_unit_tools.py::test_dependency_handler_on_rhel_8", "tests/test_unit_tools.py::test_dependency_handler_init_on_known_env", "tests/test_unit_tools.py::test_dependency_handler_init_on_unknown_env_without_os_release_file", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_doesnt_fail_without_deps", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_only_failed", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_executable_and_package_on_known_platform", "tests/test_unit_tools.py::test_dependency_handler_handle_dependencies_with_platform_specific_package", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_only", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail", "tests/test_unit_tools.py::test_dependency_handler_check_for_executable_with_executable_fail_with_package", "tests/test_unit_tools.py::test_handle_core_dependencies_no_certifi", "tests/test_unit_tools.py::test_handle_core_dependencies_with_certifi", "tests/test_unit_tools.py::test_run_wrapper_whitespace", "tests/test_unit_tools.py::test_run_wrapper_no_capture", "tests/test_unit_tools.py::test_run_wrapper_capture_error" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-07-13 13:22:00+00:00
mit
1,543
celery__billiard-230
diff --git a/CHANGES.txt b/CHANGES.txt index 9e6c09e..e2366da 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,16 @@ +3.5.0.3 - 2017-07-16 +-------------------- + +- Adds Process._authkey alias to .authkey for 2.7 compat. +- Remove superfluous else clause from max_memory_per_child_check. +- Document and test all supported Python versions. +- Extend 'Process' to be compatible with < Py3.5. +- Use a properly initialized logger in pool.py error logging. +- _trywaitkill can now kill a whole process group if the worker process declares itself as a group leader. +- Fix cpython issue 14881 (See http://bugs.python.org/issue14881). +- Fix for a crash on windows. +- Fix messaging in case of worker exceeds max memory. + 3.5.0.2 - 2016-10-03 -------------------- diff --git a/billiard/__init__.py b/billiard/__init__.py index ada838a..9c7c92a 100644 --- a/billiard/__init__.py +++ b/billiard/__init__.py @@ -22,7 +22,7 @@ from __future__ import absolute_import import sys from . import context -VERSION = (3, 5, 0, 2) +VERSION = (3, 5, 0, 3) __version__ = '.'.join(map(str, VERSION[0:4])) + "".join(VERSION[4:]) __author__ = 'R Oudkerk / Python Software Foundation' __author_email__ = '[email protected]' diff --git a/billiard/heap.py b/billiard/heap.py index 278bfe5..b7581ce 100644 --- a/billiard/heap.py +++ b/billiard/heap.py @@ -73,11 +73,12 @@ else: self.size = size self.fd = fd if fd == -1: - self.fd, name = tempfile.mkstemp( - prefix='pym-%d-' % (os.getpid(), ), - dir=util.get_temp_dir(), - ) if PY3: + self.fd, name = tempfile.mkstemp( + prefix='pym-%d-' % (os.getpid(),), + dir=util.get_temp_dir(), + ) + os.unlink(name) util.Finalize(self, os.close, (self.fd,)) with io.open(self.fd, 'wb', closefd=False) as f: @@ -90,6 +91,10 @@ else: f.write(b'\0' * (size % bs)) assert f.tell() == size else: + name = tempfile.mktemp( + prefix='pym-%d-' % (os.getpid(),), + dir=util.get_temp_dir(), + ) self.fd = os.open( name, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600, ) diff --git a/billiard/pool.py b/billiard/pool.py index 2734f2a..1bb9d10 100644 --- a/billiard/pool.py +++ b/billiard/pool.py @@ -47,7 +47,7 @@ from .five import Empty, Queue, range, values, reraise, monotonic from .util import Finalize, debug MAXMEM_USED_FMT = """\ -child process exiting after exceeding memory limit ({0}KiB / {0}KiB) +child process exiting after exceeding memory limit ({0}KiB / {1}KiB) """ PY3 = sys.version_info[0] == 3 diff --git a/billiard/sharedctypes.py b/billiard/sharedctypes.py index 6334661..97675df 100644 --- a/billiard/sharedctypes.py +++ b/billiard/sharedctypes.py @@ -155,7 +155,7 @@ def rebuild_ctype(type_, wrapper, length): obj = type_.from_buffer(buf) else: obj = type_.from_address(wrapper.get_address()) - obj._wrapper = wrapper + obj._wrapper = wrapper return obj #
celery/billiard
bfe2dc6387853595ef8877809c1404fe4959519d
diff --git a/t/unit/test_values.py b/t/unit/test_values.py new file mode 100644 index 0000000..4b0bfc2 --- /dev/null +++ b/t/unit/test_values.py @@ -0,0 +1,77 @@ +from __future__ import absolute_import +import pytest + +from billiard import Value, RawValue, Lock, Process + + +class test_values: + + codes_values = [ + ('i', 4343, 24234), + ('d', 3.625, -4.25), + ('h', -232, 234), + ('c', 'x'.encode('latin'), 'y'.encode('latin')) + ] + + def test_issue_229(self): + """Test fix for issue #229""" + + a = Value('i', 0) + b = Value('i', 0) + + a.value = 5 + assert a.value == 5 + assert b.value == 0 + + @classmethod + def _test(cls, values): + for sv, cv in zip(values, cls.codes_values): + sv.value = cv[2] + + def test_value(self, raw=False): + if raw: + values = [RawValue(code, value) + for code, value, _ in self.codes_values] + else: + values = [Value(code, value) + for code, value, _ in self.codes_values] + + for sv, cv in zip(values, self.codes_values): + assert sv.value == cv[1] + + proc = Process(target=self._test, args=(values,)) + proc.daemon = True + proc.start() + proc.join() + + for sv, cv in zip(values, self.codes_values): + assert sv.value == cv[2] + + def test_rawvalue(self): + self.test_value(raw=True) + + def test_getobj_getlock(self): + val1 = Value('i', 5) + lock1 = val1.get_lock() + obj1 = val1.get_obj() + + val2 = Value('i', 5, lock=None) + lock2 = val2.get_lock() + obj2 = val2.get_obj() + + lock = Lock() + val3 = Value('i', 5, lock=lock) + lock3 = val3.get_lock() + obj3 = val3.get_obj() + assert lock == lock3 + + arr4 = Value('i', 5, lock=False) + assert not hasattr(arr4, 'get_lock') + assert not hasattr(arr4, 'get_obj') + + with pytest.raises(AttributeError): + Value('i', 5, lock='navalue') + + arr5 = RawValue('i', 5) + assert not hasattr(arr5, 'get_lock') + assert not hasattr(arr5, 'get_obj')
multiple billiard.Value instances sharing the same state **Problem description** When using multiple instances of `billiard.Value` and changing one variable's value, the other one is changed as well. In the example below when I update the variable `value`, `done` is set to the same value as well. When replacing `billiard` with `multiprocessing` the example works as expected. **Example** See [below](#issuecomment-311695221) for an easier example. ```python import ctypes import time from billiard import Pool, Value def foo(): for i in range(10): value.value = i time.sleep(1) done.value = True def bar(): while True: print(value.value, '\t', done.value) time.sleep(0.5) if __name__ == '__main__': value = Value(ctypes.c_int, 0) done = Value(ctypes.c_bool, False) with Pool() as pool: pool.apply_async(bar) pool.apply(foo) ``` **Expected output** ``` 0 False 0 False 1 False 1 False 1 False 2 False 3 False 3 False 4 False 4 False 5 False 5 False 6 False 6 False 7 False 7 False 8 False 8 False 9 False 9 False 9 True ``` **Actual output** ``` 0 False 0 False 1 True 1 True 2 True 2 True 3 True 3 True 4 True 4 True 5 True 5 True 6 True 6 True 7 True 7 True 8 True 8 True 9 True 9 True ``` **Versions** ```shell % pip freeze | grep billiard billiard==3.5.0.2 % python --version Python 3.6.0 % uname -a Darwin HOST 16.4.0 Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64 % sw_vers -productVersion 10.12.3 ```
0.0
bfe2dc6387853595ef8877809c1404fe4959519d
[ "t/unit/test_values.py::test_values::test_issue_229", "t/unit/test_values.py::test_values::test_value", "t/unit/test_values.py::test_values::test_rawvalue" ]
[ "t/unit/test_values.py::test_values::test_getobj_getlock" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-06-28 15:37:39+00:00
bsd-3-clause
1,544
celery__billiard-344
diff --git a/t/skip.py b/t/skip.py new file mode 100644 index 0000000..c348385 --- /dev/null +++ b/t/skip.py @@ -0,0 +1,13 @@ +import sys + +import pytest + +if_win32 = pytest.mark.skipif( + sys.platform.startswith('win32'), + reason='Does not work on Windows' +) + +unless_win32 = pytest.mark.skipif( + not sys.platform.startswith('win32'), + reason='Requires Windows to work' +)
celery/billiard
0713348618a72dfd1eec376adc867f228f6c5567
diff --git a/requirements/test.txt b/requirements/test.txt index 71d9213..ad102df 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,4 +1,3 @@ -case>=1.3.1 pytest<6.2 # psutil is pinned since this is the last version that supports pypy2 psutil==5.8.0 diff --git a/t/unit/test_common.py b/t/unit/test_common.py index 2951342..df505e5 100644 --- a/t/unit/test_common.py +++ b/t/unit/test_common.py @@ -6,8 +6,9 @@ import signal from contextlib import contextmanager from time import time +from unittest.mock import patch, Mock, call -from case import Mock, call, patch, skip +from t import skip from billiard.common import ( _shutdown_cleanup, diff --git a/t/unit/test_win32.py b/t/unit/test_win32.py index 463bf07..4c4e287 100644 --- a/t/unit/test_win32.py +++ b/t/unit/test_win32.py @@ -3,10 +3,10 @@ from __future__ import absolute_import import pytest import signal -from case import skip from billiard.util import set_pdeathsig, get_pdeathsig from billiard.compat import _winapi +from t import skip @skip.unless_win32()
3.6.4.0: billiard still uses `nose` which is deprecated https://nose.readthedocs.io/en/latest/
0.0
0713348618a72dfd1eec376adc867f228f6c5567
[ "t/unit/test_common.py::test_reset_signals::test_shutdown_handler", "t/unit/test_common.py::test_reset_signals::test_does_not_reset_ignored_signal", "t/unit/test_common.py::test_reset_signals::test_does_not_reset_if_current_is_None", "t/unit/test_common.py::test_reset_signals::test_resets_for_SIG_DFL", "t/unit/test_common.py::test_reset_signals::test_resets_for_obj", "t/unit/test_common.py::test_reset_signals::test_handles_errors", "t/unit/test_common.py::test_restart_state::test_raises", "t/unit/test_common.py::test_restart_state::test_time_passed_resets_counter" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-11-11 17:40:44+00:00
bsd-3-clause
1,545
celery__billiard-372
diff --git a/billiard/einfo.py b/billiard/einfo.py index de385c0..640ddd8 100644 --- a/billiard/einfo.py +++ b/billiard/einfo.py @@ -91,16 +91,24 @@ class Traceback: class RemoteTraceback(Exception): def __init__(self, tb): self.tb = tb + def __str__(self): return self.tb -class ExceptionWithTraceback: + +class ExceptionWithTraceback(Exception): def __init__(self, exc, tb): self.exc = exc self.tb = '\n"""\n%s"""' % tb + super().__init__() + + def __str__(self): + return self.tb + def __reduce__(self): return rebuild_exc, (self.exc, self.tb) + def rebuild_exc(exc, tb): exc.__cause__ = RemoteTraceback(tb) return exc
celery/billiard
69c576df48d062457baccc06a016d52356755133
diff --git a/t/unit/test_einfo.py b/t/unit/test_einfo.py new file mode 100644 index 0000000..5d2482d --- /dev/null +++ b/t/unit/test_einfo.py @@ -0,0 +1,28 @@ +import pickle +import logging +from billiard.einfo import ExceptionInfo + +logger = logging.getLogger(__name__) + + +def test_exception_info_log_before_pickle(caplog): + try: + raise RuntimeError("some message") + except Exception: + exception = ExceptionInfo().exception + + logger.exception("failed", exc_info=exception) + assert ' raise RuntimeError("some message")' in caplog.text + assert "RuntimeError: some message" in caplog.text + + +def test_exception_info_log_after_pickle(caplog): + try: + raise RuntimeError("some message") + except Exception: + exception = ExceptionInfo().exception + exception = pickle.loads(pickle.dumps(exception)) + + logger.exception("failed", exc_info=exception) + assert ' raise RuntimeError("some message")' in caplog.text + assert "RuntimeError: some message" in caplog.text
ExceptionWithTraceback object has no attribute __cause__ Platform: Windows Python: 3.8.6 Celery: 5.3.0b1 billiard: 4.0.1 ## Description I have a celery task that raises `RuntimeError("requires pyicat-plus")`. In `celery.app.trace` the exception gets [logged](https://github.com/celery/celery/blob/feaad3f9fdf98d0453a07a68e307e48c6c3c2550/celery/app/trace.py#L262) before sending a `task_failure` signal. This causes an error in the logging module. ## Reason Because of https://github.com/celery/billiard/pull/368 the exception in `Traceinfo.handle_failure` is no longer an instance of a class derived from `Exception` but it is an instance of `ExceptionWithTraceback` which does not have a `__cause__` attribute. ## Possible solution `ExceptionWithTraceback` should derive from `Exception` (for local usage like logging) while at the same time keeping its pickling behavior to preserve the remote traceback. ## Traceback ``` C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py:657: RuntimeWarning: Exception raised outside body: AttributeError("'ExceptionWithTraceback' object has no attribute '__cause__'"): Traceback (most recent call last): File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 448, in trace_task R = retval = fun(*args, **kwargs) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\ewoksjob\apps\ewoks.py", line 20, in wrapper return method(self, *args, **kwargs) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\ewoksjob\apps\ewoks.py", line 30, in wrapper return method(self, *args, **kwargs) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\ewoksjob\apps\ewoks.py", line 59, in execute_and_upload_workflow return tasks.execute_and_upload_graph(*args, **kwargs) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\ewoksjob\tasks\execute_and_upload.py", line 28, in execute_and_upload_graph raise RuntimeError("requires pyicat-plus") RuntimeError: requires pyicat-plus During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 465, in trace_task I, R, state, retval = on_error(task_request, exc) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 376, in on_error R = I.handle_error_state( File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 175, in handle_error_state return { File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 234, in handle_failure self._log_error(task, req, einfo) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\celery\app\trace.py", line 262, in _log_error logger.log(policy.severity, policy.format.strip(), context, File "C:\python\3.8\lib\logging\__init__.py", line 1500, in log self._log(level, msg, args, **kwargs) File "C:\python\3.8\lib\logging\__init__.py", line 1577, in _log self.handle(record) File "C:\python\3.8\lib\logging\__init__.py", line 1587, in handle self.callHandlers(record) File "C:\python\3.8\lib\logging\__init__.py", line 1649, in callHandlers hdlr.handle(record) File "C:\python\3.8\lib\logging\__init__.py", line 950, in handle self.emit(record) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\_pytest\logging.py", line 342, in emit super().emit(record) File "C:\python\3.8\lib\logging\__init__.py", line 1089, in emit self.handleError(record) File "C:\python\3.8\lib\logging\__init__.py", line 1081, in emit msg = self.format(record) File "C:\python\3.8\lib\logging\__init__.py", line 925, in format return fmt.format(record) File "C:\gitlab-runner\builds\L4y3rgSY\0\workflow\ewoks\ewoksjob\build_venv\lib\site-packages\_pytest\logging.py", line 113, in format return super().format(record) File "C:\python\3.8\lib\logging\__init__.py", line 672, in format record.exc_text = self.formatException(record.exc_info) File "C:\python\3.8\lib\logging\__init__.py", line 622, in formatException traceback.print_exception(ei[0], ei[1], tb, None, sio) File "C:\python\3.8\lib\traceback.py", line 103, in print_exception for line in TracebackException( File "C:\python\3.8\lib\traceback.py", line 479, in __init__ if (exc_value and exc_value.__cause__ is not None AttributeError: 'ExceptionWithTraceback' object has no attribute '__cause__' ```
0.0
69c576df48d062457baccc06a016d52356755133
[ "t/unit/test_einfo.py::test_exception_info_log_before_pickle" ]
[ "t/unit/test_einfo.py::test_exception_info_log_after_pickle" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-08-02 15:02:53+00:00
bsd-3-clause
1,546
celery__py-amqp-344
diff --git a/amqp/transport.py b/amqp/transport.py index 3eec88f..b183120 100644 --- a/amqp/transport.py +++ b/amqp/transport.py @@ -354,9 +354,9 @@ class SSLTransport(_AbstractTransport): def _wrap_socket_sni(self, sock, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, - do_handshake_on_connect=False, + ca_certs=None, do_handshake_on_connect=False, suppress_ragged_eofs=True, server_hostname=None, - ssl_version=ssl.PROTOCOL_TLS): + ciphers=None, ssl_version=ssl.PROTOCOL_TLS): """Socket wrap with SNI headers. stdlib `ssl.SSLContext.wrap_socket` method augmented with support for @@ -373,6 +373,10 @@ class SSLTransport(_AbstractTransport): context = ssl.SSLContext(ssl_version) if certfile is not None: context.load_cert_chain(certfile, keyfile) + if ca_certs is not None: + context.load_verify_locations(ca_certs) + if ciphers: + context.set_ciphers(ciphers) if cert_reqs != ssl.CERT_NONE: context.check_hostname = True # Set SNI headers if supported
celery/py-amqp
8e5ddd41b776f31faea6a47fcc757b76c567b007
diff --git a/t/unit/test_transport.py b/t/unit/test_transport.py index d94a520..5eec1ab 100644 --- a/t/unit/test_transport.py +++ b/t/unit/test_transport.py @@ -4,7 +4,7 @@ import re import socket import struct from struct import pack -from unittest.mock import ANY, MagicMock, Mock, call, patch +from unittest.mock import ANY, MagicMock, Mock, call, patch, sentinel import pytest @@ -638,14 +638,136 @@ class test_SSLTransport: ctx.wrap_socket.assert_called_with(sock, f=1) def test_wrap_socket_sni(self): + # testing default values of _wrap_socket_sni() sock = Mock() - with patch('ssl.SSLContext.wrap_socket') as mock_ssl_wrap: - self.t._wrap_socket_sni(sock) - mock_ssl_wrap.assert_called_with(sock=sock, - server_side=False, - do_handshake_on_connect=False, - suppress_ragged_eofs=True, - server_hostname=None) + with patch( + 'ssl.SSLContext.wrap_socket', + return_value=sentinel.WRAPPED_SOCKET) as mock_ssl_wrap: + ret = self.t._wrap_socket_sni(sock) + + mock_ssl_wrap.assert_called_with(sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=None) + + assert ret == sentinel.WRAPPED_SOCKET + + def test_wrap_socket_sni_certfile(self): + # testing _wrap_socket_sni() with parameters certfile and keyfile + sock = Mock() + with patch( + 'ssl.SSLContext.wrap_socket', + return_value=sentinel.WRAPPED_SOCKET) as mock_ssl_wrap, \ + patch('ssl.SSLContext.load_cert_chain') as mock_load_cert_chain: + ret = self.t._wrap_socket_sni( + sock, keyfile=sentinel.KEYFILE, certfile=sentinel.CERTFILE) + + mock_load_cert_chain.assert_called_with( + sentinel.CERTFILE, sentinel.KEYFILE) + mock_ssl_wrap.assert_called_with(sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=None) + + assert ret == sentinel.WRAPPED_SOCKET + + def test_wrap_socket_ca_certs(self): + # testing _wrap_socket_sni() with parameter ca_certs + sock = Mock() + with patch( + 'ssl.SSLContext.wrap_socket', + return_value=sentinel.WRAPPED_SOCKET + ) as mock_ssl_wrap, patch( + 'ssl.SSLContext.load_verify_locations' + ) as mock_load_verify_locations: + ret = self.t._wrap_socket_sni(sock, ca_certs=sentinel.CA_CERTS) + + mock_load_verify_locations.assert_called_with(sentinel.CA_CERTS) + mock_ssl_wrap.assert_called_with(sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=None) + + assert ret == sentinel.WRAPPED_SOCKET + + def test_wrap_socket_ciphers(self): + # testing _wrap_socket_sni() with parameter ciphers + sock = Mock() + with patch( + 'ssl.SSLContext.wrap_socket', + return_value=sentinel.WRAPPED_SOCKET) as mock_ssl_wrap, \ + patch('ssl.SSLContext.set_ciphers') as mock_set_ciphers: + ret = self.t._wrap_socket_sni(sock, ciphers=sentinel.CIPHERS) + + mock_set_ciphers.assert_called_with(sentinel.CIPHERS) + mock_ssl_wrap.assert_called_with(sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=None) + assert ret == sentinel.WRAPPED_SOCKET + + def test_wrap_socket_sni_cert_reqs(self): + # testing _wrap_socket_sni() with parameter cert_reqs + sock = Mock() + with patch('ssl.SSLContext') as mock_ssl_context_class: + wrap_socket_method_mock = mock_ssl_context_class().wrap_socket + wrap_socket_method_mock.return_value = sentinel.WRAPPED_SOCKET + ret = self.t._wrap_socket_sni(sock, cert_reqs=sentinel.CERT_REQS) + + wrap_socket_method_mock.assert_called_with( + sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=None + ) + assert mock_ssl_context_class().check_hostname is True + assert ret == sentinel.WRAPPED_SOCKET + + def test_wrap_socket_sni_setting_sni_header(self): + # testing _wrap_socket_sni() with setting SNI header + sock = Mock() + with patch('ssl.SSLContext') as mock_ssl_context_class, \ + patch('ssl.HAS_SNI', new=True): + # SSL module supports SNI + wrap_socket_method_mock = mock_ssl_context_class().wrap_socket + wrap_socket_method_mock.return_value = sentinel.WRAPPED_SOCKET + ret = self.t._wrap_socket_sni( + sock, cert_reqs=sentinel.CERT_REQS, + server_hostname=sentinel.SERVER_HOSTNAME + ) + wrap_socket_method_mock.assert_called_with( + sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=sentinel.SERVER_HOSTNAME + ) + assert mock_ssl_context_class().verify_mode == sentinel.CERT_REQS + assert ret == sentinel.WRAPPED_SOCKET + + with patch('ssl.SSLContext') as mock_ssl_context_class, \ + patch('ssl.HAS_SNI', new=False): + # SSL module does not support SNI + wrap_socket_method_mock = mock_ssl_context_class().wrap_socket + wrap_socket_method_mock.return_value = sentinel.WRAPPED_SOCKET + ret = self.t._wrap_socket_sni( + sock, cert_reqs=sentinel.CERT_REQS, + server_hostname=sentinel.SERVER_HOSTNAME + ) + wrap_socket_method_mock.assert_called_with( + sock=sock, + server_side=False, + do_handshake_on_connect=False, + suppress_ragged_eofs=True, + server_hostname=sentinel.SERVER_HOSTNAME + ) + assert mock_ssl_context_class().verify_mode != sentinel.CERT_REQS + assert ret == sentinel.WRAPPED_SOCKET def test_shutdown_transport(self): self.t.sock = None
SSLTransport error: unexpected keyword argument 'ca_certs' Using amqp version 5.0.1, I discovered an SSLTransport error. When I use amqp version 5.0.0b1, SSL works just fine. Here's the error I get when using amqp==5.0.1: `/usr/local/lib/python3.8/dist-packages/kombu/connection.py:283: in channel chan = self.transport.create_channel(self.connection) /usr/local/lib/python3.8/dist-packages/kombu/connection.py:858: in connection return self._ensure_connection( /usr/local/lib/python3.8/dist-packages/kombu/connection.py:435: in _ensure_connection return retry_over_time( /usr/local/lib/python3.8/dist-packages/kombu/utils/functional.py:325: in retry_over_time return fun(*args, **kwargs) /usr/local/lib/python3.8/dist-packages/kombu/connection.py:866: in _connection_factory self._connection = self._establish_connection() /usr/local/lib/python3.8/dist-packages/kombu/connection.py:801: in _establish_connection conn = self.transport.establish_connection() /usr/local/lib/python3.8/dist-packages/kombu/transport/pyamqp.py:128: in establish_connection conn.connect() /usr/local/lib/python3.8/dist-packages/amqp/connection.py:314: in connect self.transport.connect() /usr/local/lib/python3.8/dist-packages/amqp/transport.py:77: in connect self._init_socket( /usr/local/lib/python3.8/dist-packages/amqp/transport.py:188: in _init_socket self._setup_transport() /usr/local/lib/python3.8/dist-packages/amqp/transport.py:323: in _setup_transport self.sock = self._wrap_socket(self.sock, **self.sslopts) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <amqp.transport.SSLTransport object at 0x7f8a0083a370> sock = <socket.socket fd=11, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 41008), raddr=('127.0.0.1', 5671)> context = None sslopts = {'ca_certs': '/home/cameron/Defense/tls-gen/basic/result/ca_certificate.pem', 'cert_reqs': <VerifyMode.CERT_REQUIRED: ...e/tls-gen/basic/result/client_certificate.pem', 'keyfile': '/home/cameron/Defense/tls-gen/basic/result/client_key.pem'} def _wrap_socket(self, sock, context=None, **sslopts): if context: return self._wrap_context(sock, sslopts, **context) > return self._wrap_socket_sni(sock, **sslopts) E TypeError: _wrap_socket_sni() got an unexpected keyword argument 'ca_certs' /usr/local/lib/python3.8/dist-packages/amqp/transport.py:330: TypeError ----------------------------------------------------------- Captured stdout call ----------------------------------------------------------- 2020-10-28 16:46:54: INFO: Consumer successfully connected to kombu server at localhost:5671 2020-10-28 16:46:54: ERROR: Failed to initialize rabbit consumer connection: Traceback (most recent call last): TypeError: _wrap_socket_sni() got an unexpected keyword argument 'ca_certs'` Looking at `py-amqp/amqp/transport.py`, the parameters for the method `_wrap_socket_sni` for amqp==5.0.1, it doesn't include `ca_certs`. On amqp==5.0.0b1, the method _wrap_socket_sni` does include `ca_certs` as a parameter. Is this a bug or was this left out by accident? Here are the links to amqp version 5.0.1 and 5.0.0b1 of `py-amqp/amqp/transport.py` with the line numbers highlighting the method: amqp==5.0.1: https://github.com/celery/py-amqp/blob/93e4f3a2990f2ed1a6da861c99c7f0a3b0d32160/amqp/transport.py#L337 amqp==5.0.0b1: https://github.com/celery/py-amqp/blob/c5fe7daaf379cfbcccbe81fcd1ea12807274f8fb/amqp/transport.py#L339
0.0
8e5ddd41b776f31faea6a47fcc757b76c567b007
[ "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ca_certs", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ciphers" ]
[ "t/unit/test_transport.py::test_SSLTransport::test_repr_disconnected", "t/unit/test_transport.py::test_SSLTransport::test_repr_connected", "t/unit/test_transport.py::test_SSLTransport::test_setup_transport", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket", "t/unit/test_transport.py::test_SSLTransport::test_wrap_context", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_certfile", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_cert_reqs", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_setting_sni_header", "t/unit/test_transport.py::test_SSLTransport::test_shutdown_transport", "t/unit/test_transport.py::test_SSLTransport::test_read_EOF", "t/unit/test_transport.py::test_SSLTransport::test_write_success", "t/unit/test_transport.py::test_SSLTransport::test_write_socket_closed", "t/unit/test_transport.py::test_SSLTransport::test_write_ValueError", "t/unit/test_transport.py::test_SSLTransport::test_read_timeout", "t/unit/test_transport.py::test_SSLTransport::test_read_SSLError", "t/unit/test_transport.py::test_TCPTransport::test_repr_disconnected", "t/unit/test_transport.py::test_TCPTransport::test_repr_connected", "t/unit/test_transport.py::test_TCPTransport::test_setup_transport", "t/unit/test_transport.py::test_TCPTransport::test_read_EOF", "t/unit/test_transport.py::test_TCPTransport::test_read_frame__windowstimeout" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-11-07 22:18:49+00:00
bsd-3-clause
1,547
celery__py-amqp-357
diff --git a/AUTHORS b/AUTHORS index d6628d4..cc03f59 100644 --- a/AUTHORS +++ b/AUTHORS @@ -24,3 +24,4 @@ ChangBo Guo(gcb) <[email protected]> Alan Justino <[email protected]> Jelte Fennema <[email protected]> Jon Dufresne <[email protected]> +Colton Hicks <[email protected]> diff --git a/Changelog b/Changelog index 9d64cc4..148a880 100644 --- a/Changelog +++ b/Changelog @@ -5,6 +5,17 @@ py-amqp is fork of amqplib used by Kombu containing additional features and impr The previous amqplib changelog is here: http://code.google.com/p/py-amqplib/source/browse/CHANGES +.. _version-5.0.6: + +5.0.6 +===== +- Change the order in which context.check_hostname and context.verify_mode get set + in SSLTransport._wrap_socket_sni. Fixes bug introduced in 5.0.3 where setting + context.verify_mode = ssl.CERT_NONE would raise + "ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled." + Setting context.check_hostname prior to setting context.verify_mode resolves the + issue. + .. _version-5.0.5: 5.0.5 diff --git a/amqp/transport.py b/amqp/transport.py index 4130681..7056be8 100644 --- a/amqp/transport.py +++ b/amqp/transport.py @@ -525,9 +525,13 @@ class SSLTransport(_AbstractTransport): context.load_verify_locations(ca_certs) if ciphers is not None: context.set_ciphers(ciphers) - if cert_reqs is not None: - context.verify_mode = cert_reqs - # Set SNI headers if supported + # Set SNI headers if supported. + # Must set context.check_hostname before setting context.verify_mode + # to avoid setting context.verify_mode=ssl.CERT_NONE while + # context.check_hostname is still True (the default value in context + # if client-side) which results in the following exception: + # ValueError: Cannot set verify_mode to CERT_NONE when check_hostname + # is enabled. try: context.check_hostname = ( ssl.HAS_SNI and server_hostname is not None @@ -535,6 +539,11 @@ class SSLTransport(_AbstractTransport): except AttributeError: pass # ask forgiveness not permission + # See note above re: ordering for context.check_hostname and + # context.verify_mode assignments. + if cert_reqs is not None: + context.verify_mode = cert_reqs + if ca_certs is None and context.verify_mode != ssl.CERT_NONE: purpose = ( ssl.Purpose.CLIENT_AUTH
celery/py-amqp
137245bc8cae3290cab20fbbbe03bb5916d237c9
diff --git a/t/unit/test_transport.py b/t/unit/test_transport.py index f217fb6..d93116a 100644 --- a/t/unit/test_transport.py +++ b/t/unit/test_transport.py @@ -700,7 +700,6 @@ class test_SSLTransport: set_ciphers_method_mock.assert_called_with(sentinel.CIPHERS) def test_wrap_socket_sni_cert_reqs(self): - # testing _wrap_socket_sni() with parameter cert_reqs == ssl.CERT_NONE with patch('ssl.SSLContext') as mock_ssl_context_class: sock = Mock() context = mock_ssl_context_class() @@ -720,6 +719,48 @@ class test_SSLTransport: ) assert context.verify_mode == sentinel.CERT_REQS + # testing context creation inside _wrap_socket_sni() with parameter + # cert_reqs == ssl.CERT_NONE. Previously raised ValueError because + # code path attempted to set context.verify_mode=ssl.CERT_NONE before + # setting context.check_hostname = False which raised a ValueError + with patch('ssl.SSLContext.wrap_socket') as mock_wrap_socket: + with patch('ssl.SSLContext.load_default_certs') as mock_load_default_certs: + sock = Mock() + self.t._wrap_socket_sni( + sock, server_side=True, cert_reqs=ssl.CERT_NONE + ) + mock_load_default_certs.assert_not_called() + mock_wrap_socket.assert_called_once() + + with patch('ssl.SSLContext.wrap_socket') as mock_wrap_socket: + with patch('ssl.SSLContext.load_default_certs') as mock_load_default_certs: + sock = Mock() + self.t._wrap_socket_sni( + sock, server_side=False, cert_reqs=ssl.CERT_NONE + ) + mock_load_default_certs.assert_not_called() + mock_wrap_socket.assert_called_once() + + with patch('ssl.SSLContext.wrap_socket') as mock_wrap_socket: + with patch('ssl.SSLContext.load_default_certs') as mock_load_default_certs: + sock = Mock() + self.t._wrap_socket_sni( + sock, server_side=True, cert_reqs=ssl.CERT_REQUIRED + ) + mock_load_default_certs.assert_called_with(ssl.Purpose.CLIENT_AUTH) + mock_wrap_socket.assert_called_once() + + with patch('ssl.SSLContext.wrap_socket') as mock_wrap_socket: + with patch('ssl.SSLContext.load_default_certs') as mock_load_default_certs: + sock = Mock() + self.t._wrap_socket_sni( + sock, server_side=False, cert_reqs=ssl.CERT_REQUIRED + ) + mock_load_default_certs.assert_called_once_with( + ssl.Purpose.SERVER_AUTH + ) + mock_wrap_socket.assert_called_once() + def test_wrap_socket_sni_setting_sni_header(self): # testing _wrap_socket_sni() without parameter server_hostname
[BUG] Cannot set cert_reqs=ssl.CERT_NONE due to order of context modification in _wrap_socker_sni Setting the [broker_use_ssl](https://docs.celeryproject.org/en/stable/userguide/configuration.html#broker-use-ssl) value in celery configuration to `{"cert_reqs": ssl.CERT_NONE}` is not respected. This occurs because of the following snippet of code inside of `amqp.transport.SSLTransport._wrap_socket_sni`: ``` if cert_reqs is not None: context.verify_mode = cert_reqs # Set SNI headers if supported try: context.check_hostname = ( ssl.HAS_SNI and server_hostname is not None ) except AttributeError: pass # ask forgiveness not permission ``` Here we need to set `context.verify_mode` to the passed value of `cert_reqs` (in this case `ssl.CERT_NONE`). However, when `context.verify_mode = cert_reqs` executes it raises a `ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.` This is because the default context object instantiated has `context.check_hostname=True` by default. The code above attempts to also set this value in the subsequent block: ``` try: context.check_hostname = ( ssl.HAS_SNI and server_hostname is not None ) except AttributeError: pass # ask forgiveness not permission ``` however, the exception has already been raised. These code blocks need to be revered in order for the verification to not occur (as per the `broker_use_ssl={"cert_reqs": ssl.CERT_NONE}` parameter. Setting `context.check_hostname=False` must occur before setting `context.verify_mode=ssl.CERT_NONE`. I'll submit a PR for review. Please let me know if I am missing some other security implication of this ordering! Here's my basic app setup that creates the issue: ``` app = Celery( broker=amqps://... ) app.conf.update( broker_use_ssl={ "cert_reqs": ssl.CERT_NONE, }, ) ``` Which raises the noted `ValueError: Cannot set verify_mode to CERT_NONE when check_hostname is enabled.` The use case is connecting to a RabbitMQ instance that runs behind a Traefik reverse proxy providing TLS termination. Since Traefik is dynamically provisioning certificates I do not want to perform client-side certificate verification. The `ValueError` is swallowed by the celery worker somewhere, so the SSL verification ultimately fails (because the context is left with the default `context.verify_mode = ssl.CERT_REQUIRED` value), and the output the users see is the following: ``` [2021-02-18 21:24:33,507: ERROR/MainProcess] consumer: Cannot connect to amqps://admin:**@[**redacted**]:5671//: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1076). ```
0.0
137245bc8cae3290cab20fbbbe03bb5916d237c9
[ "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_cert_reqs" ]
[ "t/unit/test_transport.py::test_SSLTransport::test_repr_disconnected", "t/unit/test_transport.py::test_SSLTransport::test_repr_connected", "t/unit/test_transport.py::test_SSLTransport::test_setup_transport", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket", "t/unit/test_transport.py::test_SSLTransport::test_wrap_context", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_certfile", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ca_certs", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ciphers", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_setting_sni_header", "t/unit/test_transport.py::test_SSLTransport::test_shutdown_transport", "t/unit/test_transport.py::test_SSLTransport::test_read_EOF", "t/unit/test_transport.py::test_SSLTransport::test_write_success", "t/unit/test_transport.py::test_SSLTransport::test_write_socket_closed", "t/unit/test_transport.py::test_SSLTransport::test_write_ValueError", "t/unit/test_transport.py::test_SSLTransport::test_read_timeout", "t/unit/test_transport.py::test_SSLTransport::test_read_SSLError", "t/unit/test_transport.py::test_TCPTransport::test_repr_disconnected", "t/unit/test_transport.py::test_TCPTransport::test_repr_connected", "t/unit/test_transport.py::test_TCPTransport::test_setup_transport", "t/unit/test_transport.py::test_TCPTransport::test_read_EOF", "t/unit/test_transport.py::test_TCPTransport::test_read_frame__windowstimeout" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-18 21:08:10+00:00
bsd-3-clause
1,548
celery__py-amqp-364
diff --git a/t/mocks.py b/t/mocks.py new file mode 100644 index 0000000..f91ae9b --- /dev/null +++ b/t/mocks.py @@ -0,0 +1,24 @@ +from unittest.mock import Mock + +class _ContextMock(Mock): + """Dummy class implementing __enter__ and __exit__ + as the :keyword:`with` statement requires these to be implemented + in the class, not just the instance.""" + + def __enter__(self): + return self + + def __exit__(self, *exc_info): + pass + + +def ContextMock(*args, **kwargs): + """Mock that mocks :keyword:`with` statement contexts.""" + obj = _ContextMock(*args, **kwargs) + obj.attach_mock(_ContextMock(), '__enter__') + obj.attach_mock(_ContextMock(), '__exit__') + obj.__enter__.return_value = obj + # if __exit__ return a value the exception is ignored, + # so it must return None here. + obj.__exit__.return_value = None + return obj
celery/py-amqp
7300741f9fc202083e87abd10e1cb38c28efad92
diff --git a/requirements/test.txt b/requirements/test.txt index 57c3734..242016f 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,4 +1,3 @@ -case>=1.3.1 pytest>=3.0,<=5.3.5 pytest-sugar>=0.9.1 pytest-rerunfailures>=6.0 diff --git a/t/unit/conftest.py b/t/unit/conftest.py new file mode 100644 index 0000000..9a59124 --- /dev/null +++ b/t/unit/conftest.py @@ -0,0 +1,54 @@ +from unittest.mock import MagicMock +import pytest + +sentinel = object() + +class _patching: + + def __init__(self, monkeypatch, request): + self.monkeypatch = monkeypatch + self.request = request + + def __getattr__(self, name): + return getattr(self.monkeypatch, name) + + def __call__(self, path, value=sentinel, name=None, + new=MagicMock, **kwargs): + value = self._value_or_mock(value, new, name, path, **kwargs) + self.monkeypatch.setattr(path, value) + return value + + def _value_or_mock(self, value, new, name, path, **kwargs): + if value is sentinel: + value = new(name=name or path.rpartition('.')[2]) + for k, v in kwargs.items(): + setattr(value, k, v) + return value + + def setattr(self, target, name=sentinel, value=sentinel, **kwargs): + # alias to __call__ with the interface of pytest.monkeypatch.setattr + if value is sentinel: + value, name = name, None + return self(target, value, name=name) + + def setitem(self, dic, name, value=sentinel, new=MagicMock, **kwargs): + # same as pytest.monkeypatch.setattr but default value is MagicMock + value = self._value_or_mock(value, new, name, dic, **kwargs) + self.monkeypatch.setitem(dic, name, value) + return value + + [email protected] +def patching(monkeypatch, request): + """Monkeypath.setattr shortcut. + Example: + .. code-block:: python + def test_foo(patching): + # execv value here will be mock.MagicMock by default. + execv = patching('os.execv') + patching('sys.platform', 'darwin') # set concrete value + patching.setenv('DJANGO_SETTINGS_MODULE', 'x.settings') + # val will be of type mock.MagicMock by default + val = patching.setitem('path.to.dict', 'KEY') + """ + return _patching(monkeypatch, request) diff --git a/t/unit/test_channel.py b/t/unit/test_channel.py index 096ffcc..79eb951 100644 --- a/t/unit/test_channel.py +++ b/t/unit/test_channel.py @@ -3,7 +3,6 @@ from struct import pack from unittest.mock import ANY, MagicMock, Mock, patch import pytest -from case import ContextMock from vine import promise from amqp import spec @@ -13,6 +12,7 @@ from amqp.exceptions import (ConsumerCancelled, MessageNacked, NotFound, RecoverableConnectionError) from amqp.serialization import dumps +from t.mocks import ContextMock class test_Channel: diff --git a/t/unit/test_connection.py b/t/unit/test_connection.py index 4515585..21faebd 100644 --- a/t/unit/test_connection.py +++ b/t/unit/test_connection.py @@ -4,7 +4,6 @@ import warnings from unittest.mock import Mock, call, patch import pytest -from case import ContextMock from amqp import Connection, spec from amqp.connection import SSLError @@ -13,6 +12,8 @@ from amqp.exceptions import (ConnectionError, NotFound, from amqp.sasl import AMQPLAIN, EXTERNAL, GSSAPI, PLAIN, SASL from amqp.transport import TCPTransport +from t.mocks import ContextMock + class test_Connection:
5.0.6: test suite is using `case` which uses `nose` (which is outdated) `nose` is for python 2.x and is no longer maintained https://nose.readthedocs.io/en/latest/ ```console + /usr/bin/pytest -ra =========================================================================== test session starts ============================================================================ platform linux -- Python 3.8.11, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000) Using --randomly-seed=670535953 rootdir: /home/tkloczko/rpmbuild/BUILD/py-amqp-5.0.6, configfile: setup.cfg, testpaths: t/unit/, t/integration/ plugins: forked-1.3.0, shutil-1.7.0, virtualenv-1.7.0, expect-1.1.0, flake8-1.0.7, timeout-1.4.2, betamax-0.8.1, freezegun-0.4.2, aspectlib-1.5.2, toolbox-0.5, rerunfailures-9.1.1, requests-mock-1.9.3, cov-2.12.1, pyfakefs-4.5.0, flaky-3.7.0, benchmark-3.4.1, xdist-2.3.0, pylama-7.7.1, datadir-1.3.1, regressions-2.2.0, cases-3.6.3, xprocess-0.18.1, black-0.3.12, anyio-3.3.0, Faker-8.11.0, asyncio-0.15.1, trio-0.7.0, httpbin-1.0.0, subtests-0.5.0, isort-2.0.0, hypothesis-6.14.6, mock-3.6.1, profiling-1.7.0, randomly-3.8.0, checkdocs-2.7.1 collected 235 items / 2 errors / 233 selected ================================================================================== ERRORS ================================================================================== _________________________________________________________________ ERROR collecting t/unit/test_channel.py __________________________________________________________________ ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/py-amqp-5.0.6/t/unit/test_channel.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/lib64/python3.8/importlib/__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) t/unit/test_channel.py:6: in <module> from case import ContextMock E ModuleNotFoundError: No module named 'case' ________________________________________________________________ ERROR collecting t/unit/test_connection.py ________________________________________________________________ ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/py-amqp-5.0.6/t/unit/test_connection.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/lib64/python3.8/importlib/__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) t/unit/test_connection.py:7: in <module> from case import ContextMock E ModuleNotFoundError: No module named 'case' ========================================================================= short test summary info ========================================================================== ERROR t/unit/test_channel.py ERROR t/unit/test_connection.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 2 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ============================================================================ 2 errors in 0.73s ============================================================================= pytest-xprocess reminder::Be sure to terminate the started process by running 'pytest --xkill' if you have not explicitly done so in your fixture with 'xprocess.getinfo(<process_name>).terminate()'. ```
0.0
7300741f9fc202083e87abd10e1cb38c28efad92
[ "t/unit/test_channel.py::test_Channel::test_init_confirm_enabled", "t/unit/test_channel.py::test_Channel::test_init_confirm_disabled", "t/unit/test_channel.py::test_Channel::test_init_auto_channel", "t/unit/test_channel.py::test_Channel::test_init_explicit_channel", "t/unit/test_channel.py::test_Channel::test_then", "t/unit/test_channel.py::test_Channel::test_collect", "t/unit/test_channel.py::test_Channel::test_do_revive", "t/unit/test_channel.py::test_Channel::test_close__not_open", "t/unit/test_channel.py::test_Channel::test_close__no_connection", "t/unit/test_channel.py::test_Channel::test_close", "t/unit/test_channel.py::test_Channel::test_on_close", "t/unit/test_channel.py::test_Channel::test_on_close_ok", "t/unit/test_channel.py::test_Channel::test_flow", "t/unit/test_channel.py::test_Channel::test_on_flow", "t/unit/test_channel.py::test_Channel::test_x_flow_ok", "t/unit/test_channel.py::test_Channel::test_open", "t/unit/test_channel.py::test_Channel::test_on_open_ok", "t/unit/test_channel.py::test_Channel::test_exchange_declare", "t/unit/test_channel.py::test_Channel::test_exchange_declare__auto_delete", "t/unit/test_channel.py::test_Channel::test_exchange_delete", "t/unit/test_channel.py::test_Channel::test_exchange_bind", "t/unit/test_channel.py::test_Channel::test_exchange_unbind", "t/unit/test_channel.py::test_Channel::test_queue_bind", "t/unit/test_channel.py::test_Channel::test_queue_unbind", "t/unit/test_channel.py::test_Channel::test_queue_declare", "t/unit/test_channel.py::test_Channel::test_queue_declare__sync", "t/unit/test_channel.py::test_Channel::test_queue_delete", "t/unit/test_channel.py::test_Channel::test_queue_purge", "t/unit/test_channel.py::test_Channel::test_basic_ack", "t/unit/test_channel.py::test_Channel::test_basic_cancel", "t/unit/test_channel.py::test_Channel::test_on_basic_cancel", "t/unit/test_channel.py::test_Channel::test_on_basic_cancel_ok", "t/unit/test_channel.py::test_Channel::test_remove_tag", "t/unit/test_channel.py::test_Channel::test_basic_consume", "t/unit/test_channel.py::test_Channel::test_basic_consume__no_ack", "t/unit/test_channel.py::test_Channel::test_basic_consume_no_consumer_tag", "t/unit/test_channel.py::test_Channel::test_basic_consume_no_wait", "t/unit/test_channel.py::test_Channel::test_basic_consume_no_wait_no_consumer_tag", "t/unit/test_channel.py::test_Channel::test_on_basic_deliver", "t/unit/test_channel.py::test_Channel::test_basic_get", "t/unit/test_channel.py::test_Channel::test_on_get_empty", "t/unit/test_channel.py::test_Channel::test_on_get_ok", "t/unit/test_channel.py::test_Channel::test_basic_publish", "t/unit/test_channel.py::test_Channel::test_basic_publish_confirm", "t/unit/test_channel.py::test_Channel::test_basic_publish_confirm_nack", "t/unit/test_channel.py::test_Channel::test_basic_publish_connection_blocked", "t/unit/test_channel.py::test_Channel::test_basic_publish_connection_blocked_not_supported", "t/unit/test_channel.py::test_Channel::test_basic_publish_connection_blocked_not_supported_missing", "t/unit/test_channel.py::test_Channel::test_basic_publish_connection_blocked_no_capabilities", "t/unit/test_channel.py::test_Channel::test_basic_publish_confirm_callback", "t/unit/test_channel.py::test_Channel::test_basic_publish_connection_closed", "t/unit/test_channel.py::test_Channel::test_basic_qos", "t/unit/test_channel.py::test_Channel::test_basic_recover", "t/unit/test_channel.py::test_Channel::test_basic_recover_async", "t/unit/test_channel.py::test_Channel::test_basic_reject", "t/unit/test_channel.py::test_Channel::test_on_basic_return", "t/unit/test_channel.py::test_Channel::test_on_basic_return__handled", "t/unit/test_channel.py::test_Channel::test_tx_commit", "t/unit/test_channel.py::test_Channel::test_tx_rollback", "t/unit/test_channel.py::test_Channel::test_tx_select", "t/unit/test_channel.py::test_Channel::test_confirm_select", "t/unit/test_channel.py::test_Channel::test_on_basic_ack", "t/unit/test_channel.py::test_Channel::test_on_basic_nack", "t/unit/test_connection.py::test_Connection::test_sasl_authentication", "t/unit/test_connection.py::test_Connection::test_sasl_authentication_iterable", "t/unit/test_connection.py::test_Connection::test_gssapi", "t/unit/test_connection.py::test_Connection::test_external", "t/unit/test_connection.py::test_Connection::test_amqplain", "t/unit/test_connection.py::test_Connection::test_plain", "t/unit/test_connection.py::test_Connection::test_login_method_gssapi", "t/unit/test_connection.py::test_Connection::test_login_method_external", "t/unit/test_connection.py::test_Connection::test_login_method_amqplain", "t/unit/test_connection.py::test_Connection::test_login_method_plain", "t/unit/test_connection.py::test_Connection::test_enter_exit", "t/unit/test_connection.py::test_Connection::test__enter__socket_error", "t/unit/test_connection.py::test_Connection::test__exit__socket_error", "t/unit/test_connection.py::test_Connection::test_then", "t/unit/test_connection.py::test_Connection::test_connect", "t/unit/test_connection.py::test_Connection::test_connect__already_connected", "t/unit/test_connection.py::test_Connection::test_connect__socket_error", "t/unit/test_connection.py::test_Connection::test_on_start", "t/unit/test_connection.py::test_Connection::test_on_start_string_mechanisms", "t/unit/test_connection.py::test_Connection::test_missing_credentials", "t/unit/test_connection.py::test_Connection::test_invalid_method", "t/unit/test_connection.py::test_Connection::test_mechanism_mismatch", "t/unit/test_connection.py::test_Connection::test_login_method_response", "t/unit/test_connection.py::test_Connection::test_on_start__consumer_cancel_notify", "t/unit/test_connection.py::test_Connection::test_on_start__connection_blocked", "t/unit/test_connection.py::test_Connection::test_on_start__authentication_failure_close", "t/unit/test_connection.py::test_Connection::test_on_start__authentication_failure_close__disabled", "t/unit/test_connection.py::test_Connection::test_on_secure", "t/unit/test_connection.py::test_Connection::test_on_tune", "t/unit/test_connection.py::test_Connection::test_on_tune__client_heartbeat_disabled", "t/unit/test_connection.py::test_Connection::test_on_tune_sent", "t/unit/test_connection.py::test_Connection::test_on_open_ok", "t/unit/test_connection.py::test_Connection::test_connected", "t/unit/test_connection.py::test_Connection::test_collect", "t/unit/test_connection.py::test_Connection::test_collect__channel_raises_socket_error", "t/unit/test_connection.py::test_Connection::test_collect_no_transport", "t/unit/test_connection.py::test_Connection::test_collect_again", "t/unit/test_connection.py::test_Connection::test_get_free_channel_id__raises_IndexError", "t/unit/test_connection.py::test_Connection::test_claim_channel_id", "t/unit/test_connection.py::test_Connection::test_channel", "t/unit/test_connection.py::test_Connection::test_channel_when_connection_is_closed", "t/unit/test_connection.py::test_Connection::test_is_alive", "t/unit/test_connection.py::test_Connection::test_drain_events", "t/unit/test_connection.py::test_Connection::test_blocking_read__no_timeout", "t/unit/test_connection.py::test_Connection::test_blocking_read__timeout", "t/unit/test_connection.py::test_Connection::test_blocking_read__SSLError", "t/unit/test_connection.py::test_Connection::test_on_inbound_method", "t/unit/test_connection.py::test_Connection::test_on_inbound_method_when_connection_is_closed", "t/unit/test_connection.py::test_Connection::test_close", "t/unit/test_connection.py::test_Connection::test_close__already_closed", "t/unit/test_connection.py::test_Connection::test_close__socket_error", "t/unit/test_connection.py::test_Connection::test_on_close", "t/unit/test_connection.py::test_Connection::test_x_close_ok", "t/unit/test_connection.py::test_Connection::test_on_close_ok", "t/unit/test_connection.py::test_Connection::test_on_blocked", "t/unit/test_connection.py::test_Connection::test_on_unblocked", "t/unit/test_connection.py::test_Connection::test_send_heartbeat", "t/unit/test_connection.py::test_Connection::test_heartbeat_tick__no_heartbeat", "t/unit/test_connection.py::test_Connection::test_heartbeat_tick", "t/unit/test_connection.py::test_Connection::test_server_capabilities", "t/unit/test_connection.py::test_Connection::test_repr_disconnected[conn_kwargs0-/]", "t/unit/test_connection.py::test_Connection::test_repr_disconnected[conn_kwargs1-/]", "t/unit/test_connection.py::test_Connection::test_repr_disconnected[conn_kwargs2-test_vhost]", "t/unit/test_connection.py::test_Connection::test_repr_connected[conn_kwargs0-/]", "t/unit/test_connection.py::test_Connection::test_repr_connected[conn_kwargs1-/]", "t/unit/test_connection.py::test_Connection::test_repr_connected[conn_kwargs2-test_vhost]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2021-09-15 10:43:10+00:00
bsd-3-clause
1,549
celery__py-amqp-379
diff --git a/amqp/transport.py b/amqp/transport.py index 177fb22..b87f9fe 100644 --- a/amqp/transport.py +++ b/amqp/transport.py @@ -272,7 +272,11 @@ class _AbstractTransport: def close(self): if self.sock is not None: - self._shutdown_transport() + try: + self._shutdown_transport() + except OSError: + pass + # Call shutdown first to make sure that pending messages # reach the AMQP broker if the program exits after # calling this method. @@ -280,7 +284,11 @@ class _AbstractTransport: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass - self.sock.close() + + try: + self.sock.close() + except OSError: + pass self.sock = None self.connected = False
celery/py-amqp
be6b5ededa5654ca43cea67927667456e32523a3
diff --git a/t/unit/test_transport.py b/t/unit/test_transport.py index b111497..348b6c2 100644 --- a/t/unit/test_transport.py +++ b/t/unit/test_transport.py @@ -587,6 +587,16 @@ class test_AbstractTransport_connect: self.t.connect() assert self.t.connected and self.t.sock is sock_obj + def test_close__close_error(self): + # sock.close() can raise an error if the fd is invalid + # make sure the socket is properly deallocated + sock = self.t.sock = Mock() + sock.unwrap.return_value = sock + sock.close.side_effect = OSError + self.t.close() + sock.close.assert_called_with() + assert self.t.sock is None and self.t.connected is False + class test_SSLTransport: class Transport(transport.SSLTransport): @@ -835,6 +845,14 @@ class test_SSLTransport: self.t._shutdown_transport() assert self.t.sock is sock.unwrap() + def test_close__unwrap_error(self): + # sock.unwrap() can raise an error if the was a connection failure + # make sure the socket is properly closed and deallocated + sock = self.t.sock = Mock() + sock.unwrap.side_effect = OSError + self.t.close() + assert self.t.sock is None + def test_read_EOF(self): self.t.sock = Mock(name='SSLSocket') self.t.connected = True
5.0.7 SSL connection problem After upgrade to the 5.0.7 celery workers are unable to connect to RabbitMQ (3.9.11) using SSL. Worker dies immediately after start and following exceptions are logged. Reverting to 5.0.6 solves the connection problem. <pre>2021-12-15 07:31:14 [11] CRITICAL Unrecoverable error: OperationalError('[Errno 32] Broken pipe') (/usr/local/lib/python3.9/site-packages/celery/worker/worker.py:start) Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 524, in _ensured return fun(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/kombu/messaging.py", line 193, in _publish [maybe_declare(entity) for entity in declare] File "/usr/local/lib/python3.9/site-packages/kombu/messaging.py", line 193, in <listcomp> [maybe_declare(entity) for entity in declare] File "/usr/local/lib/python3.9/site-packages/kombu/messaging.py", line 99, in maybe_declare return maybe_declare(entity, self.channel, retry, **retry_policy) File "/usr/local/lib/python3.9/site-packages/kombu/common.py", line 110, in maybe_declare return _maybe_declare(entity, channel) File "/usr/local/lib/python3.9/site-packages/kombu/common.py", line 150, in _maybe_declare entity.declare(channel=channel) File "/usr/local/lib/python3.9/site-packages/kombu/entity.py", line 180, in declare return (channel or self.channel).exchange_declare( File "/usr/local/lib/python3.9/site-packages/amqp/channel.py", line 608, in exchange_declare self.send_method( File "/usr/local/lib/python3.9/site-packages/amqp/abstract_channel.py", line 57, in send_method conn.frame_writer(1, self.channel_id, sig, args, content) File "/usr/local/lib/python3.9/site-packages/amqp/method_framing.py", line 183, in write_frame write(view[:offset]) File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 355, in write self._write(s) File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 599, in _write n = write(s) File "/usr/local/lib/python3.9/ssl.py", line 1118, in write return self._sslobj.write(data) BrokenPipeError: [Errno 32] Broken pipe During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 447, in _reraise_as_library_errors yield File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 536, in _ensured self.collect() File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 366, in collect gc_transport(self._connection) File "/usr/local/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 173, in _collect connection.collect() File "/usr/local/lib/python3.9/site-packages/amqp/connection.py", line 470, in collect self._transport.close() File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 275, in close self._shutdown_transport() File "/usr/local/lib/python3.9/site-packages/amqp/transport.py", line 564, in _shutdown_transport self.sock = self.sock.unwrap() File "/usr/local/lib/python3.9/ssl.py", line 1285, in unwrap s = self._sslobj.shutdown() BrokenPipeError: [Errno 32] Broken pipe The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 326, in start blueprint.start(self) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/mingle.py", line 37, in start self.sync(c) File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/mingle.py", line 41, in sync replies = self.send_hello(c) File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/mingle.py", line 54, in send_hello replies = inspect.hello(c.hostname, our_revoked._data) or {} File "/usr/local/lib/python3.9/site-packages/celery/app/control.py", line 389, in hello return self._request('hello', from_node=from_node, revoked=revoked) File "/usr/local/lib/python3.9/site-packages/celery/app/control.py", line 106, in _request return self._prepare(self.app.control.broadcast( File "/usr/local/lib/python3.9/site-packages/celery/app/control.py", line 741, in broadcast return self.mailbox(conn)._broadcast( File "/usr/local/lib/python3.9/site-packages/kombu/pidbox.py", line 335, in _broadcast self._publish(command, arguments, destination=destination, File "/usr/local/lib/python3.9/site-packages/kombu/pidbox.py", line 303, in _publish producer.publish( File "/usr/local/lib/python3.9/site-packages/kombu/messaging.py", line 177, in publish return _publish( File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 557, in _ensured errback and errback(exc, 0) File "/usr/local/lib/python3.9/contextlib.py", line 137, in __exit__ self.gen.throw(typ, value, traceback) File "/usr/local/lib/python3.9/site-packages/kombu/connection.py", line 451, in _reraise_as_library_errors raise ConnectionError(str(exc)) from exc kombu.exceptions.OperationalError: [Errno 32] Broken pipe </pre>
0.0
be6b5ededa5654ca43cea67927667456e32523a3
[ "t/unit/test_transport.py::test_AbstractTransport_connect::test_close__close_error", "t/unit/test_transport.py::test_SSLTransport::test_close__unwrap_error" ]
[ "t/unit/test_transport.py::test_socket_options::test_backward_compatibility_tcp_transport", "t/unit/test_transport.py::test_socket_options::test_backward_compatibility_SSL_transport", "t/unit/test_transport.py::test_socket_options::test_use_default_sock_tcp_opts", "t/unit/test_transport.py::test_socket_options::test_set_single_sock_tcp_opt_tcp_transport", "t/unit/test_transport.py::test_socket_options::test_set_single_sock_tcp_opt_SSL_transport", "t/unit/test_transport.py::test_socket_options::test_values_are_set", "t/unit/test_transport.py::test_socket_options::test_passing_wrong_options", "t/unit/test_transport.py::test_socket_options::test_passing_wrong_value_options", "t/unit/test_transport.py::test_socket_options::test_passing_value_as_string", "t/unit/test_transport.py::test_socket_options::test_passing_tcp_nodelay", "t/unit/test_transport.py::test_socket_options::test_platform_socket_opts", "t/unit/test_transport.py::test_socket_options::test_set_sockopt_opts_timeout", "t/unit/test_transport.py::test_AbstractTransport::test_port", "t/unit/test_transport.py::test_AbstractTransport::test_read", "t/unit/test_transport.py::test_AbstractTransport::test_setup_transport", "t/unit/test_transport.py::test_AbstractTransport::test_shutdown_transport", "t/unit/test_transport.py::test_AbstractTransport::test_write", "t/unit/test_transport.py::test_AbstractTransport::test_close", "t/unit/test_transport.py::test_AbstractTransport::test_close_os_error", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__timeout", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__SSLError", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__EINTR", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__EBADF", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__simple", "t/unit/test_transport.py::test_AbstractTransport::test_read_frame__long", "t/unit/test_transport.py::test_AbstractTransport::test_write__success", "t/unit/test_transport.py::test_AbstractTransport::test_write__socket_timeout", "t/unit/test_transport.py::test_AbstractTransport::test_write__EINTR", "t/unit/test_transport.py::test_AbstractTransport::test_having_timeout_none", "t/unit/test_transport.py::test_AbstractTransport::test_set_timeout", "t/unit/test_transport.py::test_AbstractTransport::test_set_timeout_exception_raised", "t/unit/test_transport.py::test_AbstractTransport::test_set_same_timeout", "t/unit/test_transport.py::test_AbstractTransport::test_set_timeout_ewouldblock_exc", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_socket_fails", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_socket_initialization_fails", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_multiple_addr_entries_fails", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_multiple_addr_entries_succeed", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_short_curcuit_on_INET_succeed", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_short_curcuit_on_INET_fails", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_getaddrinfo_raises_gaierror", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_getaddrinfo_raises_gaierror_once_recovers", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_survives_not_implemented_set_cloexec", "t/unit/test_transport.py::test_AbstractTransport_connect::test_connect_already_connected", "t/unit/test_transport.py::test_SSLTransport::test_repr_disconnected", "t/unit/test_transport.py::test_SSLTransport::test_repr_connected", "t/unit/test_transport.py::test_SSLTransport::test_setup_transport", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket", "t/unit/test_transport.py::test_SSLTransport::test_wrap_context", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_certfile", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ca_certs", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_ciphers", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_cert_reqs", "t/unit/test_transport.py::test_SSLTransport::test_wrap_socket_sni_setting_sni_header", "t/unit/test_transport.py::test_SSLTransport::test_shutdown_transport", "t/unit/test_transport.py::test_SSLTransport::test_read_EOF", "t/unit/test_transport.py::test_SSLTransport::test_write_success", "t/unit/test_transport.py::test_SSLTransport::test_write_socket_closed", "t/unit/test_transport.py::test_SSLTransport::test_write_ValueError", "t/unit/test_transport.py::test_SSLTransport::test_read_timeout", "t/unit/test_transport.py::test_SSLTransport::test_read_SSLError", "t/unit/test_transport.py::test_TCPTransport::test_repr_disconnected", "t/unit/test_transport.py::test_TCPTransport::test_repr_connected", "t/unit/test_transport.py::test_TCPTransport::test_setup_transport", "t/unit/test_transport.py::test_TCPTransport::test_read_EOF", "t/unit/test_transport.py::test_TCPTransport::test_read_frame__windowstimeout" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-12-15 18:29:37+00:00
bsd-3-clause
1,550
census-instrumentation__opencensus-python-216
diff --git a/opencensus/trace/propagation/google_cloud_format.py b/opencensus/trace/propagation/google_cloud_format.py index 8c635dd..1e7b335 100644 --- a/opencensus/trace/propagation/google_cloud_format.py +++ b/opencensus/trace/propagation/google_cloud_format.py @@ -18,6 +18,7 @@ import re from opencensus.trace.span_context import SpanContext from opencensus.trace.trace_options import TraceOptions +_TRACE_CONTEXT_HEADER_NAME = 'X_CLOUD_TRACE_CONTEXT' _TRACE_CONTEXT_HEADER_FORMAT = '([0-9a-f]{32})(\/([0-9a-f]{16}))?(;o=(\d+))?' _TRACE_CONTEXT_HEADER_RE = re.compile(_TRACE_CONTEXT_HEADER_FORMAT) _TRACE_ID_DELIMETER = '/' @@ -73,6 +74,21 @@ class GoogleCloudFormatPropagator(object): .format(header)) return SpanContext() + def from_headers(self, headers): + """Generate a SpanContext object using the trace context header. + + :type headers: dict + :param headers: HTTP request headers. + + :rtype: :class:`~opencensus.trace.span_context.SpanContext` + :returns: SpanContext generated from the trace context header. + """ + if headers is None: + return SpanContext() + if _TRACE_CONTEXT_HEADER_NAME not in headers: + return SpanContext() + return self.from_header(headers[_TRACE_CONTEXT_HEADER_NAME]) + def to_header(self, span_context): """Convert a SpanContext object to header string. @@ -92,3 +108,17 @@ class GoogleCloudFormatPropagator(object): span_id, int(trace_options)) return header + + def to_headers(self, span_context): + """Convert a SpanContext object to HTTP request headers. + + :type span_context: + :class:`~opencensus.trace.span_context.SpanContext` + :param span_context: SpanContext object. + + :rtype: dict + :returns: Trace context headers in google cloud format. + """ + return { + _TRACE_CONTEXT_HEADER_NAME: self.to_header(span_context), + } diff --git a/opencensus/trace/propagation/trace_context_http_header_format.py b/opencensus/trace/propagation/trace_context_http_header_format.py index 3ac3301..63a024c 100644 --- a/opencensus/trace/propagation/trace_context_http_header_format.py +++ b/opencensus/trace/propagation/trace_context_http_header_format.py @@ -18,6 +18,7 @@ import re from opencensus.trace.span_context import SpanContext from opencensus.trace.trace_options import TraceOptions +_TRACE_PARENT_HEADER_NAME = 'traceparent' _TRACE_CONTEXT_HEADER_FORMAT = \ '([0-9a-f]{2})(-([0-9a-f]{32}))(-([0-9a-f]{16}))?(-([0-9a-f]{2}))?' _TRACE_CONTEXT_HEADER_RE = re.compile(_TRACE_CONTEXT_HEADER_FORMAT) @@ -76,6 +77,21 @@ class TraceContextPropagator(object): return SpanContext() + def from_headers(self, headers): + """Generate a SpanContext object using the W3C Distributed Tracing headers. + + :type headers: dict + :param headers: HTTP request headers. + + :rtype: :class:`~opencensus.trace.span_context.SpanContext` + :returns: SpanContext generated from the trace context header. + """ + if headers is None: + return SpanContext() + if _TRACE_PARENT_HEADER_NAME not in headers: + return SpanContext() + return self.from_header(headers[_TRACE_PARENT_HEADER_NAME]) + def to_header(self, span_context): """Convert a SpanContext object to header string, using version 0. @@ -98,3 +114,18 @@ class TraceContextPropagator(object): span_id, trace_options) return header + + def to_headers(self, span_context): + """Convert a SpanContext object to W3C Distributed Tracing headers, + using version 0. + + :type span_context: + :class:`~opencensus.trace.span_context.SpanContext` + :param span_context: SpanContext object. + + :rtype: dict + :returns: W3C Distributed Tracing headers. + """ + return { + _TRACE_PARENT_HEADER_NAME: self.to_header(span_context), + }
census-instrumentation/opencensus-python
9369932c40ada4a01dfe67f823ff4f3b987074db
diff --git a/tests/unit/trace/propagation/test_google_cloud_format.py b/tests/unit/trace/propagation/test_google_cloud_format.py index b18e7d4..626eca9 100644 --- a/tests/unit/trace/propagation/test_google_cloud_format.py +++ b/tests/unit/trace/propagation/test_google_cloud_format.py @@ -27,6 +27,22 @@ class TestGoogleCloudFormatPropagator(unittest.TestCase): assert isinstance(span_context, SpanContext) + def test_from_headers_none(self): + from opencensus.trace.span_context import SpanContext + + propagator = google_cloud_format.GoogleCloudFormatPropagator() + span_context = propagator.from_headers(None) + + assert isinstance(span_context, SpanContext) + + def test_from_headers_empty(self): + from opencensus.trace.span_context import SpanContext + + propagator = google_cloud_format.GoogleCloudFormatPropagator() + span_context = propagator.from_headers({}) + + assert isinstance(span_context, SpanContext) + def test_header_type_error(self): header = 1234 @@ -81,6 +97,22 @@ class TestGoogleCloudFormatPropagator(unittest.TestCase): self.assertNotEqual(span_context.trace_id, trace_id) + def test_headers_match(self): + # Trace option is enabled. + headers = { + 'X_CLOUD_TRACE_CONTEXT': + '6e0c63257de34c92bf9efcd03927272e/00f067aa0ba902b7;o=1', + } + expected_trace_id = '6e0c63257de34c92bf9efcd03927272e' + expected_span_id = '00f067aa0ba902b7' + + propagator = google_cloud_format.GoogleCloudFormatPropagator() + span_context = propagator.from_headers(headers) + + self.assertEqual(span_context.trace_id, expected_trace_id) + self.assertEqual(span_context.span_id, expected_span_id) + self.assertTrue(span_context.trace_options.enabled) + def test_to_header(self): from opencensus.trace import span_context from opencensus.trace import trace_options @@ -99,3 +131,23 @@ class TestGoogleCloudFormatPropagator(unittest.TestCase): trace_id, span_id, 1) self.assertEqual(header, expected_header) + + def test_to_headers(self): + from opencensus.trace import span_context + from opencensus.trace import trace_options + + trace_id = '6e0c63257de34c92bf9efcd03927272e' + span_id = '00f067aa0ba902b7' + span_context = span_context.SpanContext( + trace_id=trace_id, + span_id=span_id, + trace_options=trace_options.TraceOptions('1')) + + propagator = google_cloud_format.GoogleCloudFormatPropagator() + + headers = propagator.to_headers(span_context) + expected_headers = { + 'X_CLOUD_TRACE_CONTEXT': '{}/{};o={}'.format(trace_id, span_id, 1), + } + + self.assertEqual(headers, expected_headers) diff --git a/tests/unit/trace/propagation/test_trace_context_http_header_format.py b/tests/unit/trace/propagation/test_trace_context_http_header_format.py index dc75694..653d783 100644 --- a/tests/unit/trace/propagation/test_trace_context_http_header_format.py +++ b/tests/unit/trace/propagation/test_trace_context_http_header_format.py @@ -28,6 +28,24 @@ class TestTraceContextPropagator(unittest.TestCase): assert isinstance(span_context, SpanContext) + def test_from_headers_none(self): + from opencensus.trace.span_context import SpanContext + + propagator = trace_context_http_header_format.\ + TraceContextPropagator() + span_context = propagator.from_headers(None) + + assert isinstance(span_context, SpanContext) + + def test_from_headers_empty(self): + from opencensus.trace.span_context import SpanContext + + propagator = trace_context_http_header_format.\ + TraceContextPropagator() + span_context = propagator.from_headers({}) + + assert isinstance(span_context, SpanContext) + def test_header_type_error(self): header = 1234 @@ -97,6 +115,23 @@ class TestTraceContextPropagator(unittest.TestCase): self.assertNotEqual(span_context.trace_id, trace_id) + def test_headers_match(self): + # Trace option is enabled. + headers = { + 'traceparent': + '00-6e0c63257de34c92bf9efcd03927272e-00f067aa0ba902b7-01', + } + expected_trace_id = '6e0c63257de34c92bf9efcd03927272e' + expected_span_id = '00f067aa0ba902b7' + + propagator = trace_context_http_header_format.\ + TraceContextPropagator() + span_context = propagator.from_headers(headers) + + self.assertEqual(span_context.trace_id, expected_trace_id) + self.assertEqual(span_context.span_id, expected_span_id) + self.assertTrue(span_context.trace_options.enabled) + def test_to_header(self): from opencensus.trace import span_context from opencensus.trace import trace_options @@ -117,3 +152,24 @@ class TestTraceContextPropagator(unittest.TestCase): span_id_hex) self.assertEqual(header, expected_header) + + def test_to_headers(self): + from opencensus.trace import span_context + from opencensus.trace import trace_options + + trace_id = '6e0c63257de34c92bf9efcd03927272e' + span_id_hex = '00f067aa0ba902b7' + span_context = span_context.SpanContext( + trace_id=trace_id, + span_id=span_id_hex, + trace_options=trace_options.TraceOptions('1')) + + propagator = trace_context_http_header_format.\ + TraceContextPropagator() + + headers = propagator.to_headers(span_context) + expected_headers = { + 'traceparent': '00-{}-{}-01'.format(trace_id, span_id_hex), + } + + self.assertEqual(headers, expected_headers)
Trace header should be tied to propagator and not web framework for example: https://github.com/census-instrumentation/opencensus-python/blob/master/opencensus/trace/ext/flask/flask_middleware.py#L34 This is related to https://github.com/census-instrumentation/opencensus-python/issues/46#issuecomment-384423270
0.0
9369932c40ada4a01dfe67f823ff4f3b987074db
[ "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_from_headers_empty", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_from_headers_none", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_headers_match", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_to_headers", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_from_headers_empty", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_from_headers_none", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_headers_match", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_to_headers" ]
[ "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_from_header_no_header", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_header_match", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_header_match_no_option", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_header_not_match", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_header_type_error", "tests/unit/trace/propagation/test_google_cloud_format.py::TestGoogleCloudFormatPropagator::test_to_header", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_from_header_no_header", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_header_match", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_header_match_no_option", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_header_not_match", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_header_type_error", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_header_version_not_support", "tests/unit/trace/propagation/test_trace_context_http_header_format.py::TestTraceContextPropagator::test_to_header" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-06-29 16:08:25+00:00
apache-2.0
1,551
certbot__certbot-5687
diff --git a/acme/acme/client.py b/acme/acme/client.py index d52c82a5c..9e2478afe 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -227,8 +227,7 @@ class ClientBase(object): # pylint: disable=too-many-instance-attributes response = self._post(url, messages.Revocation( certificate=cert, - reason=rsn), - content_type=None) + reason=rsn)) if response.status_code != http_client.OK: raise errors.ClientError( 'Successful revocation must return HTTP OK status')
certbot/certbot
e0ae356aa35adf22d154113e06dd01409df93bba
diff --git a/acme/acme/client_test.py b/acme/acme/client_test.py index a0c27e74f..00b9e19dd 100644 --- a/acme/acme/client_test.py +++ b/acme/acme/client_test.py @@ -635,8 +635,7 @@ class ClientTest(ClientTestBase): def test_revoke(self): self.client.revoke(self.certr.body, self.rsn) self.net.post.assert_called_once_with( - self.directory[messages.Revocation], mock.ANY, content_type=None, - acme_version=1) + self.directory[messages.Revocation], mock.ANY, acme_version=1) def test_revocation_payload(self): obj = messages.Revocation(certificate=self.certr.body, reason=self.rsn) @@ -776,8 +775,7 @@ class ClientV2Test(ClientTestBase): def test_revoke(self): self.client.revoke(messages_test.CERT, self.rsn) self.net.post.assert_called_once_with( - self.directory["revokeCert"], mock.ANY, content_type=None, - acme_version=2) + self.directory["revokeCert"], mock.ANY, acme_version=2) class MockJSONDeSerializable(jose.JSONDeSerializable):
`acme` module's `client._revoke` sends incorrect `ContentType` header. [ACME draft-10, section 6.2](https://tools.ietf.org/html/draft-ietf-acme-acme-10#section-6.2) explicitly requires POSTs be sent with a `Content-Type` of `application/jose+json`: > Because client requests in ACME carry JWS objects in the Flattened > JSON Serialization, they must have the "Content-Type" header field > set to "application/jose+json". If a request does not meet this > requirement, then the server MUST return a response with status code > 415 (Unsupported Media Type). The good news is that Certbot & the `acme` module already do this in 99.99% of cases :tada: :+1: :balloon: The bad news is that `client._revoke` overrides the default (correct) `ContentType` with `none`: https://github.com/certbot/certbot/blob/77fdb4d7d6194989dcc775f2e0ad81b6147c2359/acme/acme/client.py#L231 This will make revocation requests fail in a world where this restriction is enforced (See https://github.com/letsencrypt/boulder/pull/3532) There doesn't seem to be a reason to want to override `ContentType` in this case so I believe the fix is to change `_revoke` to use the default. Thanks!
0.0
e0ae356aa35adf22d154113e06dd01409df93bba
[ "acme/acme/client_test.py::ClientTest::test_revoke", "acme/acme/client_test.py::ClientV2Test::test_revoke" ]
[ "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_fetch_chain_error", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_success", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_timeout", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v2", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_forwarding", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_init_acme_version", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_init_downloads_directory", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_account_and_tos", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_order_v1", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_order_v2", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_revoke", "acme/acme/client_test.py::ClientTest::test_agree_to_tos", "acme/acme/client_test.py::ClientTest::test_answer_challenge", "acme/acme/client_test.py::ClientTest::test_answer_challenge_missing_next", "acme/acme/client_test.py::ClientTest::test_check_cert", "acme/acme/client_test.py::ClientTest::test_check_cert_missing_location", "acme/acme/client_test.py::ClientTest::test_deactivate_account", "acme/acme/client_test.py::ClientTest::test_fetch_chain_max", "acme/acme/client_test.py::ClientTest::test_fetch_chain_no_up_link", "acme/acme/client_test.py::ClientTest::test_fetch_chain_single", "acme/acme/client_test.py::ClientTest::test_fetch_chain_too_many", "acme/acme/client_test.py::ClientTest::test_init_downloads_directory", "acme/acme/client_test.py::ClientTest::test_poll", "acme/acme/client_test.py::ClientTest::test_poll_and_request_issuance", "acme/acme/client_test.py::ClientTest::test_query_registration", "acme/acme/client_test.py::ClientTest::test_refresh", "acme/acme/client_test.py::ClientTest::test_register", "acme/acme/client_test.py::ClientTest::test_request_challenges", "acme/acme/client_test.py::ClientTest::test_request_challenges_custom_uri", "acme/acme/client_test.py::ClientTest::test_request_challenges_deprecated_arg", "acme/acme/client_test.py::ClientTest::test_request_challenges_unexpected_update", "acme/acme/client_test.py::ClientTest::test_request_challenges_wildcard", "acme/acme/client_test.py::ClientTest::test_request_domain_challenges", "acme/acme/client_test.py::ClientTest::test_request_issuance", "acme/acme/client_test.py::ClientTest::test_request_issuance_missing_location", "acme/acme/client_test.py::ClientTest::test_request_issuance_missing_up", "acme/acme/client_test.py::ClientTest::test_retry_after_date", "acme/acme/client_test.py::ClientTest::test_retry_after_invalid", "acme/acme/client_test.py::ClientTest::test_retry_after_missing", "acme/acme/client_test.py::ClientTest::test_retry_after_overflow", "acme/acme/client_test.py::ClientTest::test_retry_after_seconds", "acme/acme/client_test.py::ClientTest::test_revocation_payload", "acme/acme/client_test.py::ClientTest::test_revoke_bad_status_raises_error", "acme/acme/client_test.py::ClientTest::test_update_registration", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_error", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_success", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_timeout", "acme/acme/client_test.py::ClientV2Test::test_new_account", "acme/acme/client_test.py::ClientV2Test::test_new_order", "acme/acme/client_test.py::ClientV2Test::test_poll_and_finalize", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_failure", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_success", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_timeout", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_conflict", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_jobj", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_jobj_error", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_jobj_no_error", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_no_jobj", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_ok_no_jobj_ct_required", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_ok_no_jobj_no_ct", "acme/acme/client_test.py::ClientNetworkTest::test_del", "acme/acme/client_test.py::ClientNetworkTest::test_del_error", "acme/acme/client_test.py::ClientNetworkTest::test_init", "acme/acme/client_test.py::ClientNetworkTest::test_requests_error_passthrough", "acme/acme/client_test.py::ClientNetworkTest::test_send_request", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_get_der", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_post", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_timeout", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_user_agent", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_verify_ssl", "acme/acme/client_test.py::ClientNetworkTest::test_urllib_error", "acme/acme/client_test.py::ClientNetworkTest::test_wrap_in_jws", "acme/acme/client_test.py::ClientNetworkTest::test_wrap_in_jws_v2", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_get", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_head", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_head_get_post_error_passthrough", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_failed_retry", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_no_content_type", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_not_retried", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_successful_retry", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_wrong_initial_nonce", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_wrong_post_response_nonce" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-03-07 22:55:23+00:00
apache-2.0
1,552
certbot__certbot-5992
diff --git a/acme/acme/client.py b/acme/acme/client.py index 7807f0ece..bdc07fb1c 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -12,7 +12,9 @@ from six.moves import http_client # pylint: disable=import-error import josepy as jose import OpenSSL import re +from requests_toolbelt.adapters.source import SourceAddressAdapter import requests +from requests.adapters import HTTPAdapter import sys from acme import crypto_util @@ -857,9 +859,12 @@ class ClientNetwork(object): # pylint: disable=too-many-instance-attributes :param bool verify_ssl: Whether to verify certificates on SSL connections. :param str user_agent: String to send as User-Agent header. :param float timeout: Timeout for requests. + :param source_address: Optional source address to bind to when making requests. + :type source_address: str or tuple(str, int) """ def __init__(self, key, account=None, alg=jose.RS256, verify_ssl=True, - user_agent='acme-python', timeout=DEFAULT_NETWORK_TIMEOUT): + user_agent='acme-python', timeout=DEFAULT_NETWORK_TIMEOUT, + source_address=None): # pylint: disable=too-many-arguments self.key = key self.account = account @@ -869,6 +874,13 @@ class ClientNetwork(object): # pylint: disable=too-many-instance-attributes self.user_agent = user_agent self.session = requests.Session() self._default_timeout = timeout + adapter = HTTPAdapter() + + if source_address is not None: + adapter = SourceAddressAdapter(source_address) + + self.session.mount("http://", adapter) + self.session.mount("https://", adapter) def __del__(self): # Try to close the session, but don't show exceptions to the @@ -1018,7 +1030,7 @@ class ClientNetwork(object): # pylint: disable=too-many-instance-attributes if response.headers.get("Content-Type") == DER_CONTENT_TYPE: debug_content = base64.b64encode(response.content) else: - debug_content = response.content + debug_content = response.content.decode("utf-8") logger.debug('Received response:\nHTTP %d\n%s\n\n%s', response.status_code, "\n".join(["{0}: {1}".format(k, v) diff --git a/acme/setup.py b/acme/setup.py index 72ab5919b..e91c36b3d 100644 --- a/acme/setup.py +++ b/acme/setup.py @@ -19,6 +19,7 @@ install_requires = [ 'pyrfc3339', 'pytz', 'requests[security]>=2.4.1', # security extras added in 2.4.1 + 'requests-toolbelt>=0.3.0', 'setuptools', 'six>=1.9.0', # needed for python_2_unicode_compatible ] diff --git a/certbot/main.py b/certbot/main.py index a041b998f..0ae5b9d7a 100644 --- a/certbot/main.py +++ b/certbot/main.py @@ -324,7 +324,7 @@ def _find_lineage_for_domains_and_certname(config, domains, certname): return "newcert", None else: raise errors.ConfigurationError("No certificate with name {0} found. " - "Use -d to specify domains, or run certbot --certificates to see " + "Use -d to specify domains, or run certbot certificates to see " "possible certificate names.".format(certname)) def _get_added_removed(after, before): diff --git a/docs/using.rst b/docs/using.rst index 272f5ac6e..40d8f8452 100644 --- a/docs/using.rst +++ b/docs/using.rst @@ -609,7 +609,7 @@ commands into your individual environment. .. note:: ``certbot renew`` exit status will only be 1 if a renewal attempt failed. This means ``certbot renew`` exit status will be 0 if no certificate needs to be updated. If you write a custom script and expect to run a command only after a certificate was actually renewed - you will need to use the ``--post-hook`` since the exit status will be 0 both on successful renewal + you will need to use the ``--deploy-hook`` since the exit status will be 0 both on successful renewal and when renewal is not necessary. .. _renewal-config-file:
certbot/certbot
907ee797151f270bec3a2697743568362db497cd
diff --git a/acme/acme/client_test.py b/acme/acme/client_test.py index c17b83210..f3018ed81 100644 --- a/acme/acme/client_test.py +++ b/acme/acme/client_test.py @@ -1129,6 +1129,31 @@ class ClientNetworkWithMockedResponseTest(unittest.TestCase): self.assertRaises(requests.exceptions.RequestException, self.net.post, 'uri', obj=self.obj) +class ClientNetworkSourceAddressBindingTest(unittest.TestCase): + """Tests that if ClientNetwork has a source IP set manually, the underlying library has + used the provided source address.""" + + def setUp(self): + self.source_address = "8.8.8.8" + + def test_source_address_set(self): + from acme.client import ClientNetwork + net = ClientNetwork(key=None, alg=None, source_address=self.source_address) + for adapter in net.session.adapters.values(): + self.assertTrue(self.source_address in adapter.source_address) + + def test_behavior_assumption(self): + """This is a test that guardrails the HTTPAdapter behavior so that if the default for + a Session() changes, the assumptions here aren't violated silently.""" + from acme.client import ClientNetwork + # Source address not specified, so the default adapter type should be bound -- this + # test should fail if the default adapter type is changed by requests + net = ClientNetwork(key=None, alg=None) + session = requests.Session() + for scheme in session.adapters.keys(): + client_network_adapter = net.session.adapters.get(scheme) + default_adapter = session.adapters.get(scheme) + self.assertEqual(client_network_adapter.__class__, default_adapter.__class__) if __name__ == '__main__': unittest.main() # pragma: no cover
HTTP responses logged as hard-to-read bytes repr in Python 3 If you're having trouble using Certbot and aren't sure you've found a bug or request for a new feature, please first try asking for help at https://community.letsencrypt.org/. There is a much larger community there of people familiar with the project who will be able to more quickly answer your questions. ## My operating system is (include version): Ubuntu 16.04 (x86-64) ## I installed Certbot with (certbot-auto, OS package manager, pip, etc): certbot-auto (Python 2) and the PPA (0.22.2, Python 3) on different systems. ## I ran this command and it produced this output: ## Certbot's behavior differed from what I expected because: Under Python 2, Certbot logs HTTP responses as easy-to-read text, e.g.: 2018-05-02 13:41:58,328:DEBUG:acme.client:Received response: HTTP 200 Server: nginx Content-Type: application/json Content-Length: 724 X-Frame-Options: DENY Strict-Transport-Security: max-age=604800 Expires: Wed, 02 May 2018 13:41:58 GMT Cache-Control: max-age=0, no-cache, no-store Pragma: no-cache Date: Wed, 02 May 2018 13:41:58 GMT Connection: keep-alive { "6ELa2lV28v0": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417", "keyChange": "https://acme-staging-v02.api.letsencrypt.org/acme/key-change", "meta": { "caaIdentities": [ "letsencrypt.org" ], "termsOfService": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf", "website": "https://letsencrypt.org/docs/staging-environment/" }, "newAccount": "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct", "newNonce": "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce", "newOrder": "https://acme-staging-v02.api.letsencrypt.org/acme/new-order", "revokeCert": "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert" } Under Python 3, it logs the `repr()` of the bytes: 2018-05-02 13:44:24,936:DEBUG:acme.client:Received response: HTTP 200 Server: nginx Content-Type: application/json Content-Length: 724 X-Frame-Options: DENY Strict-Transport-Security: max-age=604800 Expires: Wed, 02 May 2018 13:44:24 GMT Cache-Control: max-age=0, no-cache, no-store Pragma: no-cache Date: Wed, 02 May 2018 13:44:24 GMT Connection: keep-alive b'{\n "keyChange": "https://acme-staging-v02.api.letsencrypt.org/acme/key-change",\n "meta": {\n "caaIdentities": [\n "letsencrypt.org"\n ],\n "termsOfService": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",\n "website": "https://letsencrypt.org/docs/staging-environment/"\n },\n "newAccount": "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct",\n "newNonce": "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce",\n "newOrder": "https://acme-staging-v02.api.letsencrypt.org/acme/new-order",\n "revokeCert": "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert",\n "uog1GW6DtvQ": "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/33417"\n}' It makes log files more difficult to read. Ideally Certbot would try to decode the HTTP response and log it normally. (Or perhaps dump the raw bytes straight to the log file.) This affects JSON responses and certificates, but a certificate's worth of base64 isn't human readable anyway. ## Here is a Certbot log showing the issue (if available): ###### Logs are stored in `/var/log/letsencrypt` by default. Feel free to redact domains, e-mail and IP addresses as you see fit. ## Here is the relevant nginx server block or Apache virtualhost for the domain I am configuring:
0.0
907ee797151f270bec3a2697743568362db497cd
[ "acme/acme/client_test.py::ClientNetworkSourceAddressBindingTest::test_source_address_set" ]
[ "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_fetch_chain_error", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_success", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v1_timeout", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_finalize_order_v2", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_forwarding", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_init_acme_version", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_init_downloads_directory", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_account_and_tos", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_order_v1", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_new_order_v2", "acme/acme/client_test.py::BackwardsCompatibleClientV2Test::test_revoke", "acme/acme/client_test.py::ClientTest::test_agree_to_tos", "acme/acme/client_test.py::ClientTest::test_answer_challenge", "acme/acme/client_test.py::ClientTest::test_answer_challenge_missing_next", "acme/acme/client_test.py::ClientTest::test_check_cert", "acme/acme/client_test.py::ClientTest::test_check_cert_missing_location", "acme/acme/client_test.py::ClientTest::test_deactivate_account", "acme/acme/client_test.py::ClientTest::test_fetch_chain_max", "acme/acme/client_test.py::ClientTest::test_fetch_chain_no_up_link", "acme/acme/client_test.py::ClientTest::test_fetch_chain_single", "acme/acme/client_test.py::ClientTest::test_fetch_chain_too_many", "acme/acme/client_test.py::ClientTest::test_init_downloads_directory", "acme/acme/client_test.py::ClientTest::test_poll", "acme/acme/client_test.py::ClientTest::test_poll_and_request_issuance", "acme/acme/client_test.py::ClientTest::test_query_registration", "acme/acme/client_test.py::ClientTest::test_refresh", "acme/acme/client_test.py::ClientTest::test_register", "acme/acme/client_test.py::ClientTest::test_request_challenges", "acme/acme/client_test.py::ClientTest::test_request_challenges_custom_uri", "acme/acme/client_test.py::ClientTest::test_request_challenges_deprecated_arg", "acme/acme/client_test.py::ClientTest::test_request_challenges_unexpected_update", "acme/acme/client_test.py::ClientTest::test_request_challenges_wildcard", "acme/acme/client_test.py::ClientTest::test_request_domain_challenges", "acme/acme/client_test.py::ClientTest::test_request_issuance", "acme/acme/client_test.py::ClientTest::test_request_issuance_missing_location", "acme/acme/client_test.py::ClientTest::test_request_issuance_missing_up", "acme/acme/client_test.py::ClientTest::test_retry_after_date", "acme/acme/client_test.py::ClientTest::test_retry_after_invalid", "acme/acme/client_test.py::ClientTest::test_retry_after_missing", "acme/acme/client_test.py::ClientTest::test_retry_after_overflow", "acme/acme/client_test.py::ClientTest::test_retry_after_seconds", "acme/acme/client_test.py::ClientTest::test_revocation_payload", "acme/acme/client_test.py::ClientTest::test_revoke", "acme/acme/client_test.py::ClientTest::test_revoke_bad_status_raises_error", "acme/acme/client_test.py::ClientTest::test_update_registration", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_error", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_success", "acme/acme/client_test.py::ClientV2Test::test_finalize_order_timeout", "acme/acme/client_test.py::ClientV2Test::test_new_account", "acme/acme/client_test.py::ClientV2Test::test_new_order", "acme/acme/client_test.py::ClientV2Test::test_poll_and_finalize", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_failure", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_success", "acme/acme/client_test.py::ClientV2Test::test_poll_authorizations_timeout", "acme/acme/client_test.py::ClientV2Test::test_revoke", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_conflict", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_jobj", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_jobj_error", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_jobj_no_error", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_not_ok_no_jobj", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_ok_no_jobj_ct_required", "acme/acme/client_test.py::ClientNetworkTest::test_check_response_ok_no_jobj_no_ct", "acme/acme/client_test.py::ClientNetworkTest::test_del", "acme/acme/client_test.py::ClientNetworkTest::test_del_error", "acme/acme/client_test.py::ClientNetworkTest::test_init", "acme/acme/client_test.py::ClientNetworkTest::test_requests_error_passthrough", "acme/acme/client_test.py::ClientNetworkTest::test_send_request", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_get_der", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_post", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_timeout", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_user_agent", "acme/acme/client_test.py::ClientNetworkTest::test_send_request_verify_ssl", "acme/acme/client_test.py::ClientNetworkTest::test_urllib_error", "acme/acme/client_test.py::ClientNetworkTest::test_wrap_in_jws", "acme/acme/client_test.py::ClientNetworkTest::test_wrap_in_jws_v2", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_get", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_head", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_head_get_post_error_passthrough", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_failed_retry", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_no_content_type", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_not_retried", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_successful_retry", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_wrong_initial_nonce", "acme/acme/client_test.py::ClientNetworkWithMockedResponseTest::test_post_wrong_post_response_nonce", "acme/acme/client_test.py::ClientNetworkSourceAddressBindingTest::test_behavior_assumption" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2018-05-14 21:20:12+00:00
apache-2.0
1,553
chaimleib__intervaltree-80
diff --git a/intervaltree/interval.py b/intervaltree/interval.py index f38627b..865cca7 100644 --- a/intervaltree/interval.py +++ b/intervaltree/interval.py @@ -53,6 +53,29 @@ class Interval(namedtuple('IntervalBase', ['begin', 'end', 'data'])): except: return self.contains_point(begin) + def overlap_size(self, begin, end=None): + """ + Return the overlap size between two intervals or a point + :param begin: beginning point of the range, or the point, or an Interval + :param end: end point of the range. Optional if not testing ranges. + :return: Return the overlap size, None if not overlap is found + :rtype: depends on the given input (e.g., int will be returned for int interval and timedelta for + datetime intervals) + """ + overlaps = self.overlaps(begin, end) + if not overlaps: + return 0 + + if end is not None: + # case end is given + i0 = max(self.begin, begin) + i1 = min(self.end, end) + return i1 - i0 + # assume the type is interval, in other cases, an exception will be thrown + i0 = max(self.begin, begin.begin) + i1 = min(self.end, begin.end) + return i1 - i0 + def contains_point(self, p): """ Whether the Interval contains p. diff --git a/intervaltree/node.py b/intervaltree/node.py index 7b94406..ff04959 100644 --- a/intervaltree/node.py +++ b/intervaltree/node.py @@ -58,13 +58,22 @@ class Node(object): @classmethod def from_intervals(cls, intervals): + """ + :rtype : Node + """ + if not intervals: + return None + return Node.from_sorted_intervals(sorted(intervals)) + + @classmethod + def from_sorted_intervals(cls, intervals): """ :rtype : Node """ if not intervals: return None node = Node() - node = node.init_from_sorted(sorted(intervals)) + node = node.init_from_sorted(intervals) return node def init_from_sorted(self, intervals): @@ -82,8 +91,8 @@ class Node(object): s_right.append(k) else: self.s_center.add(k) - self.left_node = Node.from_intervals(s_left) - self.right_node = Node.from_intervals(s_right) + self.left_node = Node.from_sorted_intervals(s_left) + self.right_node = Node.from_sorted_intervals(s_right) return self.rotate() def center_hit(self, interval): diff --git a/setup.py b/setup.py index 1afc8e3..32bc151 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ from setuptools.command.test import test as TestCommand import subprocess ## CONFIG -target_version = '3.0.2' +target_version = '3.0.3' def version_info(target_version):
chaimleib/intervaltree
73a00f78559b21aac4f469cec9dcb36c49f99a94
diff --git a/test/interval_methods/binary_test.py b/test/interval_methods/binary_test.py index 4b8451b..68ef212 100644 --- a/test/interval_methods/binary_test.py +++ b/test/interval_methods/binary_test.py @@ -36,7 +36,20 @@ iv9 = Interval(15, 20) iv10 = Interval(-5, 0) -def test_interval_overlaps_interval(): +def test_interval_overlaps_size_interval(): + assert iv0.overlap_size(iv0) == 10 + assert not iv0.overlap_size(iv1) + assert not iv0.overlap_size(iv2) + assert iv0.overlap_size(iv3) == 5 + assert iv0.overlap_size(iv4) == 10 + assert iv0.overlap_size(iv5) == 10 + assert iv0.overlap_size(iv6) == 10 + assert iv0.overlap_size(iv7) == 5 + assert not iv0.overlap_size(iv8) + assert not iv0.overlap_size(iv9) + + +def test_interval_overlap_interval(): assert iv0.overlaps(iv0) assert not iv0.overlaps(iv1) assert not iv0.overlaps(iv2) diff --git a/test/issues/issue67_test.py b/test/issues/issue67_test.py index 5097bb6..d19363a 100644 --- a/test/issues/issue67_test.py +++ b/test/issues/issue67_test.py @@ -25,7 +25,7 @@ from __future__ import absolute_import from intervaltree import IntervalTree import pytest -def test_interval_insersion_67(): +def test_interval_insertion_67(): intervals = ( (3657433088, 3665821696), (2415132672, 2415394816), diff --git a/test/issues/issue72_test.py b/test/issues/issue72_test.py new file mode 100644 index 0000000..3c96bb1 --- /dev/null +++ b/test/issues/issue72_test.py @@ -0,0 +1,42 @@ +""" +intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. +Queries may be by point, by range overlap, or by range envelopment. + +Test module: IntervalTree, remove_overlap caused incorrect balancing +where intervals overlapping an ancestor's x_center were buried too deep. +Submitted as issue #72 (KeyError raised after calling remove_overlap) +by alexandersoto + +Copyright 2013-2018 Chaim Leib Halbert + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +from __future__ import absolute_import +from intervaltree import IntervalTree, Interval +import pytest + +def test_interval_removal_72(): + tree = IntervalTree([ + Interval(0.0, 2.588, 841), + Interval(65.5, 85.8, 844), + Interval(93.6, 130.0, 837), + Interval(125.0, 196.5, 829), + Interval(391.8, 521.0, 825), + Interval(720.0, 726.0, 834), + Interval(800.0, 1033.0, 850), + Interval(800.0, 1033.0, 855), + ]) + tree.verify() + tree.remove_overlap(0.0, 521.0) + tree.verify() +
UnicodeDecodeError hi, E:\zephyr>pip install intervaltree Collecting intervaltree Using cached https://files.pythonhosted.org/packages/6b/63/42329a3e503366be2be68384336db308a795516b362437368ddd82d3368f/intervaltree-3.0.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\gary\AppData\Local\Temp\pip-install-kcs7dz4o\intervaltree\setup.py", line 60, in <module> long_description = fh.read() UnicodeDecodeError: 'cp950' codec can't decode byte 0xe2 in position 5223: illegal multibyte sequence !!!>>> This is a RELEASE version <<<!!! Version: 3.0.1 ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\gary\AppData\Local\Temp\pip-install-kcs7dz4o\intervaltree\
0.0
73a00f78559b21aac4f469cec9dcb36c49f99a94
[ "test/interval_methods/binary_test.py::test_interval_overlaps_size_interval" ]
[ "test/interval_methods/binary_test.py::test_interval_overlap_interval", "test/interval_methods/binary_test.py::test_contains_interval", "test/interval_methods/binary_test.py::test_distance_to_interval", "test/interval_methods/binary_test.py::test_distance_to_point", "test/issues/issue67_test.py::test_interval_insertion_67", "test/issues/issue72_test.py::test_interval_removal_72" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-12-18 02:48:39+00:00
apache-2.0
1,554
chakki-works__seqeval-63
diff --git a/seqeval/metrics/v1.py b/seqeval/metrics/v1.py index 2197293..0dbb392 100644 --- a/seqeval/metrics/v1.py +++ b/seqeval/metrics/v1.py @@ -207,7 +207,8 @@ def precision_recall_fscore_support(y_true: List[List[str]], sample_weight: Optional[List[int]] = None, zero_division: str = 'warn', scheme: Optional[Type[Token]] = None, - suffix: bool = False) -> SCORES: + suffix: bool = False, + **kwargs) -> SCORES: """Compute precision, recall, F-measure and support for each class. Args: @@ -288,9 +289,11 @@ def precision_recall_fscore_support(y_true: List[List[str]], modified with ``zero_division``. """ def extract_tp_actual_correct(y_true, y_pred, suffix, scheme): - target_names = unique_labels(y_true, y_pred, scheme, suffix) - entities_true = Entities(y_true, scheme, suffix) - entities_pred = Entities(y_pred, scheme, suffix) + # If this function is called from classification_report, + # try to reuse entities to optimize the function. + entities_true = kwargs.get('entities_true') or Entities(y_true, scheme, suffix) + entities_pred = kwargs.get('entities_pred') or Entities(y_pred, scheme, suffix) + target_names = sorted(entities_true.unique_tags | entities_pred.unique_tags) tp_sum = np.array([], dtype=np.int32) pred_sum = np.array([], dtype=np.int32) @@ -376,7 +379,10 @@ def classification_report(y_true: List[List[str]], if scheme is None or not issubclass(scheme, Token): scheme = auto_detect(y_true, suffix) - target_names = unique_labels(y_true, y_pred, scheme, suffix) + + entities_true = Entities(y_true, scheme, suffix) + entities_pred = Entities(y_pred, scheme, suffix) + target_names = sorted(entities_true.unique_tags | entities_pred.unique_tags) if output_dict: reporter = DictReporter() @@ -393,7 +399,9 @@ def classification_report(y_true: List[List[str]], sample_weight=sample_weight, zero_division=zero_division, scheme=scheme, - suffix=suffix + suffix=suffix, + entities_true=entities_true, + entities_pred=entities_pred ) for row in zip(target_names, p, r, f1, s): reporter.write(*row) @@ -408,7 +416,9 @@ def classification_report(y_true: List[List[str]], sample_weight=sample_weight, zero_division=zero_division, scheme=scheme, - suffix=suffix + suffix=suffix, + entities_true=entities_true, + entities_pred=entities_pred ) reporter.write('{} avg'.format(average), avg_p, avg_r, avg_f1, support) reporter.write_blank() diff --git a/seqeval/scheme.py b/seqeval/scheme.py index 013be37..f60abfa 100644 --- a/seqeval/scheme.py +++ b/seqeval/scheme.py @@ -35,6 +35,9 @@ class Prefix(enum.Flag): ANY = I | O | B | E | S | U | L +Prefixes = dict(Prefix.__members__) + + class Tag(enum.Flag): SAME = enum.auto() DIFF = enum.auto() @@ -49,25 +52,13 @@ class Token: def __init__(self, token: str, suffix: bool = False, delimiter: str = '-'): self.token = token - self.suffix = suffix - self.delimiter = delimiter + self.prefix = Prefixes[token[-1]] if suffix else Prefixes[token[0]] + tag = token[:-1] if suffix else token[1:] + self.tag = tag.strip(delimiter) or '_' def __repr__(self): return self.token - @property - def prefix(self): - """Extracts a prefix from the token.""" - prefix = self.token[-1] if self.suffix else self.token[0] - return Prefix[prefix] - - @property - def tag(self): - """Extracts a tag from the token.""" - tag = self.token[:-1] if self.suffix else self.token[1:] - tag = tag.strip(self.delimiter) or '_' - return tag - def is_valid(self): """Check whether the prefix is allowed or not.""" if self.prefix not in self.allowed_prefix: @@ -229,9 +220,9 @@ class Tokens: def __init__(self, tokens: List[str], scheme: Type[Token], suffix: bool = False, delimiter: str = '-', sent_id: int = None): - self.tokens = [scheme(token, suffix=suffix, delimiter=delimiter) for token in tokens] - self.scheme = scheme self.outside_token = scheme('O', suffix=suffix, delimiter=delimiter) + self.tokens = [scheme(token, suffix=suffix, delimiter=delimiter) for token in tokens] + self.extended_tokens = self.tokens + [self.outside_token] self.sent_id = sent_id @property @@ -276,12 +267,6 @@ class Tokens: prev = self.extended_tokens[i - 1] return token.is_end(prev) - @property - def extended_tokens(self): - # append a sentinel. - tokens = self.tokens + [self.outside_token] - return tokens - class Entities: @@ -315,8 +300,8 @@ def auto_detect(sequences: List[List[str]], suffix: bool = False, delimiter: str error_message = 'This scheme is not supported: {}' for tokens in sequences: for token in tokens: - token = Token(token, suffix=suffix, delimiter=delimiter) try: + token = Token(token, suffix=suffix, delimiter=delimiter) prefixes.add(token.prefix) except KeyError: raise ValueError(error_message.format(token))
chakki-works/seqeval
8db3fe6257b1da76ee772b7293565157229aaa5c
diff --git a/tests/test_scheme.py b/tests/test_scheme.py index 53fb480..411e758 100644 --- a/tests/test_scheme.py +++ b/tests/test_scheme.py @@ -627,22 +627,23 @@ def test_bilou_tokens_without_tag(tokens, expected): class TestToken: def test_raises_type_error_if_input_is_binary_string(self): - token = Token('I-組織'.encode('utf-8')) - with pytest.raises(TypeError): - tag = token.tag + with pytest.raises(KeyError): + token = Token('I-組織'.encode('utf-8')) def test_raises_index_error_if_input_is_empty_string(self): - token = Token('') with pytest.raises(IndexError): - prefix = token.prefix + token = Token('') + + def test_representation(self): + token = Token('B-ORG') + assert 'B-ORG' == str(token) class TestIOB2Token: def test_invalid_prefix(self): - token = IOB2('T') with pytest.raises(KeyError): - prefix = token.prefix + token = IOB2('T') @pytest.mark.parametrize(
Classification_report is going really slow for mode='strict' I have a dummy dataset in my local machine. While my sklearn token-level evaluation (strict mode on/off) and my seqeval entity-level evaluation (strict mode off) run all together in 5 seconds, for some reason the seqeval entity-level evaluation with arg **`mode='strict'` takes around 70 seconds, which is too much.** Is there any way to speed it up somehow? Maybe the code needs to get more optimized? I can't run experiments with more data on my AWS machine using `mode='strict'`. The evaluation on `mode='strict'` takes more time than the training of the neural models. Many thanks! * Operating System: Ubuntu 18 (LTS) * Python Version: 3.8 * Package Version: 1.1.0
0.0
8db3fe6257b1da76ee772b7293565157229aaa5c
[ "tests/test_scheme.py::TestToken::test_raises_type_error_if_input_is_binary_string", "tests/test_scheme.py::TestToken::test_raises_index_error_if_input_is_empty_string", "tests/test_scheme.py::TestIOB2Token::test_invalid_prefix" ]
[ "tests/test_scheme.py::test_entity_repr", "tests/test_scheme.py::test_entity_equality[data10-data20-True]", "tests/test_scheme.py::test_entity_equality[data11-data21-False]", "tests/test_scheme.py::test_entity_equality[data12-data22-False]", "tests/test_scheme.py::test_entity_equality[data13-data23-False]", "tests/test_scheme.py::test_entity_equality[data14-data24-False]", "tests/test_scheme.py::test_entities_filter[sequences0--expected0]", "tests/test_scheme.py::test_entities_filter[sequences1-ORG-expected1]", "tests/test_scheme.py::test_entities_filter[sequences2-PER-expected2]", "tests/test_scheme.py::test_token_prefix[I-MISC-False-Prefix.I]", "tests/test_scheme.py::test_token_prefix[B-MISC-False-Prefix.B]", "tests/test_scheme.py::test_token_prefix[O-False-Prefix.O]", "tests/test_scheme.py::test_token_prefix[MISC-I-True-Prefix.I]", "tests/test_scheme.py::test_token_prefix[MISC-B-True-Prefix.B]", "tests/test_scheme.py::test_token_prefix[O-True-Prefix.O]", "tests/test_scheme.py::test_token_tag[I-MISC-False-MISC]", "tests/test_scheme.py::test_token_tag[MISC-I-True-MISC]", "tests/test_scheme.py::test_token_tag[I-False-_]", "tests/test_scheme.py::test_token_tag[O-False-_]", "tests/test_scheme.py::test_token_tag[I-ORG-COMPANY-False-ORG-COMPANY]", "tests/test_scheme.py::test_token_tag[ORG-COMPANY-I-True-ORG-COMPANY]", "tests/test_scheme.py::test_token_tag[I-\\u7d44\\u7e54-False-\\u7d44\\u7e54]", "tests/test_scheme.py::test_iob1_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_iob1_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_iob1_start_inside_end[O-B-PER-expected2]", "tests/test_scheme.py::test_iob1_start_inside_end[I-PER-O-expected3]", "tests/test_scheme.py::test_iob1_start_inside_end[I-PER-I-PER-expected4]", "tests/test_scheme.py::test_iob1_start_inside_end[I-PER-I-ORG-expected5]", "tests/test_scheme.py::test_iob1_start_inside_end[I-PER-B-PER-expected6]", "tests/test_scheme.py::test_iob1_start_inside_end[I-PER-B-ORG-expected7]", "tests/test_scheme.py::test_iob1_start_inside_end[B-PER-O-expected8]", "tests/test_scheme.py::test_iob1_start_inside_end[B-PER-I-PER-expected9]", "tests/test_scheme.py::test_iob1_start_inside_end[B-PER-I-ORG-expected10]", "tests/test_scheme.py::test_iob1_start_inside_end[B-PER-B-PER-expected11]", "tests/test_scheme.py::test_iob1_start_inside_end[B-PER-B-ORG-expected12]", "tests/test_scheme.py::test_iob2_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_iob2_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_iob2_start_inside_end[O-B-PER-expected2]", "tests/test_scheme.py::test_iob2_start_inside_end[I-PER-O-expected3]", "tests/test_scheme.py::test_iob2_start_inside_end[I-PER-I-PER-expected4]", "tests/test_scheme.py::test_iob2_start_inside_end[I-PER-I-ORG-expected5]", "tests/test_scheme.py::test_iob2_start_inside_end[I-PER-B-PER-expected6]", "tests/test_scheme.py::test_iob2_start_inside_end[I-PER-B-ORG-expected7]", "tests/test_scheme.py::test_iob2_start_inside_end[B-PER-O-expected8]", "tests/test_scheme.py::test_iob2_start_inside_end[B-PER-I-PER-expected9]", "tests/test_scheme.py::test_iob2_start_inside_end[B-PER-I-ORG-expected10]", "tests/test_scheme.py::test_iob2_start_inside_end[B-PER-B-PER-expected11]", "tests/test_scheme.py::test_iob2_start_inside_end[B-PER-B-ORG-expected12]", "tests/test_scheme.py::test_ioe1_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_ioe1_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_ioe1_start_inside_end[O-E-PER-expected2]", "tests/test_scheme.py::test_ioe1_start_inside_end[I-PER-O-expected3]", "tests/test_scheme.py::test_ioe1_start_inside_end[I-PER-I-PER-expected4]", "tests/test_scheme.py::test_ioe1_start_inside_end[I-PER-I-ORG-expected5]", "tests/test_scheme.py::test_ioe1_start_inside_end[I-PER-E-PER-expected6]", "tests/test_scheme.py::test_ioe1_start_inside_end[I-PER-E-ORG-expected7]", "tests/test_scheme.py::test_ioe1_start_inside_end[E-PER-O-expected8]", "tests/test_scheme.py::test_ioe1_start_inside_end[E-PER-I-PER-expected9]", "tests/test_scheme.py::test_ioe1_start_inside_end[E-PER-I-ORG-expected10]", "tests/test_scheme.py::test_ioe1_start_inside_end[E-PER-E-PER-expected11]", "tests/test_scheme.py::test_ioe1_start_inside_end[E-PER-E-ORG-expected12]", "tests/test_scheme.py::test_ioe2_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_ioe2_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_ioe2_start_inside_end[O-E-PER-expected2]", "tests/test_scheme.py::test_ioe2_start_inside_end[I-PER-O-expected3]", "tests/test_scheme.py::test_ioe2_start_inside_end[I-PER-I-PER-expected4]", "tests/test_scheme.py::test_ioe2_start_inside_end[I-PER-I-ORG-expected5]", "tests/test_scheme.py::test_ioe2_start_inside_end[I-PER-E-PER-expected6]", "tests/test_scheme.py::test_ioe2_start_inside_end[I-PER-E-ORG-expected7]", "tests/test_scheme.py::test_ioe2_start_inside_end[E-PER-O-expected8]", "tests/test_scheme.py::test_ioe2_start_inside_end[E-PER-I-PER-expected9]", "tests/test_scheme.py::test_ioe2_start_inside_end[E-PER-I-ORG-expected10]", "tests/test_scheme.py::test_ioe2_start_inside_end[E-PER-E-PER-expected11]", "tests/test_scheme.py::test_ioe2_start_inside_end[E-PER-E-ORG-expected12]", "tests/test_scheme.py::test_iobes_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_iobes_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_iobes_start_inside_end[O-B-PER-expected2]", "tests/test_scheme.py::test_iobes_start_inside_end[O-E-PER-expected3]", "tests/test_scheme.py::test_iobes_start_inside_end[O-S-PER-expected4]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-O-expected5]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-I-PER-expected6]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-I-ORG-expected7]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-B-PER-expected8]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-E-PER-expected9]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-E-ORG-expected10]", "tests/test_scheme.py::test_iobes_start_inside_end[I-PER-S-PER-expected11]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-O-expected12]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-I-PER-expected13]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-I-ORG-expected14]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-E-PER-expected15]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-E-ORG-expected16]", "tests/test_scheme.py::test_iobes_start_inside_end[B-PER-S-PER-expected17]", "tests/test_scheme.py::test_iobes_start_inside_end[E-PER-O-expected18]", "tests/test_scheme.py::test_iobes_start_inside_end[E-PER-I-PER-expected19]", "tests/test_scheme.py::test_iobes_start_inside_end[E-PER-B-PER-expected20]", "tests/test_scheme.py::test_iobes_start_inside_end[E-PER-E-PER-expected21]", "tests/test_scheme.py::test_iobes_start_inside_end[E-PER-S-PER-expected22]", "tests/test_scheme.py::test_iobes_start_inside_end[S-PER-O-expected23]", "tests/test_scheme.py::test_iobes_start_inside_end[S-PER-I-PER-expected24]", "tests/test_scheme.py::test_iobes_start_inside_end[S-PER-B-PER-expected25]", "tests/test_scheme.py::test_iobes_start_inside_end[S-PER-E-PER-expected26]", "tests/test_scheme.py::test_iobes_start_inside_end[S-PER-S-PER-expected27]", "tests/test_scheme.py::test_bilou_start_inside_end[O-O-expected0]", "tests/test_scheme.py::test_bilou_start_inside_end[O-I-PER-expected1]", "tests/test_scheme.py::test_bilou_start_inside_end[O-B-PER-expected2]", "tests/test_scheme.py::test_bilou_start_inside_end[O-L-PER-expected3]", "tests/test_scheme.py::test_bilou_start_inside_end[O-U-PER-expected4]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-O-expected5]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-I-PER-expected6]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-I-ORG-expected7]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-B-PER-expected8]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-L-PER-expected9]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-L-ORG-expected10]", "tests/test_scheme.py::test_bilou_start_inside_end[I-PER-U-PER-expected11]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-O-expected12]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-I-PER-expected13]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-I-ORG-expected14]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-L-PER-expected15]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-L-ORG-expected16]", "tests/test_scheme.py::test_bilou_start_inside_end[B-PER-U-PER-expected17]", "tests/test_scheme.py::test_bilou_start_inside_end[L-PER-O-expected18]", "tests/test_scheme.py::test_bilou_start_inside_end[L-PER-I-PER-expected19]", "tests/test_scheme.py::test_bilou_start_inside_end[L-PER-B-PER-expected20]", "tests/test_scheme.py::test_bilou_start_inside_end[L-PER-L-PER-expected21]", "tests/test_scheme.py::test_bilou_start_inside_end[L-PER-U-PER-expected22]", "tests/test_scheme.py::test_bilou_start_inside_end[U-PER-O-expected23]", "tests/test_scheme.py::test_bilou_start_inside_end[U-PER-I-PER-expected24]", "tests/test_scheme.py::test_bilou_start_inside_end[U-PER-B-PER-expected25]", "tests/test_scheme.py::test_bilou_start_inside_end[U-PER-L-PER-expected26]", "tests/test_scheme.py::test_bilou_start_inside_end[U-PER-U-PER-expected27]", "tests/test_scheme.py::test_iob1_tokens[tokens0-expected0]", "tests/test_scheme.py::test_iob1_tokens[tokens1-expected1]", "tests/test_scheme.py::test_iob1_tokens[tokens2-expected2]", "tests/test_scheme.py::test_iob1_tokens[tokens3-expected3]", "tests/test_scheme.py::test_iob1_tokens[tokens4-expected4]", "tests/test_scheme.py::test_iob1_tokens[tokens5-expected5]", "tests/test_scheme.py::test_iob1_tokens[tokens6-expected6]", "tests/test_scheme.py::test_iob1_tokens[tokens7-expected7]", "tests/test_scheme.py::test_iob1_tokens[tokens8-expected8]", "tests/test_scheme.py::test_iob1_tokens[tokens9-expected9]", "tests/test_scheme.py::test_iob1_tokens[tokens10-expected10]", "tests/test_scheme.py::test_iob1_tokens[tokens11-expected11]", "tests/test_scheme.py::test_iob1_tokens[tokens12-expected12]", "tests/test_scheme.py::test_iob1_tokens[tokens13-expected13]", "tests/test_scheme.py::test_iob1_tokens[tokens14-expected14]", "tests/test_scheme.py::test_iob1_tokens[tokens15-expected15]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_iob1_tokens_without_tag[tokens12-expected12]", "tests/test_scheme.py::test_iob2_tokens[tokens0-expected0]", "tests/test_scheme.py::test_iob2_tokens[tokens1-expected1]", "tests/test_scheme.py::test_iob2_tokens[tokens2-expected2]", "tests/test_scheme.py::test_iob2_tokens[tokens3-expected3]", "tests/test_scheme.py::test_iob2_tokens[tokens4-expected4]", "tests/test_scheme.py::test_iob2_tokens[tokens5-expected5]", "tests/test_scheme.py::test_iob2_tokens[tokens6-expected6]", "tests/test_scheme.py::test_iob2_tokens[tokens7-expected7]", "tests/test_scheme.py::test_iob2_tokens[tokens8-expected8]", "tests/test_scheme.py::test_iob2_tokens[tokens9-expected9]", "tests/test_scheme.py::test_iob2_tokens[tokens10-expected10]", "tests/test_scheme.py::test_iob2_tokens[tokens11-expected11]", "tests/test_scheme.py::test_iob2_tokens[tokens12-expected12]", "tests/test_scheme.py::test_iob2_tokens[tokens13-expected13]", "tests/test_scheme.py::test_iob2_tokens[tokens14-expected14]", "tests/test_scheme.py::test_iob2_tokens[tokens15-expected15]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_iob2_tokens_without_tag[tokens12-expected12]", "tests/test_scheme.py::test_ioe1_tokens[tokens0-expected0]", "tests/test_scheme.py::test_ioe1_tokens[tokens1-expected1]", "tests/test_scheme.py::test_ioe1_tokens[tokens2-expected2]", "tests/test_scheme.py::test_ioe1_tokens[tokens3-expected3]", "tests/test_scheme.py::test_ioe1_tokens[tokens4-expected4]", "tests/test_scheme.py::test_ioe1_tokens[tokens5-expected5]", "tests/test_scheme.py::test_ioe1_tokens[tokens6-expected6]", "tests/test_scheme.py::test_ioe1_tokens[tokens7-expected7]", "tests/test_scheme.py::test_ioe1_tokens[tokens8-expected8]", "tests/test_scheme.py::test_ioe1_tokens[tokens9-expected9]", "tests/test_scheme.py::test_ioe1_tokens[tokens10-expected10]", "tests/test_scheme.py::test_ioe1_tokens[tokens11-expected11]", "tests/test_scheme.py::test_ioe1_tokens[tokens12-expected12]", "tests/test_scheme.py::test_ioe1_tokens[tokens13-expected13]", "tests/test_scheme.py::test_ioe1_tokens[tokens14-expected14]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_ioe1_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_ioe2_tokens[tokens0-expected0]", "tests/test_scheme.py::test_ioe2_tokens[tokens1-expected1]", "tests/test_scheme.py::test_ioe2_tokens[tokens2-expected2]", "tests/test_scheme.py::test_ioe2_tokens[tokens3-expected3]", "tests/test_scheme.py::test_ioe2_tokens[tokens4-expected4]", "tests/test_scheme.py::test_ioe2_tokens[tokens5-expected5]", "tests/test_scheme.py::test_ioe2_tokens[tokens6-expected6]", "tests/test_scheme.py::test_ioe2_tokens[tokens7-expected7]", "tests/test_scheme.py::test_ioe2_tokens[tokens8-expected8]", "tests/test_scheme.py::test_ioe2_tokens[tokens9-expected9]", "tests/test_scheme.py::test_ioe2_tokens[tokens10-expected10]", "tests/test_scheme.py::test_ioe2_tokens[tokens11-expected11]", "tests/test_scheme.py::test_ioe2_tokens[tokens12-expected12]", "tests/test_scheme.py::test_ioe2_tokens[tokens13-expected13]", "tests/test_scheme.py::test_ioe2_tokens[tokens14-expected14]", "tests/test_scheme.py::test_ioe2_tokens[tokens15-expected15]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_ioe2_tokens_without_tag[tokens12-expected12]", "tests/test_scheme.py::test_iobes_tokens[tokens0-expected0]", "tests/test_scheme.py::test_iobes_tokens[tokens1-expected1]", "tests/test_scheme.py::test_iobes_tokens[tokens2-expected2]", "tests/test_scheme.py::test_iobes_tokens[tokens3-expected3]", "tests/test_scheme.py::test_iobes_tokens[tokens4-expected4]", "tests/test_scheme.py::test_iobes_tokens[tokens5-expected5]", "tests/test_scheme.py::test_iobes_tokens[tokens6-expected6]", "tests/test_scheme.py::test_iobes_tokens[tokens7-expected7]", "tests/test_scheme.py::test_iobes_tokens[tokens8-expected8]", "tests/test_scheme.py::test_iobes_tokens[tokens9-expected9]", "tests/test_scheme.py::test_iobes_tokens[tokens10-expected10]", "tests/test_scheme.py::test_iobes_tokens[tokens11-expected11]", "tests/test_scheme.py::test_iobes_tokens[tokens12-expected12]", "tests/test_scheme.py::test_iobes_tokens[tokens13-expected13]", "tests/test_scheme.py::test_iobes_tokens[tokens14-expected14]", "tests/test_scheme.py::test_iobes_tokens[tokens15-expected15]", "tests/test_scheme.py::test_iobes_tokens[tokens16-expected16]", "tests/test_scheme.py::test_iobes_tokens[tokens17-expected17]", "tests/test_scheme.py::test_iobes_tokens[tokens18-expected18]", "tests/test_scheme.py::test_iobes_tokens[tokens19-expected19]", "tests/test_scheme.py::test_iobes_tokens[tokens20-expected20]", "tests/test_scheme.py::test_iobes_tokens[tokens21-expected21]", "tests/test_scheme.py::test_iobes_tokens[tokens22-expected22]", "tests/test_scheme.py::test_iobes_tokens[tokens23-expected23]", "tests/test_scheme.py::test_iobes_tokens[tokens24-expected24]", "tests/test_scheme.py::test_iobes_tokens[tokens25-expected25]", "tests/test_scheme.py::test_iobes_tokens[tokens26-expected26]", "tests/test_scheme.py::test_iobes_tokens[tokens27-expected27]", "tests/test_scheme.py::test_iobes_tokens[tokens28-expected28]", "tests/test_scheme.py::test_iobes_tokens[tokens29-expected29]", "tests/test_scheme.py::test_iobes_tokens[tokens30-expected30]", "tests/test_scheme.py::test_iobes_tokens[tokens31-expected31]", "tests/test_scheme.py::test_iobes_tokens[tokens32-expected32]", "tests/test_scheme.py::test_iobes_tokens[tokens33-expected33]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens12-expected12]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens13-expected13]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens14-expected14]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens15-expected15]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens16-expected16]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens17-expected17]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens18-expected18]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens19-expected19]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens20-expected20]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens21-expected21]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens22-expected22]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens23-expected23]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens24-expected24]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens25-expected25]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens26-expected26]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens27-expected27]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens28-expected28]", "tests/test_scheme.py::test_iobes_tokens_without_tag[tokens29-expected29]", "tests/test_scheme.py::test_bilou_tokens[tokens0-expected0]", "tests/test_scheme.py::test_bilou_tokens[tokens1-expected1]", "tests/test_scheme.py::test_bilou_tokens[tokens2-expected2]", "tests/test_scheme.py::test_bilou_tokens[tokens3-expected3]", "tests/test_scheme.py::test_bilou_tokens[tokens4-expected4]", "tests/test_scheme.py::test_bilou_tokens[tokens5-expected5]", "tests/test_scheme.py::test_bilou_tokens[tokens6-expected6]", "tests/test_scheme.py::test_bilou_tokens[tokens7-expected7]", "tests/test_scheme.py::test_bilou_tokens[tokens8-expected8]", "tests/test_scheme.py::test_bilou_tokens[tokens9-expected9]", "tests/test_scheme.py::test_bilou_tokens[tokens10-expected10]", "tests/test_scheme.py::test_bilou_tokens[tokens11-expected11]", "tests/test_scheme.py::test_bilou_tokens[tokens12-expected12]", "tests/test_scheme.py::test_bilou_tokens[tokens13-expected13]", "tests/test_scheme.py::test_bilou_tokens[tokens14-expected14]", "tests/test_scheme.py::test_bilou_tokens[tokens15-expected15]", "tests/test_scheme.py::test_bilou_tokens[tokens16-expected16]", "tests/test_scheme.py::test_bilou_tokens[tokens17-expected17]", "tests/test_scheme.py::test_bilou_tokens[tokens18-expected18]", "tests/test_scheme.py::test_bilou_tokens[tokens19-expected19]", "tests/test_scheme.py::test_bilou_tokens[tokens20-expected20]", "tests/test_scheme.py::test_bilou_tokens[tokens21-expected21]", "tests/test_scheme.py::test_bilou_tokens[tokens22-expected22]", "tests/test_scheme.py::test_bilou_tokens[tokens23-expected23]", "tests/test_scheme.py::test_bilou_tokens[tokens24-expected24]", "tests/test_scheme.py::test_bilou_tokens[tokens25-expected25]", "tests/test_scheme.py::test_bilou_tokens[tokens26-expected26]", "tests/test_scheme.py::test_bilou_tokens[tokens27-expected27]", "tests/test_scheme.py::test_bilou_tokens[tokens28-expected28]", "tests/test_scheme.py::test_bilou_tokens[tokens29-expected29]", "tests/test_scheme.py::test_bilou_tokens[tokens30-expected30]", "tests/test_scheme.py::test_bilou_tokens[tokens31-expected31]", "tests/test_scheme.py::test_bilou_tokens[tokens32-expected32]", "tests/test_scheme.py::test_bilou_tokens[tokens33-expected33]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens0-expected0]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens1-expected1]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens2-expected2]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens3-expected3]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens4-expected4]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens5-expected5]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens6-expected6]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens7-expected7]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens8-expected8]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens9-expected9]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens10-expected10]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens11-expected11]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens12-expected12]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens13-expected13]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens14-expected14]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens15-expected15]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens16-expected16]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens17-expected17]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens18-expected18]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens19-expected19]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens20-expected20]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens21-expected21]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens22-expected22]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens23-expected23]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens24-expected24]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens25-expected25]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens26-expected26]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens27-expected27]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens28-expected28]", "tests/test_scheme.py::test_bilou_tokens_without_tag[tokens29-expected29]", "tests/test_scheme.py::TestToken::test_representation", "tests/test_scheme.py::test_valid_prefix[I-IOB1]", "tests/test_scheme.py::test_valid_prefix[O-IOB1]", "tests/test_scheme.py::test_valid_prefix[B-IOB1]", "tests/test_scheme.py::test_valid_prefix[I-IOB2]", "tests/test_scheme.py::test_valid_prefix[O-IOB2]", "tests/test_scheme.py::test_valid_prefix[B-IOB2]", "tests/test_scheme.py::test_valid_prefix[I-IOE1]", "tests/test_scheme.py::test_valid_prefix[O-IOE1]", "tests/test_scheme.py::test_valid_prefix[E-IOE1]", "tests/test_scheme.py::test_valid_prefix[I-IOE2]", "tests/test_scheme.py::test_valid_prefix[O-IOE2]", "tests/test_scheme.py::test_valid_prefix[E-IOE2]", "tests/test_scheme.py::test_valid_prefix[I-IOBES]", "tests/test_scheme.py::test_valid_prefix[O-IOBES]", "tests/test_scheme.py::test_valid_prefix[B-IOBES]", "tests/test_scheme.py::test_valid_prefix[E-IOBES]", "tests/test_scheme.py::test_valid_prefix[S-IOBES]", "tests/test_scheme.py::test_invalid_prefix[E-IOB1]", "tests/test_scheme.py::test_invalid_prefix[S-IOB1]", "tests/test_scheme.py::test_invalid_prefix[E-IOB2]", "tests/test_scheme.py::test_invalid_prefix[S-IOB2]", "tests/test_scheme.py::test_invalid_prefix[B-IOE1]", "tests/test_scheme.py::test_invalid_prefix[S-IOE1]", "tests/test_scheme.py::test_invalid_prefix[B-IOE2]", "tests/test_scheme.py::test_invalid_prefix[S-IOE2]", "tests/test_scheme.py::TestTokens::test_raise_exception_when_iobes_tokens_with_iob2_scheme", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences0-IOB2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences1-IOB2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences2-IOB2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences3-IOB2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences4-IOE2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences5-IOE2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences6-IOE2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences7-IOE2]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences8-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences9-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences10-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences11-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences12-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences13-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences14-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences15-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences16-IOBES]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences17-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences18-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences19-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences20-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences21-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences22-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences23-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences24-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_valid_scheme[sequences25-BILOU]", "tests/test_scheme.py::TestAutoDetect::test_invalid_scheme[sequences0-IOB2]", "tests/test_scheme.py::TestAutoDetect::test_invalid_scheme[sequences1-IOB2]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-17 00:26:52+00:00
mit
1,555
chapinb__chickadee-55
diff --git a/libchickadee/backends/__init__.py b/libchickadee/backends/__init__.py index 2b110e6..d1f79ef 100644 --- a/libchickadee/backends/__init__.py +++ b/libchickadee/backends/__init__.py @@ -62,13 +62,18 @@ class ResolverBase(object): Args: data (list, tuple, set, str): One or more IPs to resolve - Yield: - (dict) request data iterator + Returns: + (list) List of collected records. Example: >>> records = ['1.1.1.1', '2.2.2.2'] >>> resolver = ResolverBase() >>> resolved_data = resolver.query(records) + >>> print(resolved_data) + [ + {"query": "1.1.1.1", "country": "Australia", ...}, + {"query": "2.2.2.2", "country": "France", ...} + ] """ self.data = data diff --git a/libchickadee/backends/ipapi.py b/libchickadee/backends/ipapi.py index 14d5dac..398d9ea 100644 --- a/libchickadee/backends/ipapi.py +++ b/libchickadee/backends/ipapi.py @@ -182,7 +182,7 @@ class Resolver(ResolverBase): for x in orig_recs: params = { - 'fields': ','.join(self.fields), + 'fields': ','.join(self.fields) if isinstance(self.fields, list) else self.fields, 'lang': self.lang, } if self.api_key: @@ -237,7 +237,7 @@ class Resolver(ResolverBase): ) if rdata.status_code == 200: self.rate_limit(rdata.headers) - return rdata.json() + return [rdata.json()] elif rdata.status_code == 429: self.rate_limit(rdata.headers) self.sleeper() diff --git a/libchickadee/chickadee.py b/libchickadee/chickadee.py index 4ed060a..29ad97c 100644 --- a/libchickadee/chickadee.py +++ b/libchickadee/chickadee.py @@ -194,7 +194,7 @@ class Chickadee(object): self.input_data = None self.outformat = outformat self.outfile = outfile - self.fields = fields + self.fields = fields if isinstance(fields, list) else fields.split(',') self.force_single = False self.ignore_bogon = True self.lang = 'en' @@ -380,7 +380,7 @@ class Chickadee(object): for element in data: resolver.data = element - results.append(resolver.single()) + results += resolver.single() else: results = resolver.query(distinct_ips)
chapinb/chickadee
1be8ad64f2880ad1e39cc18fda25d9bde14778dd
diff --git a/libchickadee/test/test_backend_ipapi.py b/libchickadee/test/test_backend_ipapi.py index c10895c..62a0ee9 100644 --- a/libchickadee/test/test_backend_ipapi.py +++ b/libchickadee/test/test_backend_ipapi.py @@ -72,7 +72,7 @@ class IPAPITestCase(unittest.TestCase): mock_query.return_value = MockResponse(json_data=self.expected_result[count], status_code=200) self.resolver.data = ip data = self.resolver.single() - self.assertEqual(data, self.expected_result[count]) + self.assertEqual(data, [self.expected_result[count]]) @patch("libchickadee.backends.ipapi.requests.post") def test_ipapi_resolve_batch(self, mock_query): @@ -105,7 +105,7 @@ class IPAPITestCase(unittest.TestCase): def test_ipapi_rate_limiting(self, mock_get, mock_post): single = { "test_data": self.test_data_ips[1], - "expected_data": self.expected_result[1], + "expected_data": [self.expected_result[1]], "mock_data": [ MockResponse(json_data={}, status_code=429, rl='0', ttl='2'), MockResponse(json_data=self.expected_result[1], status_code=200, rl='0', ttl='0') diff --git a/libchickadee/test/test_chickadee.py b/libchickadee/test/test_chickadee.py index 03ea9c6..7de8cba 100644 --- a/libchickadee/test/test_chickadee.py +++ b/libchickadee/test/test_chickadee.py @@ -188,7 +188,7 @@ class ChickadeeStringTestCase(unittest.TestCase): chickadee = Chickadee() chickadee.ignore_bogon = False chickadee.fields = self.fields - mock_query.return_value = self.expected_result.copy() + mock_query.return_value = self.expected_result data = chickadee.run(','.join(self.test_data_ips)) res = [x for x in data] self.assertCountEqual(res, self.expected_result) @@ -202,7 +202,7 @@ class ChickadeeStringTestCase(unittest.TestCase): self.data = None def single(self): - return [x for x in expected_results if x['query'] == self.data][0] + return [x for x in expected_results if x['query'] == self.data] chickadee = Chickadee() chickadee.ignore_bogon = False @@ -222,6 +222,13 @@ class ChickadeeStringTestCase(unittest.TestCase): failed = True self.assertTrue(failed) + @patch("libchickadee.backends.ipapi.Resolver.batch") + def test_manual_run(self, mock_query): + chick = Chickadee(fields=self.fields) + mock_query.return_value = [self.expected_result[1]] + actual = chick.run(self.test_data_ips[1]) + self.assertDictEqual(self.expected_result[1], actual[0]) + class ChickadeeFileTestCase(unittest.TestCase): """Chickadee script tests."""
Chickadee passes fields as string instead of list to resolver **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior. Please share (as you can): 1. Sample IP addresses causing issue: `1.1.1.1` 1. Arguments used to invoke chickadee: `chick = Chickadee(); chick.run('1.1.1.1')` 1. Error message or `chickadee.log` file: Returns `[{"count": 0}]` **Version (please complete the following information):** - OS: Windows and macOS - Version: d826822 - Python version: 3.7.2 **Additional context** Add any other context about the problem here. Appears when you provide an IP address via API call.
0.0
1be8ad64f2880ad1e39cc18fda25d9bde14778dd
[ "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_rate_limiting", "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_resolve_single", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_chickadee_force_single" ]
[ "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_resolve_batch", "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_resolve_query_batch", "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_resolve_query_single", "libchickadee/test/test_backend_ipapi.py::IPAPITestCase::test_ipapi_resolve_single_field", "libchickadee/test/test_backend_ipapi.py::WritersTestCase::test_write_csv", "libchickadee/test/test_backend_ipapi.py::WritersTestCase::test_write_json", "libchickadee/test/test_backend_ipapi.py::WritersTestCase::test_write_json_headers", "libchickadee/test/test_backend_ipapi.py::WritersTestCase::test_write_json_lines", "libchickadee/test/test_chickadee.py::ChickadeeConfigTestCase::test_argparse", "libchickadee/test/test_chickadee.py::ChickadeeConfigTestCase::test_configparse", "libchickadee/test/test_chickadee.py::ChickadeeConfigTestCase::test_find_config_file", "libchickadee/test/test_chickadee.py::ChickadeeConfigTestCase::test_parse_config_file_provided", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_chickadee_csv_str", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_chickadee_single", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_improper_type", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_manual_run", "libchickadee/test/test_chickadee.py::ChickadeeStringTestCase::test_no_resolve", "libchickadee/test/test_chickadee.py::ChickadeeFileTestCase::test_ipapi_resolve_query_folder", "libchickadee/test/test_chickadee.py::ChickadeeFileTestCase::test_ipapi_resolve_query_gz_file", "libchickadee/test/test_chickadee.py::ChickadeeFileTestCase::test_ipapi_resolve_query_txt_file", "libchickadee/test/test_chickadee.py::ChickadeeFileTestCase::test_ipapi_resolve_query_xlsx_file", "libchickadee/test/test_chickadee.py::ChickadeeUtilityTestCase::test_get_apikey" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-20 13:05:46+00:00
mit
1,556
chapinb__chickadee-63
diff --git a/CHANGELOG.md b/CHANGELOG.md index 104b977..fc87bab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 20200805.0 + +### Fixed + +* Addressed bug in rate limiting VirusTotal. [Issue-62](https://github.com/chapinb/chickadee/issues/62) + ## 20200802.0 ### Added diff --git a/doc_src/source/conf.py b/doc_src/source/conf.py index ad6c81a..31e098a 100644 --- a/doc_src/source/conf.py +++ b/doc_src/source/conf.py @@ -22,7 +22,7 @@ copyright = 'MIT 2020, Chapin Bryce' author = 'Chapin Bryce' # The full version, including alpha/beta/rc tags -release = '20200802' +release = '20200805' # -- General configuration --------------------------------------------------- diff --git a/libchickadee/__init__.py b/libchickadee/__init__.py index 202fa79..e7393a1 100644 --- a/libchickadee/__init__.py +++ b/libchickadee/__init__.py @@ -145,7 +145,7 @@ library from the command line. """ __author__ = 'Chapin Bryce' -__date__ = 20200802 -__version__ = 20200802.0 +__date__ = 20200805 +__version__ = 20200805.0 __license__ = 'MIT Copyright 2020 Chapin Bryce' __desc__ = '''Yet another GeoIP resolution tool.''' diff --git a/libchickadee/chickadee.py b/libchickadee/chickadee.py index fd12d15..d43deac 100644 --- a/libchickadee/chickadee.py +++ b/libchickadee/chickadee.py @@ -65,7 +65,7 @@ Usage -V, --version Displays version -l LOG, --log LOG Path to log file (default: chickadee.log) - Built by Chapin Bryce, v.20200801.0 + Built by Chapin Bryce, v.20200805.0 .. _chickadee-examples: @@ -171,7 +171,7 @@ from libchickadee.parsers.evtx import EVTXParser __author__ = 'Chapin Bryce' -__date__ = 20200407.2 +__date__ = 20200805 __license__ = 'GPLv3 Copyright 2019 Chapin Bryce' __desc__ = '''Yet another GeoIP resolution tool. @@ -672,7 +672,7 @@ def arg_handling(args): help='Include debug log messages') parser.add_argument('-V', '--version', action='version', help='Displays version', - version=str(__date__)) + version=str(__version__)) parser.add_argument( '-l', '--log', diff --git a/libchickadee/resolvers/virustotal.py b/libchickadee/resolvers/virustotal.py index 1c21411..e538089 100644 --- a/libchickadee/resolvers/virustotal.py +++ b/libchickadee/resolvers/virustotal.py @@ -84,7 +84,7 @@ from . import ResolverBase logger = logging.getLogger(__name__) __author__ = 'Chapin Bryce' -__date__ = 20200302 +__date__ = 20200805 __license__ = 'MIT Copyright 2020 Chapin Bryce' __desc__ = 'Resolver for VirusTotal' @@ -165,6 +165,7 @@ class ProResolver(ResolverBase): 'ip': self.data } + self.last_request = datetime.now() rdata = requests.get( self.uri, params=params ) diff --git a/setup.py b/setup.py index d4d126a..67ae1ca 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ """Installer for chickadee""" import setuptools -from libchickadee import __version__ +from libchickadee import __version__, __desc__, __author__ with open('README.md') as fh: long_description = fh.read() @@ -8,8 +8,8 @@ with open('README.md') as fh: setuptools.setup( name='chickadee', version=__version__, - description='Yet another GeoIP resolution tool.', - author='Chapin Bryce', + description=__desc__, + author=__author__, author_email='[email protected]', url='https://github.com/chapinb/chickadee', long_description=long_description,
chapinb/chickadee
fa9862c3ff48e6ad3e07b2ecaad74ff922eaf926
diff --git a/libchickadee/test/test_resolver_virustotal.py b/libchickadee/test/test_resolver_virustotal.py index dfb54a1..c0dd7d4 100644 --- a/libchickadee/test/test_resolver_virustotal.py +++ b/libchickadee/test/test_resolver_virustotal.py @@ -1,5 +1,6 @@ """VirusTotal Resolver Tests.""" import datetime +import time import unittest import json import os @@ -8,7 +9,7 @@ from unittest.mock import patch, MagicMock from libchickadee.resolvers.virustotal import ProResolver __author__ = 'Chapin Bryce' -__date__ = 20200114 +__date__ = 20200805 __license__ = 'MIT Copyright 2020 Chapin Bryce' __desc__ = '''Yet another GeoIP resolution tool.''' @@ -101,6 +102,16 @@ class IPAPITestCase(unittest.TestCase): self.assertIsNone(actual) self.assertEqual(mock_log.records[0].message, err_msg) + @patch("libchickadee.resolvers.virustotal.requests.get") + def test_sleeper(self, mock_requests): + initial_time = datetime.datetime.now() + self.resolver.last_request = initial_time + time.sleep(2) + mock_requests.return_value.status_code = 403 + + self.resolver.query(data='1.1.1.1') + self.assertGreaterEqual(self.resolver.last_request, initial_time + datetime.timedelta(seconds=2)) + if __name__ == "__main__": unittest.main()
VirusTotal rate limiter does not store last request time **Describe the bug** The sleeper function checks the last request time to determine how long to sleep for. This value is only set at initialization and does not update per-request. **Version (please complete the following information):** - OS: Any (macOS) - Version: 20200802.0 - Python version: 3.7.7 **Additional context**
0.0
fa9862c3ff48e6ad3e07b2ecaad74ff922eaf926
[ "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_sleeper" ]
[ "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_parse_vt_resp", "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_parse_vt_resp_2", "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_resolve_batch", "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_resolve_errors", "libchickadee/test/test_resolver_virustotal.py::IPAPITestCase::test_resolve_single" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-05 10:20:06+00:00
mit
1,557
charliequinn__python-litmos-api-4
diff --git a/README.rst b/README.rst index bbcaaf1..4de9b0d 100644 --- a/README.rst +++ b/README.rst @@ -56,7 +56,11 @@ Getting started .. code-block:: python from litmos import Litmos - litmos = Litmos({apikey}, {source}) + API_KEY = 'AXXXXXXXXXX' + LITMOS_APP_NAME = 'jins.litmos.com' + LITMOS_SERVER_URL = 'https://api.litmos.com/v1.svc' # https://support.litmos.com/hc/en-us/articles/227734667-Overview-Developer-API + litmos = Litmos(API_KEY, LITMOS_APP_NAME, LITMOS_SERVER_URL) + # --- User --- # retrieve users diff --git a/src/litmos/__init__.py b/src/litmos/__init__.py index c8637bb..4648d68 100644 --- a/src/litmos/__init__.py +++ b/src/litmos/__init__.py @@ -13,9 +13,10 @@ __version__ = "0.6.0" class Litmos(object): ACCEPTABLE_TYPES = ['User', 'Team', 'Course', 'CourseModule'] - def __init__(self, api_key, app_name): + def __init__(self, api_key, app_name, root_url='https://api.litmos.com/v1.svc'): API.api_key = api_key API.app_name = app_name + API.ROOT_URL = root_url self.litmos_api = API diff --git a/src/litmos/api.py b/src/litmos/api.py index 77486f6..f4c7032 100644 --- a/src/litmos/api.py +++ b/src/litmos/api.py @@ -6,14 +6,14 @@ import requests class API(object): - ROOT_URL = 'https://api.litmos.com/v1.svc/' + ROOT_URL = 'https://api.litmos.com/v1.svc' PAGINATION_OFFSET = 200 api_key = None app_name = None @classmethod def _base_url(cls, resource, **kwargs): - return cls.ROOT_URL + \ + return cls.ROOT_URL + "/" + \ resource + \ ("/" + kwargs['resource_id'] if kwargs.get('resource_id', None) else "") + \ ("/" + kwargs['sub_resource'] if kwargs.get('sub_resource', None) else "") + \
charliequinn/python-litmos-api
2c2ed5135dc412a4861b163415410e179cdf9428
diff --git a/tests/test_litmos_api.py b/tests/test_litmos_api.py index 4c76140..6286658 100644 --- a/tests/test_litmos_api.py +++ b/tests/test_litmos_api.py @@ -14,7 +14,7 @@ class TestLitmosAPI: API.app_name = 'app-name-123' def test_root_url(self): - eq_(API.ROOT_URL, 'https://api.litmos.com/v1.svc/') + eq_(API.ROOT_URL, 'https://api.litmos.com/v1.svc') @patch('litmos.api.requests.request') def test_all(self, request):
Help needed to assign a list of users for a course Hi Charlie, I am unable to go beyond the code mentioned below litmos = Litmos({'aXXXXXXXXXXXXX'},{'https://api.litmoseu.com/v1.svc'}) Is there anyway I could directly get the Json file downloaded. Or derive a code to assign course to a list of users Thanks in advance. Regards, Jins
0.0
2c2ed5135dc412a4861b163415410e179cdf9428
[ "tests/test_litmos_api.py::TestLitmosAPI::test_root_url" ]
[ "tests/test_litmos_api.py::TestLitmosAPI::test_perform_request_bad_response" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-02-12 18:33:13+00:00
bsd-2-clause
1,558
cherrypy__cherrypy-1578
diff --git a/cherrypy/_cperror.py b/cherrypy/_cperror.py index 6c952e91..b597c645 100644 --- a/cherrypy/_cperror.py +++ b/cherrypy/_cperror.py @@ -271,7 +271,7 @@ class HTTPRedirect(CherryPyException): 307: 'This resource has moved temporarily to ', }[status] msg += '<a href=%s>%s</a>.' - msgs = [msg % (saxutils.quoteattr(u), u) for u in self.urls] + msgs = [msg % (saxutils.quoteattr(u), escape_html(u)) for u in self.urls] response.body = ntob('<br />\n'.join(msgs), 'utf-8') # Previous code may have set C-L, so we have to reset it # (allow finalize to set it).
cherrypy/cherrypy
8c635f55c3634b722260fef501ee49fb440be3ac
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index 2e590a9d..f16efd58 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -150,6 +150,9 @@ class CoreRequestHandlingTest(helper.CPWebCase): def url_with_quote(self): raise cherrypy.HTTPRedirect("/some\"url/that'we/want") + def url_with_xss(self): + raise cherrypy.HTTPRedirect("/some<script>alert(1);</script>url/that'we/want") + def url_with_unicode(self): raise cherrypy.HTTPRedirect(ntou('тест', 'utf-8')) @@ -435,6 +438,13 @@ class CoreRequestHandlingTest(helper.CPWebCase): self.assertStatus(303) assertValidXHTML() + def test_redirect_with_xss(self): + """A redirect to a URL with HTML injected should result in page contents escaped.""" + self.getPage('/redirect/url_with_xss') + self.assertStatus(303) + assert b'<script>' not in self.body + assert b'&lt;script&gt;' in self.body + def test_redirect_with_unicode(self): """ A redirect to a URL with Unicode should return a Location
Encode URLs in redirect responses * **I'm submitting a ...** [x] bug report [ ] feature request [ ] question about the decisions made in the repository * **What is the current behavior?** The standard response page for 30x errors contains the target URL as `href` as well as clear text. * **What is the expected behavior?** Even though browsers *mostly* will not display the result, but redirect instead, you never know: Any input from unknown sources should be html-escaped. * **Please tell us about your environment:** CherryPy 3.8 until 10.1
0.0
8c635f55c3634b722260fef501ee49fb440be3ac
[ "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_redirect_with_xss" ]
[ "cherrypy/test/test_core.py::CoreRequestHandlingTest::testCookies", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testDefaultContentType", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testFavicon", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testFlatten", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testRanges", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testRedirect", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testSlashes", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testStatus", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_InternalRedirect", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_cherrypy_url", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_expose_decorator", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_multiple_headers", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_on_end_resource_status", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_redirect_with_unicode", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_gc", "cherrypy/test/test_core.py::ErrorTests::test_contextmanager", "cherrypy/test/test_core.py::ErrorTests::test_start_response_error", "cherrypy/test/test_core.py::ErrorTests::test_gc", "cherrypy/test/test_core.py::TestBinding::test_bind_ephemeral_port" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-03-11 14:37:20+00:00
bsd-3-clause
1,559
cherrypy__cherrypy-1596
diff --git a/README.rst b/README.rst index e7b7fda9..21c07ace 100644 --- a/README.rst +++ b/README.rst @@ -56,9 +56,8 @@ Additionally: - Tutorials are included in the repository: https://github.com/cherrypy/cherrypy/tree/master/cherrypy/tutorial -- A general wiki at(will be moved to github): - https://bitbucket.org/cherrypy/cherrypy/wiki/Home -- Plugins are described at: http://tools.cherrypy.org/ +- A general wiki at: + https://github.com/cherrypy/cherrypy/wiki If the docs are insufficient to address your needs, the CherryPy community has several `avenues for support @@ -70,4 +69,4 @@ Contributing Please follow the `contribution guidelines <http://docs.cherrypy.org/en/latest/contribute.html>`_. And by all means, absorb the `Zen of -CherryPy <https://bitbucket.org/cherrypy/cherrypy/wiki/ZenOfCherryPy>`_. +CherryPy <https://github.com/cherrypy/cherrypy/wiki/The-Zen-of-CherryPy>`_. diff --git a/cherrypy/_helper.py b/cherrypy/_helper.py index 5875ec0f..9b727eac 100644 --- a/cherrypy/_helper.py +++ b/cherrypy/_helper.py @@ -223,6 +223,30 @@ def url(path='', qs='', script_name=None, base=None, relative=None): if qs: qs = '?' + qs + def normalize_path(path): + if './' not in path: + return path + + # Normalize the URL by removing ./ and ../ + atoms = [] + for atom in path.split('/'): + if atom == '.': + pass + elif atom == '..': + # Don't pop from empty list + # (i.e. ignore redundant '..') + if atoms: + atoms.pop() + elif atom: + atoms.append(atom) + + newpath = '/'.join(atoms) + # Preserve leading '/' + if path.startswith('/'): + newpath = '/' + newpath + + return newpath + if cherrypy.request.app: if not path.startswith('/'): # Append/remove trailing slash from path_info as needed @@ -246,7 +270,7 @@ def url(path='', qs='', script_name=None, base=None, relative=None): if base is None: base = cherrypy.request.base - newurl = base + script_name + path + qs + newurl = base + script_name + normalize_path(path) + qs else: # No request.app (we're being called outside a request). # We'll have to guess the base from server.* attributes. @@ -256,19 +280,7 @@ def url(path='', qs='', script_name=None, base=None, relative=None): base = cherrypy.server.base() path = (script_name or '') + path - newurl = base + path + qs - - if './' in newurl: - # Normalize the URL by removing ./ and ../ - atoms = [] - for atom in newurl.split('/'): - if atom == '.': - pass - elif atom == '..': - atoms.pop() - else: - atoms.append(atom) - newurl = '/'.join(atoms) + newurl = base + normalize_path(path) + qs # At this point, we should have a fully-qualified absolute URL.
cherrypy/cherrypy
2c5643367147bae270e83dfba25c1897f37dbe18
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index f16efd58..252c1ac5 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -74,6 +74,9 @@ class CoreRequestHandlingTest(helper.CPWebCase): relative = bool(relative) return cherrypy.url(path_info, relative=relative) + def qs(self, qs): + return cherrypy.url(qs=qs) + def log_status(): Status.statuses.append(cherrypy.response.status) cherrypy.tools.log_status = cherrypy.Tool( @@ -647,6 +650,8 @@ class CoreRequestHandlingTest(helper.CPWebCase): self.assertBody('%s/url/other/page1' % self.base()) self.getPage('/url/?path_info=/other/./page1') self.assertBody('%s/other/page1' % self.base()) + self.getPage('/url/?path_info=/other/././././page1') + self.assertBody('%s/other/page1' % self.base()) # Double dots self.getPage('/url/leaf?path_info=../page1') @@ -655,6 +660,20 @@ class CoreRequestHandlingTest(helper.CPWebCase): self.assertBody('%s/url/page1' % self.base()) self.getPage('/url/leaf?path_info=/other/../page1') self.assertBody('%s/page1' % self.base()) + self.getPage('/url/leaf?path_info=/other/../../../page1') + self.assertBody('%s/page1' % self.base()) + self.getPage('/url/leaf?path_info=/other/../../../../../page1') + self.assertBody('%s/page1' % self.base()) + + # qs param is not normalized as a path + self.getPage('/url/qs?qs=/other') + self.assertBody('%s/url/qs?/other' % self.base()) + self.getPage('/url/qs?qs=/other/../page1') + self.assertBody('%s/url/qs?/other/../page1' % self.base()) + self.getPage('/url/qs?qs=../page1') + self.assertBody('%s/url/qs?../page1' % self.base()) + self.getPage('/url/qs?qs=../../page1') + self.assertBody('%s/url/qs?../../page1' % self.base()) # Output relative to current path or script_name self.getPage('/url/?path_info=page1&relative=True')
`cherrypy.url` fails to normalize path This call to `cherrypy.url` fails with `IndexError`: ``` >>> cherrypy.url(qs='../../../../../../etc/passwd') ... IndexError: pop from empty list ``` The culprit seems in this logic, which strips `newurl` of as many `atoms` as there are `..`: https://github.com/cherrypy/cherrypy/blob/master/cherrypy/_helper.py#L261,L271 There are various problems. - That logic should only applied to the "path" part of `newurl`, not to the full url. - As a consequence of the point above, `..` in the query string `qs` should not be considered - To consider: redundant `..` should be ignored, to mimic `os.path.normpath`: ``` >>> os.path.normpath('/etc/../../../usr') '/usr' ```
0.0
2c5643367147bae270e83dfba25c1897f37dbe18
[ "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_cherrypy_url" ]
[ "cherrypy/test/test_core.py::CoreRequestHandlingTest::testCookies", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testDefaultContentType", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testFavicon", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testFlatten", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testRanges", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testRedirect", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testSlashes", "cherrypy/test/test_core.py::CoreRequestHandlingTest::testStatus", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_InternalRedirect", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_expose_decorator", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_multiple_headers", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_on_end_resource_status", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_redirect_with_unicode", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_redirect_with_xss", "cherrypy/test/test_core.py::CoreRequestHandlingTest::test_gc", "cherrypy/test/test_core.py::ErrorTests::test_contextmanager", "cherrypy/test/test_core.py::ErrorTests::test_start_response_error", "cherrypy/test/test_core.py::ErrorTests::test_gc", "cherrypy/test/test_core.py::TestBinding::test_bind_ephemeral_port" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-05-17 12:22:19+00:00
bsd-3-clause
1,560
cherrypy__cherrypy-1628
diff --git a/CHANGES.rst b/CHANGES.rst index ea4f70ca..215f33ed 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,9 @@ +v11.0.1 +------- + +* #1627: Fixed issue in proxy tool where more than one port would + appear in the ``request.base`` and thus in ``cherrypy.url``. + v11.0.0 ------- diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index 2ad5a44d..4e85c9c2 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -5,6 +5,7 @@ import re from hashlib import md5 import six +from six.moves import urllib import cherrypy from cherrypy._cpcompat import text_or_bytes @@ -195,10 +196,8 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For', if lbase is not None: base = lbase.split(',')[0] if not base: - base = request.headers.get('Host', '127.0.0.1') - port = request.local.port - if port != 80: - base += ':%s' % port + default = urllib.parse.urlparse(request.base).netloc + base = request.headers.get('Host', default) if base.find('://') == -1: # add http:// or https:// if needed
cherrypy/cherrypy
13dc1d79563973517896933b324edf9ca978e582
diff --git a/cherrypy/test/test_proxy.py b/cherrypy/test/test_proxy.py index 0cb209fb..4d34440a 100644 --- a/cherrypy/test/test_proxy.py +++ b/cherrypy/test/test_proxy.py @@ -58,6 +58,13 @@ class ProxyTest(helper.CPWebCase): return ("Browse to <a href='%s'>this page</a>." % cherrypy.url('/this/new/page')) + @cherrypy.expose + @cherrypy.config(**{ + 'tools.proxy.base': None, + }) + def base_no_base(self): + return cherrypy.request.base + for sn in script_names: cherrypy.tree.mount(Root(sn), sn) @@ -136,3 +143,12 @@ class ProxyTest(helper.CPWebCase): self.getPage('/xhost/', headers=[('X-Host', 'www.example.test')]) self.assertHeader('Location', '%s://www.example.test/xhost' % self.scheme) + + def test_no_base_port_in_host(self): + """ + If no base is indicated, and the host header is used to resolve + the base, it should rely on the host header for the port also. + """ + headers = {'Host': 'localhost:8080'}.items() + self.getPage('/base_no_base', headers=headers) + self.assertBody('http://localhost:8080')
Proxy tools causes double port, creating broken links Consider this script: ``` __requires__ = ['cherrypy'] import os import cherrypy class Server: @cherrypy.expose def index(self): return cherrypy.url('/foo/') @classmethod def run(cls): config = { 'global': { 'server.socket_port': int(os.environ.get('PORT', 8080)), 'tools.proxy.on': True, }, } cherrypy.quickstart(cls(), config=config) __name__ == '__main__' and Server.run() ``` Run it and request `/` and you'll get: ``` $ curl http://localhost:8080/ http://localhost:8080:8080/foo/ ```
0.0
13dc1d79563973517896933b324edf9ca978e582
[ "cherrypy/test/test_proxy.py::ProxyTest::test_no_base_port_in_host" ]
[ "cherrypy/test/test_proxy.py::ProxyTest::testProxy", "cherrypy/test/test_proxy.py::ProxyTest::test_gc" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-08-29 00:45:10+00:00
bsd-3-clause
1,561
cherrypy__cherrypy-1785
diff --git a/CHANGES.rst b/CHANGES.rst index 7862fc93..f9961319 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,9 @@ +v18.1.2 (unreleased) +-------------------- + +* Fixed :issue:`1377` via :pr:`1785`: Restore a native WSGI-less + HTTP server support. + v18.1.1 ------- diff --git a/cherrypy/_cpnative_server.py b/cherrypy/_cpnative_server.py index 55653c35..e9671d28 100644 --- a/cherrypy/_cpnative_server.py +++ b/cherrypy/_cpnative_server.py @@ -9,6 +9,7 @@ import cheroot.server import cherrypy from cherrypy._cperror import format_exc, bare_error from cherrypy.lib import httputil +from ._cpcompat import tonative class NativeGateway(cheroot.server.Gateway): @@ -21,21 +22,25 @@ class NativeGateway(cheroot.server.Gateway): req = self.req try: # Obtain a Request object from CherryPy - local = req.server.bind_addr + local = req.server.bind_addr # FIXME: handle UNIX sockets + local = tonative(local[0]), local[1] local = httputil.Host(local[0], local[1], '') - remote = req.conn.remote_addr, req.conn.remote_port + remote = tonative(req.conn.remote_addr), req.conn.remote_port remote = httputil.Host(remote[0], remote[1], '') - scheme = req.scheme - sn = cherrypy.tree.script_name(req.uri or '/') + scheme = tonative(req.scheme) + sn = cherrypy.tree.script_name(tonative(req.uri or '/')) if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] - method = req.method - path = req.path - qs = req.qs or '' - headers = req.inheaders.items() + method = tonative(req.method) + path = tonative(req.path) + qs = tonative(req.qs or '') + headers = ( + (tonative(h), tonative(v)) + for h, v in req.inheaders.items() + ) rfile = req.rfile prev = None @@ -52,8 +57,11 @@ class NativeGateway(cheroot.server.Gateway): # Run the CherryPy Request object and obtain the # response try: - request.run(method, path, qs, - req.request_protocol, headers, rfile) + request.run( + method, path, qs, + tonative(req.request_protocol), + headers, rfile, + ) break except cherrypy.InternalRedirect: ir = sys.exc_info()[1]
cherrypy/cherrypy
0f8523cd36153194c50b9b900f72591a44d5b95f
diff --git a/cherrypy/test/test_native.py b/cherrypy/test/test_native.py index caebc3f4..08bf9997 100644 --- a/cherrypy/test/test_native.py +++ b/cherrypy/test/test_native.py @@ -32,4 +32,7 @@ def cp_native_server(request): def test_basic_request(cp_native_server): """A request to a native server should succeed.""" - cp_native_server.get('/') + resp = cp_native_server.get('/') + assert resp.ok + assert resp.status_code == 200 + assert resp.text == 'Hello World!'
disabling wsgi interface fails under python3 Originally reported by: **Tim Miller (Bitbucket: [lashni](http://bitbucket.org/lashni), GitHub: Unknown)** --- http://docs.cherrypy.org/en/latest/advanced.html#no-need-for-the-wsgi-interface Error is encountered when the example code from the link above is run under a python 3.4.3 virtualenv on archlinux, traceback triggers when the server is accessed. Error doesn't occur with python 2.7.10. Happens with both current head and CherryPy 3.8.0. ``` [19/Jul/2015:17:41:01] ENGINE Listening for SIGUSR1. [19/Jul/2015:17:41:01] ENGINE Listening for SIGTERM. [19/Jul/2015:17:41:01] ENGINE Listening for SIGHUP. [19/Jul/2015:17:41:01] ENGINE Bus STARTING CherryPy Checker: The Application mounted at '' has an empty config. [19/Jul/2015:17:41:01] ENGINE Started monitor thread '_TimeoutMonitor'. [19/Jul/2015:17:41:01] ENGINE Started monitor thread 'Autoreloader'. [19/Jul/2015:17:41:01] ENGINE Serving on http://127.0.0.1:8080 [19/Jul/2015:17:41:01] ENGINE Bus STARTED [19/Jul/2015:17:41:05] NATIVE_ADAPTER Traceback (most recent call last): File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cpnative_server.py", line 27, in respond sn = cherrypy.tree.script_name(req.uri or "/") File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cptree.py", line 257, in script_name path = path[:path.rfind("/")] TypeError: 'str' does not support the buffer interface ValueError('invalid literal for int() with base 10: "b\'5"',) Traceback (most recent call last): File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cpnative_server.py", line 27, in respond sn = cherrypy.tree.script_name(req.uri or "/") File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cptree.py", line 257, in script_name path = path[:path.rfind("/")] TypeError: 'str' does not support the buffer interface During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/wsgiserver/wsgiserver3.py", line 1068, in communicate req.respond() File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/wsgiserver/wsgiserver3.py", line 856, in respond self.server.gateway(self).respond() File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cpnative_server.py", line 88, in respond self.send_response(s, h, b) File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/_cpnative_server.py", line 101, in send_response req.send_headers() File "/home/lashni/dev/serve/lib/python3.4/site-packages/cherrypy/wsgiserver/wsgiserver3.py", line 912, in send_headers status = int(self.status[:3]) ValueError: invalid literal for int() with base 10: "b'5" ``` --- - Bitbucket: https://bitbucket.org/cherrypy/cherrypy/issue/1377
0.0
0f8523cd36153194c50b9b900f72591a44d5b95f
[ "cherrypy/test/test_native.py::test_basic_request" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-06-22 22:39:52+00:00
bsd-3-clause
1,562
cherrypy__cherrypy-1976
diff --git a/CHANGES.rst b/CHANGES.rst index 697d77ef..35b3f895 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,12 @@ +v18.8.0 +------- + +* :issue:`1974`: Dangerous characters received in a host header + encoded using RFC 2047 are now elided by default. Currently, + dangerous characters are defined as CR and LF. The original + value is still available as ``cherrypy.request.headers['Host'].raw`` + if needed. + v18.7.0 ------- diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py index b380bb75..a661112c 100644 --- a/cherrypy/_cprequest.py +++ b/cherrypy/_cprequest.py @@ -742,6 +742,9 @@ class Request(object): if self.protocol >= (1, 1): msg = "HTTP/1.1 requires a 'Host' request header." raise cherrypy.HTTPError(400, msg) + else: + headers['Host'] = httputil.SanitizedHost(dict.get(headers, 'Host')) + host = dict.get(headers, 'Host') if not host: host = self.local.name or self.local.ip diff --git a/cherrypy/lib/httputil.py b/cherrypy/lib/httputil.py index eedf8d89..ced310a0 100644 --- a/cherrypy/lib/httputil.py +++ b/cherrypy/lib/httputil.py @@ -516,3 +516,33 @@ class Host(object): def __repr__(self): return 'httputil.Host(%r, %r, %r)' % (self.ip, self.port, self.name) + + +class SanitizedHost(str): + r""" + Wraps a raw host header received from the network in + a sanitized version that elides dangerous characters. + + >>> SanitizedHost('foo\nbar') + 'foobar' + >>> SanitizedHost('foo\nbar').raw + 'foo\nbar' + + A SanitizedInstance is only returned if sanitization was performed. + + >>> isinstance(SanitizedHost('foobar'), SanitizedHost) + False + """ + dangerous = re.compile(r'[\n\r]') + + def __new__(cls, raw): + sanitized = cls._sanitize(raw) + if sanitized == raw: + return raw + instance = super().__new__(cls, sanitized) + instance.raw = raw + return instance + + @classmethod + def _sanitize(cls, raw): + return cls.dangerous.sub('', raw)
cherrypy/cherrypy
12a06bf717effe21973953f30771a56c74130621
diff --git a/cherrypy/test/test_request_obj.py b/cherrypy/test/test_request_obj.py index 3aaa8e81..2478aabe 100644 --- a/cherrypy/test/test_request_obj.py +++ b/cherrypy/test/test_request_obj.py @@ -756,6 +756,16 @@ class RequestObjectTests(helper.CPWebCase): headers=[('Content-type', 'application/json')]) self.assertBody('application/json') + def test_dangerous_host(self): + """ + Dangerous characters like newlines should be elided. + Ref #1974. + """ + # foo\nbar + encoded = '=?iso-8859-1?q?foo=0Abar?=' + self.getPage('/headers/Host', headers=[('Host', encoded)]) + self.assertBody('foobar') + def test_basic_HTTPMethods(self): helper.webtest.methods_with_bodies = ('POST', 'PUT', 'PROPFIND', 'PATCH')
Undisclosed security issue This issue was reported to [email protected] as a security issue on 2022-06-18. I'm documenting the investigation in a hackmd.io document, which I will put here after the resolution is concluded.
0.0
12a06bf717effe21973953f30771a56c74130621
[ "cherrypy/test/test_request_obj.py::RequestObjectTests::test_dangerous_host" ]
[ "cherrypy/test/test_request_obj.py::RequestObjectTests::testAbsoluteURIPathInfo", "cherrypy/test/test_request_obj.py::RequestObjectTests::testEmptyThreadlocals", "cherrypy/test/test_request_obj.py::RequestObjectTests::testErrorHandling", "cherrypy/test/test_request_obj.py::RequestObjectTests::testExpect", "cherrypy/test/test_request_obj.py::RequestObjectTests::testHeaderElements", "cherrypy/test/test_request_obj.py::RequestObjectTests::testParamErrors", "cherrypy/test/test_request_obj.py::RequestObjectTests::testParams", "cherrypy/test/test_request_obj.py::RequestObjectTests::testRelativeURIPathInfo", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_CONNECT_method", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_CONNECT_method_invalid_authority", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_basic_HTTPMethods", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_encoded_headers", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_header_presence", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_per_request_uuid4", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_repeated_headers", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_scheme", "cherrypy/test/test_request_obj.py::RequestObjectTests::test_gc" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-07-17 20:31:25+00:00
bsd-3-clause
1,563
cherrypy__cherrypy-2006
diff --git a/.git_archival.txt b/.git_archival.txt new file mode 100644 index 00000000..3994ec0a --- /dev/null +++ b/.git_archival.txt @@ -0,0 +1,4 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true)$ +ref-names: $Format:%D$ diff --git a/.gitattributes b/.gitattributes index 00e5815f..84cc7a59 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,1 +1,7 @@ +# Needed for setuptools-scm-git-archive +.git_archival.txt export-subst + +# Blame ignore list entries are expected to always be appended, never edited +.git-blame-ignore-revs merge=union + /CHANGES.rst merge=union diff --git a/docs/conf.py b/docs/conf.py index 4a0ceb54..ebd25867 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -203,7 +203,7 @@ link_files = { ), replace=[ dict( - pattern=r'^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n', + pattern=r'(?m)^((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n', with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', ), ], diff --git a/pyproject.toml b/pyproject.toml index a29ffa3b..2c3a7cff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,7 @@ requires = [ "setuptools >= 45", # Plugins - "setuptools_scm[toml] >= 3.5", - "setuptools_scm_git_archive >= 1.1", + "setuptools_scm[toml] >= 7.0.0", ] build-backend = "setuptools.build_meta"
cherrypy/cherrypy
3567f23fca55bad3a024f74fcb0c199ce25ee8f2
diff --git a/cherrypy/test/test_session.py b/cherrypy/test/test_session.py index 80567504..f566c37f 100755 --- a/cherrypy/test/test_session.py +++ b/cherrypy/test/test_session.py @@ -146,9 +146,14 @@ class SessionTest(helper.CPWebCase): def teardown_class(cls): """Clean up sessions.""" super(cls, cls).teardown_class() + try: + files_to_clean = localDir.iterdir() # Python 3.8+ + except AttributeError: + files_to_clean = localDir.listdir() # Python 3.6-3.7 + consume( file.remove_p() - for file in localDir.iterdir() + for file in files_to_clean if file.basename().startswith( sessions.FileSession.SESSION_PREFIX )
`setuptools_scm_git_archive` is obsolete The `setuptools_scm_git_archive` package is obsolete. Please switch to `setuptools_scm >= 7.0.0`.
0.0
3567f23fca55bad3a024f74fcb0c199ce25ee8f2
[ "cherrypy/test/test_session.py::SessionTest::test_0_Session" ]
[ "cherrypy/test/test_session.py::SessionTest::test_1_Ram_Concurrency", "cherrypy/test/test_session.py::SessionTest::test_2_File_Concurrency", "cherrypy/test/test_session.py::SessionTest::test_3_Redirect", "cherrypy/test/test_session.py::SessionTest::test_4_File_deletion", "cherrypy/test/test_session.py::SessionTest::test_5_Error_paths", "cherrypy/test/test_session.py::SessionTest::test_6_regenerate", "cherrypy/test/test_session.py::SessionTest::test_7_session_cookies", "cherrypy/test/test_session.py::SessionTest::test_8_Ram_Cleanup", "cherrypy/test/test_session.py::SessionTest::test_gc" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-12-14 12:12:15+00:00
bsd-3-clause
1,564
chezou__tabula-py-151
diff --git a/README.md b/README.md index 8820792..da014ec 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,8 @@ This instruction is originally written by [@lahoffm](https://github.com/lahoffm) - multiple_tables (bool, optional): - (Experimental) Extract multiple tables. - This option uses JSON as an intermediate format, so if tabula-java output format will change, this option doesn't work. +- user_agent (str, optional) + - Set a custom user-agent when download a pdf from a url. Otherwise it uses the default urllib.request user-agent ## FAQ diff --git a/tabula/file_util.py b/tabula/file_util.py index e6fa311..dc5c0ff 100644 --- a/tabula/file_util.py +++ b/tabula/file_util.py @@ -6,12 +6,12 @@ PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] >= 3 if PY3: - from urllib.request import urlopen + from urllib.request import urlopen, Request from urllib.parse import urlparse as parse_url from urllib.parse import uses_relative, uses_netloc, uses_params text_type = str else: - from urllib2 import urlopen + from urllib2 import urlopen, Request from urlparse import urlparse as parse_url from urlparse import uses_relative, uses_netloc, uses_params text_type = unicode @@ -21,7 +21,7 @@ _VALID_URLS = set(uses_relative + uses_netloc + uses_params) _VALID_URLS.discard('') -def localize_file(path_or_buffer): +def localize_file(path_or_buffer, user_agent=None): '''Ensure localize target file. If the target file is remote, this function fetches into local storage. @@ -38,7 +38,10 @@ def localize_file(path_or_buffer): path_or_buffer = _stringify_path(path_or_buffer) if _is_url(path_or_buffer): - req = urlopen(path_or_buffer) + if user_agent: + req = urlopen(_create_request(path_or_buffer, user_agent)) + else: + req = urlopen(path_or_buffer) filename = os.path.basename(req.geturl()) if os.path.splitext(filename)[-1] is not ".pdf": pid = os.getpid() @@ -71,6 +74,10 @@ def _is_url(url): return False +def _create_request(path_or_buffer, user_agent): + req_headers = {'User-Agent': user_agent} + return Request(path_or_buffer, headers=req_headers) + def is_file_like(obj): '''Check file like object diff --git a/tabula/wrapper.py b/tabula/wrapper.py index 37801fe..0dabaf9 100644 --- a/tabula/wrapper.py +++ b/tabula/wrapper.py @@ -127,7 +127,9 @@ def read_pdf(input_path, if not any(filter(r.find, java_options)): java_options = java_options + ['-Dfile.encoding=UTF8'] - path, temporary = localize_file(input_path) + user_agent = kwargs.pop('user_agent', None) + + path, temporary = localize_file(input_path, user_agent) if not os.path.exists(path): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)
chezou/tabula-py
baacafe257d013e42564c9477f54c1b93522ef5b
diff --git a/tests/test_read_pdf_table.py b/tests/test_read_pdf_table.py index 3907535..efe30ee 100644 --- a/tests/test_read_pdf_table.py +++ b/tests/test_read_pdf_table.py @@ -12,9 +12,11 @@ import subprocess try: FileNotFoundError from unittest.mock import patch + from urllib.request import Request except NameError: FileNotFoundError = IOError from mock import patch + from urllib2 import Request class TestReadPdfTable(unittest.TestCase): @@ -30,6 +32,12 @@ class TestReadPdfTable(unittest.TestCase): df = tabula.read_pdf(uri) self.assertTrue(isinstance(df, pd.DataFrame)) + def test_read_remote_pdf_with_custom_user_agent(self): + uri = "https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/12s0324.pdf" + + df = tabula.read_pdf(uri, user_agent='Mozilla/5.0') + self.assertTrue(isinstance(df, pd.DataFrame)) + def test_read_pdf_into_json(self): pdf_path = 'tests/resources/data.pdf' expected_json = 'tests/resources/data_1.json' diff --git a/tests/test_util.py b/tests/test_util.py index e4825d9..ab523c4 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -1,11 +1,36 @@ import unittest import tabula +try: + FileNotFoundError + from unittest.mock import patch, MagicMock + from urllib.request import Request +except NameError: + FileNotFoundError = IOError + from mock import patch, MagicMock + from urllib2 import Request + class TestUtil(unittest.TestCase): def test_environment_info(self): self.assertEqual(tabula.environment_info(), None) + @patch('tabula.file_util.shutil.copyfileobj') + @patch('tabula.file_util.urlopen') + @patch('tabula.file_util._create_request') + def test_localize_file_with_user_agent(self, mock_fun, mock_urlopen, mock_copyfileobj): + uri = "https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/12s0324.pdf" + user_agent='Mozilla/5.0' + + cm = MagicMock() + cm.getcode.return_value = 200 + cm.read.return_value = b'contents' + cm.geturl.return_value = uri + mock_urlopen.return_value = cm + + tabula.file_util.localize_file(uri, user_agent=user_agent) + mock_fun.assert_called_with(uri, user_agent) + if __name__ == '__main__': unittest.main()
[Feature request] Set User-agent **Is your feature request related to a problem? Please describe.** The original problem is #144, which is some host denies accessing from urllib. **Describe the solution you'd like** Set User-agent when localizing a file. **Describe alternatives you've considered** Download a PDF manually. **Additional context** Nothing.
0.0
baacafe257d013e42564c9477f54c1b93522ef5b
[ "tests/test_util.py::TestUtil::test_localize_file_with_user_agent" ]
[ "tests/test_read_pdf_table.py::TestReadPdfTable::test_convert_into_exception", "tests/test_read_pdf_table.py::TestReadPdfTable::test_read_pdf_exception", "tests/test_read_pdf_table.py::TestReadPdfTable::test_read_pdf_with_jar_path", "tests/test_util.py::TestUtil::test_environment_info" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-06-13 15:27:58+00:00
mit
1,565
chezou__tabula-py-188
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..4b95b89 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,23 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-added-large-files + - repo: https://github.com/asottile/seed-isort-config + rev: v1.9.3 + hooks: + - id: seed-isort-config + - repo: https://github.com/pre-commit/mirrors-isort + rev: v4.3.21 + hooks: + - id: isort + - repo: https://github.com/python/black + rev: stable + hooks: + - id: black + language_version: python3.8 diff --git a/.travis.yml b/.travis.yml index dfed399..269f880 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ language: python python: - 3.6 - 3.7 +- 3.8 before_install: - pip install --upgrade setuptools install: diff --git a/setup.cfg b/setup.cfg index 50f2553..ae94dd5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -59,4 +59,4 @@ exclude = line_length = 88 multi_line_output = 3 include_trailing_comma = True -known_third_party = pandas,numpy,distro +known_third_party = nox,numpy,pandas,pkg_resources,setuptools,sphinx_rtd_theme diff --git a/tabula/wrapper.py b/tabula/wrapper.py index 81d4de2..fdf7b20 100644 --- a/tabula/wrapper.py +++ b/tabula/wrapper.py @@ -77,7 +77,16 @@ def _run(java_options, options, path=None, encoding="utf-8"): args.append(path) try: - return subprocess.check_output(args) + result = subprocess.run( + args, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, + check=True, + ) + if result.stderr: + logger.warning("Got stderr: {}".format(result.stderr.decode(encoding))) + return result.stdout except FileNotFoundError: raise JavaNotFoundError(JAVA_NOT_FOUND_ERROR) except subprocess.CalledProcessError as e:
chezou/tabula-py
6b58816c93fb8d89c99981a7f19028a5f93065a0
diff --git a/tests/test_read_pdf_table.py b/tests/test_read_pdf_table.py index 32e4063..40773e5 100644 --- a/tests/test_read_pdf_table.py +++ b/tests/test_read_pdf_table.py @@ -3,6 +3,7 @@ import json import os import platform import shutil +import subprocess import tempfile import unittest from unittest.mock import patch @@ -229,7 +230,7 @@ class TestReadPdfTable(unittest.TestCase): self.assertEqual(len(dfs), 4) self.assertTrue(dfs[0].equals(pd.read_csv(self.expected_csv1))) - @patch("subprocess.check_output") + @patch("subprocess.run") @patch("tabula.wrapper._jar_path") def test_read_pdf_with_jar_path(self, jar_func, mock_fun): jar_func.return_value = "/tmp/tabula-java.jar" @@ -248,7 +249,13 @@ class TestReadPdfTable(unittest.TestCase): "--guess", "tests/resources/data.pdf", ] - mock_fun.assert_called_with(target_args) + subp_args = { + "stdout": subprocess.PIPE, + "stderr": subprocess.PIPE, + "stdin": subprocess.DEVNULL, + "check": True, + } + mock_fun.assert_called_with(target_args, **subp_args) if __name__ == "__main__":
Getting 'OSError: [WinError 6] The handle is invalid' when i host tabula in IIS # Check list before submit Write and check the following questionaries. - [ ] Did you read [FAQ](https://tabula-py.readthedocs.io/en/latest/faq.html)? YES - [ ] (Optional, but really helpful) Your PDF URL: ? - [ ] Paste the output of `import tabula; tabula.environment_info()` on Python REPL: ? >>> import tabula >>> tabula.environment_info() Python version: 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] Java version: java version "1.8.0_231" Java(TM) SE Runtime Environment (build 1.8.0_231-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode) tabula-py version: 1.4.1 platform: Windows-8.1-6.3.9600-SP0 >>> If not possible to execute `tabula.environment_info()`, please answer following questions manually. - [ ] Paste the output of `python --version` command on your terminal: ? - [ ] Paste the output of `java -version` command on your terminal: ? - [ ] Does `java -h` command work well?; Ensure your java command is included in `PATH` - [ ] Write your OS and it's version: ? # What did you do when you faced the problem? I am publishing my python code using Visual Studio 2019 It is running well in local when i access the local url but when i run it using hosted url in IIS it shows following error ## Expected behavior: Should run on IIS ## Actual behavior: Code running fine in Local but not in IIS ``` File "C:\Program Files (x86)\Python37\lib\site-packages\tabula\wrapper.py", line 147, in read_pdf output = _run(java_options, kwargs, path, encoding) File "C:\Program Files (x86)\Python37\lib\site-packages\tabula\wrapper.py", line 67, in _run return subprocess.check_output(args) File "C:\Program Files (x86)\Python37\lib\subprocess.py", line 395, in check_output **kwargs).stdout File "C:\Program Files (x86)\Python37\lib\subprocess.py", line 472, in run with Popen(*popenargs, **kwargs) as process: File "C:\Program Files (x86)\Python37\lib\subprocess.py", line 728, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Program Files (x86)\Python37\lib\subprocess.py", line 1061, in _get_handles errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) OSError: [WinError 6] The handle is invalid ```
0.0
6b58816c93fb8d89c99981a7f19028a5f93065a0
[ "tests/test_read_pdf_table.py::TestReadPdfTable::test_read_pdf_with_jar_path" ]
[ "tests/test_read_pdf_table.py::TestReadPdfTable::test_convert_into_exception", "tests/test_read_pdf_table.py::TestReadPdfTable::test_read_pdf_exception" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-11-25 15:09:24+00:00
mit
1,566
chezou__tabula-py-331
diff --git a/tabula/util.py b/tabula/util.py index ed0a61e..eacbad2 100644 --- a/tabula/util.py +++ b/tabula/util.py @@ -208,12 +208,14 @@ class TabulaOption: if any(type(e) in [list, tuple] for e in self.area): for e in self.area: e = cast(Iterable[float], e) + _validate_area(e) __area = _format_with_relative(e, self.relative_area) __options += ["--area", __area] multiple_areas = True else: area = cast(Iterable[float], self.area) + _validate_area(area) __area = _format_with_relative(area, self.relative_area) __options += ["--area", __area] @@ -233,6 +235,9 @@ class TabulaOption: __options += ["--outfile", self.output_path] if self.columns: + if self.columns != sorted(self.columns): + raise ValueError("columns option should be sorted") + __columns = _format_with_relative(self.columns, self.relative_columns) __options += ["--columns", __columns] @@ -253,3 +258,20 @@ def _format_with_relative(values: Iterable[float], is_relative: bool) -> str: value_str = ",".join(map(str, values)) return f"{percent}{value_str}" + + +def _validate_area(values: Iterable[float]) -> None: + value_length = len(list(values)) + if value_length != 4: + raise ValueError( + f"area should have 4 values for each option but {values} has {value_length}" + ) + top, left, bottom, right = values + if top >= bottom: + raise ValueError( + f"area option bottom={bottom} should be greater than top={top}" + ) + if left >= right: + raise ValueError( + f"area option right={right} should be greater than left={left}" + )
chezou/tabula-py
5c7bd93a7c57b880853d5e2c8c04bb73ecb44aca
diff --git a/tests/test_util.py b/tests/test_util.py index 579e2f2..8202360 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -76,6 +76,30 @@ class TestUtil(unittest.TestCase): self.assertTrue(fname.endswith("123456789012345678901234567890.pdf")) self.addCleanup(os.remove, fname) + def test_tabula_option_area_order(self): + self.assertTrue( + type(tabula.util.TabulaOption(area=[2, 3, 4, 6]).build_option_list()), list + ) + with self.assertRaises(ValueError): + tabula.util.TabulaOption(area=[3, 4, 1]).build_option_list() + with self.assertRaises(ValueError): + tabula.util.TabulaOption(area=[3, 4, 1, 2]).build_option_list() + self.assertTrue( + type(tabula.util.TabulaOption(area=[[2, 3, 4, 6]]).build_option_list()), + list, + ) + with self.assertRaises(ValueError): + tabula.util.TabulaOption(area=[[3, 4, 1]]).build_option_list() + with self.assertRaises(ValueError): + tabula.util.TabulaOption(area=[[3, 4, 1, 2]]).build_option_list() + + def test_tabula_option_columns_order(self): + self.assertTrue( + type(tabula.util.TabulaOption(columns=[2, 3, 4]).build_option_list()), list + ) + with self.assertRaises(ValueError): + tabula.util.TabulaOption(columns=[3, 4, 1]).build_option_list() + if __name__ == "__main__": unittest.main()
Assert column option **Is your feature request related to a problem? Please describe.** When given invalid columns option, it passes through to tabula-java and the error message isn't clear. https://stackoverflow.com/questions/70925281/error-in-tabula-tabula-py-when-specifying-area-parameter **Describe the solution you'd like** <!--- A clear and concise description of what you want to happen. --> Have a validation before calling tabula-java would be nice. **Describe alternatives you've considered** <!--- A clear and concise description of any alternative solutions or features you've considered. --> Just google. **Additional context** <!--- Add any other context or screenshots about the feature request here. -->
0.0
5c7bd93a7c57b880853d5e2c8c04bb73ecb44aca
[ "tests/test_util.py::TestUtil::test_tabula_option_area_order", "tests/test_util.py::TestUtil::test_tabula_option_columns_order" ]
[ "tests/test_util.py::TestUtil::test_environment_info", "tests/test_util.py::TestUtil::test_localize_file_with_long_url", "tests/test_util.py::TestUtil::test_localize_file_with_non_ascii_url", "tests/test_util.py::TestUtil::test_localize_file_with_user_agent" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-11-24 15:50:14+00:00
mit
1,567
childsish__dynamic-yaml-18
diff --git a/dynamic_yaml/yaml_wrappers.py b/dynamic_yaml/yaml_wrappers.py index 14c5ecc..1a08d27 100644 --- a/dynamic_yaml/yaml_wrappers.py +++ b/dynamic_yaml/yaml_wrappers.py @@ -78,6 +78,10 @@ class YamlList(DynamicYamlObject, MutableSequence): super().__setattr__('_collection', list(*args, **kwargs)) super().__setattr__('_root', YamlDict([(YamlList.ROOT_NAME, self)])) + def __iter__(self): + for i in range(len(self)): + yield self[i] + def insert(self, index: int, object): super().__getattribute__('_collection').insert(index, object)
childsish/dynamic-yaml
73895727841024969b854b1c524ce8aa70527f46
diff --git a/tests/test_dynamic_yaml.py b/tests/test_dynamic_yaml.py index c666952..3cd4bee 100644 --- a/tests/test_dynamic_yaml.py +++ b/tests/test_dynamic_yaml.py @@ -197,6 +197,34 @@ class TestDynamicYaml(TestCase): res = load(config, recursive=True) inner_test(**res) + def test_list_iteration(self): + config = ''' + targets: + v1: value1 + v2: value2 + query: + - '{targets.v1}' + - '{targets.v2}' + ''' + + res = load(config) + self.assertEqual(['value1', 'value2'], list(res.query)) + + def test_dict_iteration(self): + config = ''' + targets: + v1: value1 + v2: value2 + query: + v1: '{targets.v1}' + v2: '{targets.v2}' + ''' + + res = load(config) + self.assertEqual(['v1', 'v2'], list(res.query)) + self.assertEqual(['value1', 'value2'], list(res.query.values())) + self.assertEqual([('v1', 'value1'), ('v2', 'value2')], list(res.query.items())) + if __name__ == '__main__': import sys
[Enhancement] - Method to resolve the dynamic object Ran into the issue when trying to pass in a list to a pandas dataframe. I was trying to define some columns, but the list of columns wouldn't resolve. See below example: ```python import dynamic_yaml import pandas as pd yml = ''' names: n1: "name1" n2: "name2" columns: - "{names.n1}" - "{names.n2}" ''' if __name__ == '__main__': config = dynamic_yaml.load(yml) df = pd.DataFrame(columns=config.columns) print(df.columns) ``` Yeilds: ``` Index(['{names.n1}', '{names.n2}'], dtype='object') ``` So either after a fix that resolves the object when passed, or a method I can call on the object such as `config.columns.as_list()` or `config.columns.as_set()` or `config.columns.resolve()`. Not sure what the best approach is. Current approach is to unpack and store in a variable. Roughly the following: ```python cols = [config.columns[x] for x in range(len(config.columns))] ```
0.0
73895727841024969b854b1c524ce8aa70527f46
[ "tests/test_dynamic_yaml.py::TestDynamicYaml::test_list_iteration" ]
[ "tests/test_dynamic_yaml.py::TestDynamicYaml::test_argparse", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_deeply_nested_dict", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_dict", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_dict_iteration", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_keyword_args", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_list", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_list_resolution", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_nested_dict", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_recursive", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_deeply_nested", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_missing", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_nested", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_nested_update", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_simple", "tests/test_dynamic_yaml.py::TestDynamicYaml::test_resolve_simple_update" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-11-11 10:49:24+00:00
mit
1,568
childsish__dynamic-yaml-31
diff --git a/dynamic_yaml/__init__.py b/dynamic_yaml/__init__.py index 2ebbab4..5245f7e 100644 --- a/dynamic_yaml/__init__.py +++ b/dynamic_yaml/__init__.py @@ -37,8 +37,8 @@ def load(stream, loader=DynamicYamlLoader, recursive=False): return result -def dump(data, *args, **kwargs): - return yaml.dump(data, *args, **kwargs) +def dump(data, sort_keys=False, *args, **kwargs): + return yaml.dump(data, sort_keys=sort_keys, *args, **kwargs) add_wrappers(DynamicYamlLoader)
childsish/dynamic-yaml
bed4e61cb46744dc8e486cc83097cef010f94557
diff --git a/tests/test_representations.py b/tests/test_representations.py index f2a3599..f8adacb 100644 --- a/tests/test_representations.py +++ b/tests/test_representations.py @@ -34,6 +34,34 @@ parameters: {tool1: {phase1: {subparameters: [0.5, 0.6]}, phase2: {subparameters project_name: hello-world'''), yaml.safe_load(dump(res))) + def test_insert_order_keys(self): + config = ''' + one: 1 + two: 2 + three: 3 + four: 4 + five: 5 + ''' + + self.assertEqual( + dump(load(config)), + 'one: 1\ntwo: 2\nthree: 3\nfour: 4\nfive: 5\n' + ) + + def test_sorted_keys(self): + config = ''' + one: 1 + two: 2 + three: 3 + four: 4 + five: 5 + ''' + + self.assertEqual( + dump(load(config), sort_keys=True), + 'five: 5\nfour: 4\none: 1\nthree: 3\ntwo: 2\n' + ) + if __name__ == '__main__': import sys
How to preserve order when dumping? How to preserve order when dumping?
0.0
bed4e61cb46744dc8e486cc83097cef010f94557
[ "tests/test_representations.py::TestDynamicYaml::test_insert_order_keys" ]
[ "tests/test_representations.py::TestDynamicYaml::test_json_dump", "tests/test_representations.py::TestDynamicYaml::test_sorted_keys" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2024-04-09 20:44:23+00:00
mit
1,569
chimpler__pyhocon-124
diff --git a/.travis.yml b/.travis.yml index cffa9ba..368f17e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,13 @@ language: python -python: 2.7 -env: - - TOX_ENV=py26 - - TOX_ENV=py27 - - TOX_ENV=py33 - - TOX_ENV=py34 -install: pip install tox coveralls -before_script: tox -e flake8 -script: tox -e ${TOX_ENV} +python: + - 2.6 + - 2.7 + - 3.3 + - 3.4 + - 3.6 +before_install: pip install --upgrade setuptools +install: pip install tox tox-travis coveralls +before_script: if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then tox -e flake8; fi +script: tox -r after_success: coveralls sudo: false diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index ca015ff..6993aef 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -220,6 +220,8 @@ class ConfigTree(OrderedDict): """ value = self.get(key, default) if value == default: + if key in self: + del self[key] return default lst = ConfigTree.parse_key(key) diff --git a/pyhocon/tool.py b/pyhocon/tool.py index 8620fc2..241fd35 100644 --- a/pyhocon/tool.py +++ b/pyhocon/tool.py @@ -3,6 +3,8 @@ import logging import sys from pyhocon import ConfigFactory from pyhocon.config_tree import ConfigTree +from pyhocon.config_tree import NoneValue + try: basestring @@ -52,7 +54,7 @@ class HOCONConverter(object): lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' ')) elif isinstance(config, basestring): lines = '"{value}"'.format(value=config.replace('\n', '\\n').replace('"', '\\"')) - elif config is None: + elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' @@ -103,7 +105,7 @@ class HOCONConverter(object): lines = '"""{value}"""'.format(value=config) # multilines else: lines = '"{value}"'.format(value=config.replace('\n', '\\n').replace('"', '\\"')) - elif config is None: + elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' @@ -150,6 +152,8 @@ class HOCONConverter(object): lines = config else: lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines]) + elif config is None or isinstance(config, NoneValue): + lines = 'null' elif config is True: lines = 'true' elif config is False: @@ -185,6 +189,8 @@ class HOCONConverter(object): lines.append('.'.join(stripped_key_stack) + ' = true') elif config is False: lines.append('.'.join(stripped_key_stack) + ' = false') + elif config is None or isinstance(config, NoneValue): + pass else: lines.append('.'.join(stripped_key_stack) + ' = ' + str(config)) return '\n'.join([line for line in lines if len(line) > 0]) diff --git a/tox.ini b/tox.ini index f9a71ce..5a4f7da 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = flake8, py26, py27, py33, py34 +envlist = flake8, py26, py27, py33, py34, py36 [testenv] passenv = TRAVIS TRAVIS_JOB_ID TRAVIS_BRANCH
chimpler/pyhocon
4dfa3b8b3c2e254964f28127f2d12ce526217869
diff --git a/tests/test_config_tree.py b/tests/test_config_tree.py index f9016d1..97a8e17 100644 --- a/tests/test_config_tree.py +++ b/tests/test_config_tree.py @@ -237,6 +237,11 @@ class TestConfigParser(object): assert config_tree.pop("config-new", {'b': 1}) == {'b': 1} assert config_tree == ConfigTree() + config_tree = ConfigTree() + config_tree.put('key', 'value') + assert config_tree.pop('key', 'value') == 'value' + assert 'key' not in config_tree + config_tree = ConfigTree() config_tree.put('a.b.c.one', 1) config_tree.put('a.b.c.two', 2) diff --git a/tests/test_tool.py b/tests/test_tool.py index 937f9e7..9610d77 100644 --- a/tests/test_tool.py +++ b/tests/test_tool.py @@ -81,7 +81,7 @@ class TestHOCONConverter(object): f1: true f2: false g: [] - h: None + h: null i: a.b: 2 """
HOCONConverter.to_json can't convert `null` value After convert into JSON with `HOCONConverter.to_json`, the value should be kept `null`, but it is converted to `NonValue`. ```py In [19]: hocon = "{foo = null}" In [20]: conf = ConfigFactory.parse_string(hocon) In [21]: conf Out[21]: ConfigTree([('foo', <pyhocon.config_tree.NoneValue at 0x1a1074e4fd0>)]) In [22]: HOCONConverter.to_json(conf) Out[22]: '{\n "foo": <pyhocon.config_tree.NoneValue object at 0x000001A1074E4FD0>\n}' ```
0.0
4dfa3b8b3c2e254964f28127f2d12ce526217869
[ "tests/test_config_tree.py::TestConfigParser::test_configtree_pop", "tests/test_tool.py::TestHOCONConverter::test_to_json", "tests/test_tool.py::TestHOCONConverter::test_to_yaml", "tests/test_tool.py::TestHOCONConverter::test_to_properties", "tests/test_tool.py::TestHOCONConverter::test_to_hocon", "tests/test_tool.py::TestHOCONConverter::test_convert_from_file" ]
[ "tests/test_config_tree.py::TestConfigParser::test_config_tree_quoted_string", "tests/test_config_tree.py::TestConfigParser::test_config_list", "tests/test_config_tree.py::TestConfigParser::test_config_tree_number", "tests/test_config_tree.py::TestConfigParser::test_config_tree_iterator", "tests/test_config_tree.py::TestConfigParser::test_config_logging", "tests/test_config_tree.py::TestConfigParser::test_config_tree_null", "tests/test_config_tree.py::TestConfigParser::test_getters", "tests/test_config_tree.py::TestConfigParser::test_getters_with_default", "tests/test_config_tree.py::TestConfigParser::test_getter_type_conversion_string_to_bool", "tests/test_config_tree.py::TestConfigParser::test_getter_type_conversion_bool_to_string", "tests/test_config_tree.py::TestConfigParser::test_getter_type_conversion_number_to_string", "tests/test_config_tree.py::TestConfigParser::test_overrides_int_with_config_no_append", "tests/test_config_tree.py::TestConfigParser::test_overrides_int_with_config_append", "tests/test_config_tree.py::TestConfigParser::test_plain_ordered_dict", "tests/test_config_tree.py::TestConfigParser::test_contains", "tests/test_config_tree.py::TestConfigParser::test_contains_with_quoted_keys", "tests/test_config_tree.py::TestConfigParser::test_keyerror_raised", "tests/test_tool.py::TestHOCONConverter::test_invalid_format" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-08-24 00:24:49+00:00
apache-2.0
1,570
chimpler__pyhocon-133
diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index 075bae1..354bfb6 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -93,7 +93,7 @@ class ConfigTree(OrderedDict): self._push_history(key_elt, value) self[key_elt] = value elif isinstance(l, list): - l += value + self[key_elt] = l + value self._push_history(key_elt, l) elif l is None: self._push_history(key_elt, value) @@ -144,6 +144,8 @@ class ConfigTree(OrderedDict): if key_index == len(key_path) - 1: if isinstance(elt, NoneValue): return None + elif isinstance(elt, list): + return [None if isinstance(x, NoneValue) else x for x in elt] else: return elt elif isinstance(elt, ConfigTree):
chimpler/pyhocon
8609e4f810ca47a3b573d8b79fa39760e97714b5
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index ca08db6..8d9dffd 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -212,9 +212,11 @@ class TestConfigParser(object): config = ConfigFactory.parse_string( """ a = null + b = [null] """ ) assert config.get('a') is None + assert config.get('b')[0] is None def test_parse_override(self): config = ConfigFactory.parse_string( diff --git a/tests/test_config_tree.py b/tests/test_config_tree.py index 97a8e17..3d194de 100644 --- a/tests/test_config_tree.py +++ b/tests/test_config_tree.py @@ -9,7 +9,7 @@ except ImportError: # pragma: no cover from ordereddict import OrderedDict -class TestConfigParser(object): +class TestConfigTree(object): def test_config_tree_quoted_string(self): config_tree = ConfigTree()
get_list() returns NoneValue's, not None's Given the following pyhocon file: ``` single_value = null list_value = [null] ``` And the following code: ```python from pyhocon import ConfigFactory config = ConfigFactory.parse_file("test.conf") single_value = config.get("single_value") print single_value, single_value is None list_value = config.get_list("list_value")[0] print list_value, list_value is None print single_value == list_value ``` You get as output: ``` None True <pyhocon.config_tree.NoneValue object at 0xe20ad0> False False ``` I expected both values to be Python's `None`.
0.0
8609e4f810ca47a3b573d8b79fa39760e97714b5
[ "tests/test_config_parser.py::TestConfigParser::test_parse_null" ]
[ "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_number_to_string", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_string_to_bool", "tests/test_config_tree.py::TestConfigTree::test_config_logging", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_append", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_no_append", "tests/test_config_tree.py::TestConfigTree::test_getters", "tests/test_config_tree.py::TestConfigTree::test_contains", "tests/test_config_tree.py::TestConfigTree::test_getters_with_default", "tests/test_config_tree.py::TestConfigTree::test_config_tree_iterator", "tests/test_config_tree.py::TestConfigTree::test_config_list", "tests/test_config_tree.py::TestConfigTree::test_contains_with_quoted_keys", "tests/test_config_tree.py::TestConfigTree::test_configtree_pop", "tests/test_config_tree.py::TestConfigTree::test_keyerror_raised", "tests/test_config_tree.py::TestConfigTree::test_config_tree_number", "tests/test_config_tree.py::TestConfigTree::test_plain_ordered_dict", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_bool_to_string", "tests/test_config_tree.py::TestConfigTree::test_config_tree_quoted_string", "tests/test_config_tree.py::TestConfigTree::test_config_tree_null", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_include_missing_file", "tests/test_config_parser.py::TestConfigParser::test_list_element_substitution", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_unquoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_multiple_substitutions", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution", "tests/test_config_parser.py::TestConfigParser::test_multiline_with_backslash", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield", "tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file", "tests/test_config_parser.py::TestConfigParser::test_invalid_assignment", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_append_array", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_self_append_object", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_object", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_include_required_file", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge", "tests/test_config_parser.py::TestConfigParser::test_with_comment_on_last_line", "tests/test_config_parser.py::TestConfigParser::test_triple_quotes_same_line", "tests/test_config_parser.py::TestConfigParser::test_bool_from_environment", "tests/test_config_parser.py::TestConfigParser::test_object_field_substitution", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_dotted_notation_merge", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse_part", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_string_opt_concat", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in_mutual", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_nested_dict", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_float_noeol", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts", "tests/test_config_parser.py::TestConfigParser::test_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_merge", "tests/test_config_parser.py::TestConfigParser::test_self_append_string", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_object_concat", "tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object2", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions_with_no_space", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path_hide", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array", "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_substitution_override", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array_to_dict", "tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_int_from_environment", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse2", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_object", "tests/test_config_parser.py::TestConfigParser::test_assign_next_line", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitiotion_dict_in_array", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_append_non_existent_string", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse", "tests/test_config_parser.py::TestConfigParser::test_multi_line_escape", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_var_with_include_keyword", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_include_substitution", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_concat_string", "tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_array", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object3", "tests/test_config_parser.py::TestConfigParser::test_cascade_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_pop", "tests/test_config_parser.py::TestConfigParser::test_unicode_dict_key", "tests/test_config_parser.py::TestConfigParser::test_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_substitution_cycle", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_triple_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_include_missing_required_file", "tests/test_config_parser.py::TestConfigParser::test_plain_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws_substitutions", "tests/test_config_parser.py::TestConfigParser::test_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_invalid", "tests/test_config_parser.py::TestConfigParser::test_quoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_include_file", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_invalid_dict", "tests/test_config_parser.py::TestConfigParser::test_issue_75", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append", "tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append_plus_equals", "tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_int_noeol", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_bad_concat", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_merge" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-10-12 18:45:20+00:00
apache-2.0
1,571
chimpler__pyhocon-173
diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py index 0257199..f68839b 100644 --- a/pyhocon/config_parser.py +++ b/pyhocon/config_parser.py @@ -3,6 +3,7 @@ import os import socket import contextlib import codecs + from pyparsing import Forward, Keyword, QuotedString, Word, Literal, Suppress, Regex, Optional, SkipTo, ZeroOrMore, \ Group, lineno, col, TokenConverter, replaceWith, alphanums, alphas8bit, ParseSyntaxException, StringEnd from pyparsing import ParserElement @@ -156,6 +157,7 @@ class ConfigParser(object): """ REPLACEMENTS = { + '\\\\': '\\', '\\\n': '\n', '\\n': '\n', '\\r': '\r', @@ -163,7 +165,7 @@ class ConfigParser(object): '\\=': '=', '\\#': '#', '\\!': '!', - '\\"': '"' + '\\"': '"', } @classmethod @@ -181,10 +183,14 @@ class ConfigParser(object): :return: a ConfigTree or a list """ + unescape_pattern = re.compile(r'\\.') + + def replace_escape_sequence(match): + value = match.group(0) + return cls.REPLACEMENTS.get(value, value) + def norm_string(value): - for k, v in cls.REPLACEMENTS.items(): - value = value.replace(k, v) - return value + return unescape_pattern.sub(replace_escape_sequence, value) def unescape_string(tokens): return ConfigUnquotedString(norm_string(tokens[0]))
chimpler/pyhocon
9b8830e409e000927f8029bf6a5c4337720120ba
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index b7ace1b..c580e23 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -1,5 +1,6 @@ # -*- encoding: utf-8 -*- +import json import os import mock import tempfile @@ -2104,3 +2105,34 @@ www.example-ö.com { assert 'abc' == config['/abc/cde1'] assert 'cde' == config['/abc/cde2'] assert 'fgh' == config['/abc/cde3'] + + def test_escape_sequences_json_equivalence(self): + """ + Quoted strings are in the same format as JSON strings, + See: https://github.com/lightbend/config/blob/master/HOCON.md#unchanged-from-json + """ + source = r""" + { + "plain-backslash": "\\", + "tab": "\t", + "no-tab": "\\t", + "newline": "\n", + "no-newline": "\\n", + "cr": "\r", + "no-cr": "\\r", + "windows": "c:\\temp" + } + """ + expected = { + 'plain-backslash': '\\', + 'tab': '\t', + 'no-tab': '\\t', + 'newline': '\n', + 'no-newline': '\\n', + 'cr': '\r', + 'no-cr': '\\r', + 'windows': 'c:\\temp', + } + config = ConfigFactory.parse_string(source) + assert config == expected + assert config == json.loads(source)
pyhocon does not handle backslashes the same way json does ``` In [1]: import json, pyhocon In [2]: single = r'{"a": "b\.c"}' In [3]: double = r'{"a": "b\\.c"}' In [4]: json.loads(single) --------------------------------------------------------------------------- JSONDecodeError... In [5]: json.loads(double) Out[5]: {'a': 'b\\.c'} In [6]: pyhocon.ConfigFactory.parse_string(single) Out[6]: ConfigTree([('a', 'b\\.c')]) In [7]: pyhocon.ConfigFactory.parse_string(double) Out[7]: ConfigTree([('a', 'b\\\\.c')]) In [8]: json.dumps(json.loads(double)) Out[8]: '{"a": "b\\\\.c"}' In [9]: json.dumps(json.loads(double)) == double Out[9]: True In [10]: json.dumps(pyhocon.ConfigFactory.parse_string(double)) Out[10]: '{"a": "b\\\\\\\\.c"}' In [11]: json.dumps(pyhocon.ConfigFactory.parse_string(double)) == double Out[11]: False ``` I looked at the HOCON documentation and I couldn't find explicit guidance, but I'd expect that my `single` example would be invalid HOCON (it's invalid JSON?) and that my `double` example would get parsed the same way that `json.loads` does it?
0.0
9b8830e409e000927f8029bf6a5c4337720120ba
[ "tests/test_config_parser.py::TestConfigParser::test_escape_sequences_json_equivalence" ]
[ "tests/test_config_parser.py::TestConfigParser::test_complex_substitutions", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array", "tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in", "tests/test_config_parser.py::TestConfigParser::test_cascade_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object", "tests/test_config_parser.py::TestConfigParser::test_include_substitution", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_object", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object3", "tests/test_config_parser.py::TestConfigParser::test_parse_null", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_list_element_substitution", "tests/test_config_parser.py::TestConfigParser::test_dotted_notation_merge", "tests/test_config_parser.py::TestConfigParser::test_escape_quote_complex", "tests/test_config_parser.py::TestConfigParser::test_assign_next_line", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_float_noeol", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_string_opt_concat", "tests/test_config_parser.py::TestConfigParser::test_fallback_non_root", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_int_from_environment", "tests/test_config_parser.py::TestConfigParser::test_attr_syntax", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples", "tests/test_config_parser.py::TestConfigParser::test_include_missing_required_file", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_with_comment_on_last_line", "tests/test_config_parser.py::TestConfigParser::test_bool_from_environment", "tests/test_config_parser.py::TestConfigParser::test_self_append_string", "tests/test_config_parser.py::TestConfigParser::test_self_append_object", "tests/test_config_parser.py::TestConfigParser::test_include_missing_file", "tests/test_config_parser.py::TestConfigParser::test_bad_concat", "tests/test_config_parser.py::TestConfigParser::test_fallback_with_resolve", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_array", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override", "tests/test_config_parser.py::TestConfigParser::test_plain_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_triple_quotes_same_line", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_object", "tests/test_config_parser.py::TestConfigParser::test_self_append_non_existent_string", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in_mutual", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge", "tests/test_config_parser.py::TestConfigParser::test_var_with_include_keyword", "tests/test_config_parser.py::TestConfigParser::test_issue_75", "tests/test_config_parser.py::TestConfigParser::test_self_append_array", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_unquoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_invalid", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array_to_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse_part", "tests/test_config_parser.py::TestConfigParser::test_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_quoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_merge", "tests/test_config_parser.py::TestConfigParser::test_self_ref_child", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_object_field_substitution", "tests/test_config_parser.py::TestConfigParser::test_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_multiline_with_backslash", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_nested_dict", "tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override", "tests/test_config_parser.py::TestConfigParser::test_include_required_file", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws_substitutions", "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_concat_string", "tests/test_config_parser.py::TestConfigParser::test_pop", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path_hide", "tests/test_config_parser.py::TestConfigParser::test_optional_with_merge", "tests/test_config_parser.py::TestConfigParser::test_include_file", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse2", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_keys_with_slash", "tests/test_config_parser.py::TestConfigParser::test_merge_overriden", "tests/test_config_parser.py::TestConfigParser::test_invalid_assignment", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_unicode_dict_key", "tests/test_config_parser.py::TestConfigParser::test_object_concat", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append_substitution", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions_with_no_space", "tests/test_config_parser.py::TestConfigParser::test_escape_quote", "tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol", "tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape", "tests/test_config_parser.py::TestConfigParser::test_substitution_override", "tests/test_config_parser.py::TestConfigParser::test_invalid_dict", "tests/test_config_parser.py::TestConfigParser::test_substitution_cycle", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append_plus_equals", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object2", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_triple_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitiotion_dict_in_array", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge", "tests/test_config_parser.py::TestConfigParser::test_multiple_substitutions", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_int_noeol", "tests/test_config_parser.py::TestConfigParser::test_multi_line_escape" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-07-09 08:28:24+00:00
apache-2.0
1,572
chimpler__pyhocon-195
diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py index 4326980..cc18eef 100644 --- a/pyhocon/config_parser.py +++ b/pyhocon/config_parser.py @@ -275,80 +275,86 @@ class ConfigParser(object): return ConfigInclude(obj if isinstance(obj, list) else obj.items()) - ParserElement.setDefaultWhitespaceChars(' \t') - - assign_expr = Forward() - true_expr = Keyword("true", caseless=True).setParseAction(replaceWith(True)) - false_expr = Keyword("false", caseless=True).setParseAction(replaceWith(False)) - null_expr = Keyword("null", caseless=True).setParseAction(replaceWith(NoneValue())) - key = QuotedString('"', escChar='\\', unquoteResults=False) | Word(alphanums + alphas8bit + '._- /') - - eol = Word('\n\r').suppress() - eol_comma = Word('\n\r,').suppress() - comment = (Literal('#') | Literal('//')) - SkipTo(eol | StringEnd()) - comment_eol = Suppress(Optional(eol_comma) + comment) - comment_no_comma_eol = (comment | eol).suppress() - number_expr = Regex(r'[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE][+\-]?\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))', - re.DOTALL).setParseAction(convert_number) - - # multi line string using """ - # Using fix described in http://pyparsing.wikispaces.com/share/view/3778969 - multiline_string = Regex('""".*?"*"""', re.DOTALL | re.UNICODE).setParseAction(parse_multi_string) - # single quoted line string - quoted_string = Regex(r'"(?:[^"\\\n]|\\.)*"[ \t]*', re.UNICODE).setParseAction(create_quoted_string) - # unquoted string that takes the rest of the line until an optional comment - # we support .properties multiline support which is like this: - # line1 \ - # line2 \ - # so a backslash precedes the \n - unquoted_string = Regex(r'(?:[^^`+?!@*&"\[\{\s\]\}#,=\$\\]|\\.)+[ \t]*', re.UNICODE).setParseAction(unescape_string) - substitution_expr = Regex(r'[ \t]*\$\{[^\}]+\}[ \t]*').setParseAction(create_substitution) - string_expr = multiline_string | quoted_string | unquoted_string - - value_expr = number_expr | true_expr | false_expr | null_expr | string_expr - - include_content = (quoted_string | ((Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress())) - include_expr = ( - Keyword("include", caseless=True).suppress() + ( - include_content | ( - Keyword("required") - Literal('(').suppress() - include_content - Literal(')').suppress() + @contextlib.contextmanager + def set_default_white_spaces(): + default = ParserElement.DEFAULT_WHITE_CHARS + ParserElement.setDefaultWhitespaceChars(' \t') + yield + ParserElement.setDefaultWhitespaceChars(default) + + with set_default_white_spaces(): + assign_expr = Forward() + true_expr = Keyword("true", caseless=True).setParseAction(replaceWith(True)) + false_expr = Keyword("false", caseless=True).setParseAction(replaceWith(False)) + null_expr = Keyword("null", caseless=True).setParseAction(replaceWith(NoneValue())) + key = QuotedString('"', escChar='\\', unquoteResults=False) | Word(alphanums + alphas8bit + '._- /') + + eol = Word('\n\r').suppress() + eol_comma = Word('\n\r,').suppress() + comment = (Literal('#') | Literal('//')) - SkipTo(eol | StringEnd()) + comment_eol = Suppress(Optional(eol_comma) + comment) + comment_no_comma_eol = (comment | eol).suppress() + number_expr = Regex(r'[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE][+\-]?\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))', + re.DOTALL).setParseAction(convert_number) + + # multi line string using """ + # Using fix described in http://pyparsing.wikispaces.com/share/view/3778969 + multiline_string = Regex('""".*?"*"""', re.DOTALL | re.UNICODE).setParseAction(parse_multi_string) + # single quoted line string + quoted_string = Regex(r'"(?:[^"\\\n]|\\.)*"[ \t]*', re.UNICODE).setParseAction(create_quoted_string) + # unquoted string that takes the rest of the line until an optional comment + # we support .properties multiline support which is like this: + # line1 \ + # line2 \ + # so a backslash precedes the \n + unquoted_string = Regex(r'(?:[^^`+?!@*&"\[\{\s\]\}#,=\$\\]|\\.)+[ \t]*', re.UNICODE).setParseAction(unescape_string) + substitution_expr = Regex(r'[ \t]*\$\{[^\}]+\}[ \t]*').setParseAction(create_substitution) + string_expr = multiline_string | quoted_string | unquoted_string + + value_expr = number_expr | true_expr | false_expr | null_expr | string_expr + + include_content = (quoted_string | ((Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress())) + include_expr = ( + Keyword("include", caseless=True).suppress() + ( + include_content | ( + Keyword("required") - Literal('(').suppress() - include_content - Literal(')').suppress() + ) ) + ).setParseAction(include_config) + + root_dict_expr = Forward() + dict_expr = Forward() + list_expr = Forward() + multi_value_expr = ZeroOrMore(comment_eol | include_expr | substitution_expr | dict_expr | list_expr | value_expr | (Literal( + '\\') - eol).suppress()) + # for a dictionary : or = is optional + # last zeroOrMore is because we can have t = {a:4} {b: 6} {c: 7} which is dictionary concatenation + inside_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma)) + inside_root_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma), root=True) + dict_expr << Suppress('{') - inside_dict_expr - Suppress('}') + root_dict_expr << Suppress('{') - inside_root_dict_expr - Suppress('}') + list_entry = ConcatenatedValueParser(multi_value_expr) + list_expr << Suppress('[') - ListParser(list_entry - ZeroOrMore(eol_comma - list_entry)) - Suppress(']') + + # special case when we have a value assignment where the string can potentially be the remainder of the line + assign_expr << Group( + key - ZeroOrMore(comment_no_comma_eol) - (dict_expr | (Literal('=') | Literal(':') | Literal('+=')) - ZeroOrMore( + comment_no_comma_eol) - ConcatenatedValueParser(multi_value_expr)) ) - ).setParseAction(include_config) - - root_dict_expr = Forward() - dict_expr = Forward() - list_expr = Forward() - multi_value_expr = ZeroOrMore(comment_eol | include_expr | substitution_expr | dict_expr | list_expr | value_expr | (Literal( - '\\') - eol).suppress()) - # for a dictionary : or = is optional - # last zeroOrMore is because we can have t = {a:4} {b: 6} {c: 7} which is dictionary concatenation - inside_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma)) - inside_root_dict_expr = ConfigTreeParser(ZeroOrMore(comment_eol | include_expr | assign_expr | eol_comma), root=True) - dict_expr << Suppress('{') - inside_dict_expr - Suppress('}') - root_dict_expr << Suppress('{') - inside_root_dict_expr - Suppress('}') - list_entry = ConcatenatedValueParser(multi_value_expr) - list_expr << Suppress('[') - ListParser(list_entry - ZeroOrMore(eol_comma - list_entry)) - Suppress(']') - - # special case when we have a value assignment where the string can potentially be the remainder of the line - assign_expr << Group( - key - ZeroOrMore(comment_no_comma_eol) - (dict_expr | (Literal('=') | Literal(':') | Literal('+=')) - ZeroOrMore( - comment_no_comma_eol) - ConcatenatedValueParser(multi_value_expr)) - ) - - # the file can be { ... } where {} can be omitted or [] - config_expr = ZeroOrMore(comment_eol | eol) + (list_expr | root_dict_expr | inside_root_dict_expr) + ZeroOrMore( - comment_eol | eol_comma) - config = config_expr.parseString(content, parseAll=True)[0] - - if resolve: - allow_unresolved = resolve and unresolved_value is not DEFAULT_SUBSTITUTION and unresolved_value is not MANDATORY_SUBSTITUTION - has_unresolved = cls.resolve_substitutions(config, allow_unresolved) - if has_unresolved and unresolved_value is MANDATORY_SUBSTITUTION: - raise ConfigSubstitutionException('resolve cannot be set to True and unresolved_value to MANDATORY_SUBSTITUTION') - - if unresolved_value is not NO_SUBSTITUTION and unresolved_value is not DEFAULT_SUBSTITUTION: - cls.unresolve_substitutions_to_value(config, unresolved_value) + + # the file can be { ... } where {} can be omitted or [] + config_expr = ZeroOrMore(comment_eol | eol) + (list_expr | root_dict_expr | inside_root_dict_expr) + ZeroOrMore( + comment_eol | eol_comma) + config = config_expr.parseString(content, parseAll=True)[0] + + if resolve: + allow_unresolved = resolve and unresolved_value is not DEFAULT_SUBSTITUTION and unresolved_value is not MANDATORY_SUBSTITUTION + has_unresolved = cls.resolve_substitutions(config, allow_unresolved) + if has_unresolved and unresolved_value is MANDATORY_SUBSTITUTION: + raise ConfigSubstitutionException('resolve cannot be set to True and unresolved_value to MANDATORY_SUBSTITUTION') + + if unresolved_value is not NO_SUBSTITUTION and unresolved_value is not DEFAULT_SUBSTITUTION: + cls.unresolve_substitutions_to_value(config, unresolved_value) return config @classmethod diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index 1492793..c39a977 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -1,7 +1,6 @@ from collections import OrderedDict from pyparsing import lineno from pyparsing import col - try: basestring except NameError: # pragma: no cover @@ -364,6 +363,14 @@ class ConfigTree(OrderedDict): raise KeyError(item) return val + try: + from collections import _OrderedDictItemsView + except ImportError: # pragma: nocover + pass + else: + def items(self): # pragma: nocover + return self._OrderedDictItemsView(self) + def __getattr__(self, item): val = self.get(item, NonExistentKey) if val is NonExistentKey:
chimpler/pyhocon
9ccb7cac7db3ac3d20c5d7f031f802281a87242d
diff --git a/tests/test_config_tree.py b/tests/test_config_tree.py index fbdee7b..1435cff 100644 --- a/tests/test_config_tree.py +++ b/tests/test_config_tree.py @@ -1,6 +1,6 @@ import pytest from collections import OrderedDict -from pyhocon.config_tree import ConfigTree +from pyhocon.config_tree import ConfigTree, NoneValue from pyhocon.exceptions import ( ConfigMissingException, ConfigWrongTypeException, ConfigException) @@ -70,6 +70,11 @@ class TestConfigTree(object): config_tree.put("a.b.c", None) assert config_tree.get("a.b.c") is None + def test_config_tree_null_items(self): + config_tree = ConfigTree() + config_tree.put("a", NoneValue()) + assert list(config_tree.items()) == [("a", None)] + def test_getters(self): config_tree = ConfigTree() config_tree.put("int", 5)
[bug] pyhocon conflicts with others package that uses pyparsing in file config_parser.py line 278, there is a code: ParserElement.setDefaultWhitespaceChars(' \t') It probably causes other packages failed if it depends on pyparsing. for exampel: from pyhocon import ConfigFactory import pydot out = ConfigFactory.parse_file("my.conf") digraph = pydot.graph_from_dot_file(dot_file)[0] # failed
0.0
9ccb7cac7db3ac3d20c5d7f031f802281a87242d
[ "tests/test_config_tree.py::TestConfigTree::test_config_tree_null_items" ]
[ "tests/test_config_tree.py::TestConfigTree::test_config_tree_quoted_string", "tests/test_config_tree.py::TestConfigTree::test_config_list", "tests/test_config_tree.py::TestConfigTree::test_numerically_index_objects_to_arrays", "tests/test_config_tree.py::TestConfigTree::test_config_tree_number", "tests/test_config_tree.py::TestConfigTree::test_config_tree_iterator", "tests/test_config_tree.py::TestConfigTree::test_config_logging", "tests/test_config_tree.py::TestConfigTree::test_config_tree_null", "tests/test_config_tree.py::TestConfigTree::test_getters", "tests/test_config_tree.py::TestConfigTree::test_getters_with_default", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_string_to_bool", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_bool_to_string", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_number_to_string", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_no_append", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_append", "tests/test_config_tree.py::TestConfigTree::test_plain_ordered_dict", "tests/test_config_tree.py::TestConfigTree::test_contains", "tests/test_config_tree.py::TestConfigTree::test_contains_with_quoted_keys", "tests/test_config_tree.py::TestConfigTree::test_configtree_pop", "tests/test_config_tree.py::TestConfigTree::test_keyerror_raised", "tests/test_config_tree.py::TestConfigTree::test_configmissing_raised" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-12-28 06:23:59+00:00
apache-2.0
1,573
chimpler__pyhocon-196
diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index 1492793..c39a977 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -1,7 +1,6 @@ from collections import OrderedDict from pyparsing import lineno from pyparsing import col - try: basestring except NameError: # pragma: no cover @@ -364,6 +363,14 @@ class ConfigTree(OrderedDict): raise KeyError(item) return val + try: + from collections import _OrderedDictItemsView + except ImportError: # pragma: nocover + pass + else: + def items(self): # pragma: nocover + return self._OrderedDictItemsView(self) + def __getattr__(self, item): val = self.get(item, NonExistentKey) if val is NonExistentKey:
chimpler/pyhocon
9ccb7cac7db3ac3d20c5d7f031f802281a87242d
diff --git a/tests/test_config_tree.py b/tests/test_config_tree.py index fbdee7b..1435cff 100644 --- a/tests/test_config_tree.py +++ b/tests/test_config_tree.py @@ -1,6 +1,6 @@ import pytest from collections import OrderedDict -from pyhocon.config_tree import ConfigTree +from pyhocon.config_tree import ConfigTree, NoneValue from pyhocon.exceptions import ( ConfigMissingException, ConfigWrongTypeException, ConfigException) @@ -70,6 +70,11 @@ class TestConfigTree(object): config_tree.put("a.b.c", None) assert config_tree.get("a.b.c") is None + def test_config_tree_null_items(self): + config_tree = ConfigTree() + config_tree.put("a", NoneValue()) + assert list(config_tree.items()) == [("a", None)] + def test_getters(self): config_tree = ConfigTree() config_tree.put("int", 5)
NoneValue object in parse result of "a=null" in PyPy In PyPy, parse result of "a=null" has a NoneValue object which is wrong: ``` Python 2.7.12 (aff251e543859ce4508159dd9f1a82a2f553de00, Nov 25 2016, 00:02:08) [PyPy 5.6.0 with GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>> from pyhocon import ConfigFactory >>>> ConfigFactory.parse_string('a=null') ConfigTree([('a', <pyhocon.config_tree.NoneValue object at 0x00000001116cbe18>)]) ``` In CPython, it's ok: ``` Python 2.7.13 (default, Dec 18 2016, 07:03:39) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from pyhocon import ConfigFactory >>> ConfigFactory.parse_string('a=null') ConfigTree([('a', None)]) ``` Versions: * pyhocon==0.3.35 * pyparsing==2.1.10 * PyPy and CPython versions are above.
0.0
9ccb7cac7db3ac3d20c5d7f031f802281a87242d
[ "tests/test_config_tree.py::TestConfigTree::test_config_tree_null_items" ]
[ "tests/test_config_tree.py::TestConfigTree::test_config_tree_quoted_string", "tests/test_config_tree.py::TestConfigTree::test_config_list", "tests/test_config_tree.py::TestConfigTree::test_numerically_index_objects_to_arrays", "tests/test_config_tree.py::TestConfigTree::test_config_tree_number", "tests/test_config_tree.py::TestConfigTree::test_config_tree_iterator", "tests/test_config_tree.py::TestConfigTree::test_config_logging", "tests/test_config_tree.py::TestConfigTree::test_config_tree_null", "tests/test_config_tree.py::TestConfigTree::test_getters", "tests/test_config_tree.py::TestConfigTree::test_getters_with_default", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_string_to_bool", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_bool_to_string", "tests/test_config_tree.py::TestConfigTree::test_getter_type_conversion_number_to_string", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_no_append", "tests/test_config_tree.py::TestConfigTree::test_overrides_int_with_config_append", "tests/test_config_tree.py::TestConfigTree::test_plain_ordered_dict", "tests/test_config_tree.py::TestConfigTree::test_contains", "tests/test_config_tree.py::TestConfigTree::test_contains_with_quoted_keys", "tests/test_config_tree.py::TestConfigTree::test_configtree_pop", "tests/test_config_tree.py::TestConfigTree::test_keyerror_raised", "tests/test_config_tree.py::TestConfigTree::test_configmissing_raised" ]
{ "failed_lite_validators": [ "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2019-01-01 12:38:35+00:00
apache-2.0
1,574
chimpler__pyhocon-292
diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py index 6846589..52a06cb 100644 --- a/pyhocon/config_parser.py +++ b/pyhocon/config_parser.py @@ -125,6 +125,10 @@ def period(period_value, period_unit): return period_impl(**arguments) +U_KEY_SEP = unicode('.') +U_KEY_FMT = unicode('"{0}"') + + class ConfigFactory(object): @classmethod @@ -868,6 +872,14 @@ class ConfigTreeParser(TokenConverter): config_tree.put(key, value, False) else: existing_value = config_tree.get(key, None) + parsed_key = ConfigTree.parse_key(key) + key = parsed_key[0] + if len(parsed_key) > 1: + # Special case when the key contains path (i.e., `x.y = v`) + new_value = ConfigTree() + new_value.put(U_KEY_SEP.join(U_KEY_FMT.format(k) for k in parsed_key[1:]), value) + value = new_value + if isinstance(value, ConfigTree) and not isinstance(existing_value, list): # Only Tree has to be merged with tree config_tree.put(key, value, True) diff --git a/setup.py b/setup.py index dad12e4..2d6b631 100755 --- a/setup.py +++ b/setup.py @@ -52,7 +52,10 @@ setup( packages=[ 'pyhocon', ], - install_requires=['pyparsing~=2.0'], + install_requires=[ + 'pyparsing~=2.0;python_version<"3.0"', + 'pyparsing>=2,<4;python_version>="3.0"', + ], extras_require={ 'Duration': ['python-dateutil>=2.8.0'] },
chimpler/pyhocon
be660deb6d6a5a175d384792e208fd39986758ea
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index 13a130f..c4ce46a 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -19,7 +19,6 @@ try: except Exception: from datetime import timedelta as period - class TestConfigParser(object): def test_parse_simple_value(self): config = ConfigFactory.parse_string( @@ -606,6 +605,58 @@ class TestConfigParser(object): 'cluster-size': 6 } + def test_dict_substitutions2(self): + config = ConfigFactory.parse_string( + """ + data-center-generic = { cluster-size = 6 } + data-center-east = ${data-center-generic} + data-center-east.name = "east" + """ + ) + + assert config.get('data-center-east.cluster-size') == 6 + assert config.get('data-center-east.name') == 'east' + + config2 = ConfigFactory.parse_string( + """ + data-center-generic = { cluster-size = 6 } + data-center-east.name = "east" + data-center-east = ${data-center-generic} + """ + ) + + assert config2.get('data-center-east.cluster-size') == 6 + assert config2.get('data-center-east.name') == 'east' + + config3 = ConfigFactory.parse_string( + """ + data-center-generic = { cluster-size = 6 } + data-center-east.name = "east" + data-center-east = ${data-center-generic} + data-center-east.cluster-size = 9 + data-center-east.opts = "-Xmx4g" + """ + ) + + assert config3.get('data-center-east.cluster-size') == 9 + assert config3.get('data-center-east.name') == 'east' + assert config3.get('data-center-east.opts') == '-Xmx4g' + + config4 = ConfigFactory.parse_string( + """ + data-center-generic = { cluster-size = 6 } + data-center-east.name = "east" + data-center-east = ${data-center-generic} + data-center-east-prod = ${data-center-east} + data-center-east-prod.tmpDir=/tmp + """ + ) + + assert config4.get('data-center-east.cluster-size') == 6 + assert config4.get('data-center-east.name') == 'east' + assert config4.get('data-center-east-prod.cluster-size') == 6 + assert config4.get('data-center-east-prod.tmpDir') == '/tmp' + def test_dos_chars_with_unquoted_string_noeol(self): config = ConfigFactory.parse_string("foo = bar") assert config['foo'] == 'bar'
ConfigFactory Parse File update after substitution incorrect If I have a config called `test.conf` ``` test: { a: 1 b: 2 } test2: ${test} test2.c: 3 ``` I would expect ``` conf = ConfigFactory.parse_file("test.conf") print(conf.get("test2")) ``` to print `{a:1, b:2, c:3}` but it just prints `{c:3}`.
0.0
be660deb6d6a5a175d384792e208fd39986758ea
[ "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions2" ]
[ "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[`]", "tests/test_config_parser.py::TestConfigParser::test_multiple_substitutions", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object", "tests/test_config_parser.py::TestConfigParser::test_fallback_with_resolve", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment", "tests/test_config_parser.py::TestConfigParser::test_quoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_resolve_package_path_format", "tests/test_config_parser.py::TestConfigParser::test_self_ref_child", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set6]", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[?]", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string", "tests/test_config_parser.py::TestConfigParser::test_plain_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_string_opt_concat", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_complex_substitutions", "tests/test_config_parser.py::TestConfigParser::test_multiline_with_backslash", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set8]", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set0]", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_bool_from_environment", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws_substitutions", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set12]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set3]", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[?]", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_triple_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set30]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set17]", "tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict", "tests/test_config_parser.py::TestConfigParser::test_cascade_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters_in_context[$]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set18]", "tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set10]", "tests/test_config_parser.py::TestConfigParser::test_dotted_notation_merge", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set7]", "tests/test_config_parser.py::TestConfigParser::test_multi_line_escape", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration_with_long_unit_name", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[^]", "tests/test_config_parser.py::TestConfigParser::test_bad_concat", "tests/test_config_parser.py::TestConfigParser::test_merge_overriden", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set33]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set9]", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append", "tests/test_config_parser.py::TestConfigParser::test_parse_with_list_mixed_types_with_durations_and_trailing_comma", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_array", "tests/test_config_parser.py::TestConfigParser::test_assign_next_line", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set15]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set1]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set25]", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path_hide", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set19]", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters_in_context[\"]", "tests/test_config_parser.py::TestConfigParser::test_escape_quote_complex", "tests/test_config_parser.py::TestConfigParser::test_self_append_object", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set27]", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts", "tests/test_config_parser.py::TestConfigParser::test_assign_int", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set2]", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set24]", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[*]", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_issue_75", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set14]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set26]", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_int_noeol", "tests/test_config_parser.py::TestConfigParser::test_mutation_values", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[@]", "tests/test_config_parser.py::TestConfigParser::test_resolve_package_path_missing", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set4]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set21]", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_nested_dict", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set23]", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[!]", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[!]", "tests/test_config_parser.py::TestConfigParser::test_include_missing_required_file", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment_self_ref_optional", "tests/test_config_parser.py::TestConfigParser::test_triple_quotes_same_line", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[`]", "tests/test_config_parser.py::TestConfigParser::test_object_concat", "tests/test_config_parser.py::TestConfigParser::test_self_append_string", "tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol", "tests/test_config_parser.py::TestConfigParser::test_escape_quote", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set31]", "tests/test_config_parser.py::TestConfigParser::test_escape_sequences_json_equivalence", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitiotion_dict_in_array", "tests/test_config_parser.py::TestConfigParser::test_attr_syntax", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse_part", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_merge", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[@]", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array_to_dict", "tests/test_config_parser.py::TestConfigParser::test_assign_float", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[*]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set32]", "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_substitution_cycle", "tests/test_config_parser.py::TestConfigParser::test_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse2", "tests/test_config_parser.py::TestConfigParser::test_pop", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_object", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[&]", "tests/test_config_parser.py::TestConfigParser::test_substitution_override", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions_with_no_space", "tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object2", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge", "tests/test_config_parser.py::TestConfigParser::test_sci_real", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield", "tests/test_config_parser.py::TestConfigParser::test_self_append_array", "tests/test_config_parser.py::TestConfigParser::test_parse_null", "tests/test_config_parser.py::TestConfigParser::test_include_glob_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_substitution_multiple_override", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment_self_ref", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set20]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set11]", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_invalid", "tests/test_config_parser.py::TestConfigParser::test_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_concat_string", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_object_field_substitution", "tests/test_config_parser.py::TestConfigParser::test_with_comment_on_last_line", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object3", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[&]", "tests/test_config_parser.py::TestConfigParser::test_unicode_dict_key", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path", "tests/test_config_parser.py::TestConfigParser::test_fallback_non_root", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_object", "tests/test_config_parser.py::TestConfigParser::test_int_from_environment", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set5]", "tests/test_config_parser.py::TestConfigParser::test_fail_parse_forbidden_characters[+]", "tests/test_config_parser.py::TestConfigParser::test_keys_with_slash", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set16]", "tests/test_config_parser.py::TestConfigParser::test_var_with_include_keyword", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_float_noeol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array", "tests/test_config_parser.py::TestConfigParser::test_invalid_dict", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in_mutual", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append_plus_equals", "tests/test_config_parser.py::TestConfigParser::test_include_package_file", "tests/test_config_parser.py::TestConfigParser::test_self_append_non_existent_string", "tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol", "tests/test_config_parser.py::TestConfigParser::test_include_glob_list_from_samples", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[+]", "tests/test_config_parser.py::TestConfigParser::test_optional_with_merge", "tests/test_config_parser.py::TestConfigParser::test_include_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set34]", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set22]", "tests/test_config_parser.py::TestConfigParser::test_parse_forbidden_characters_quoted[^]", "tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set28]", "tests/test_config_parser.py::TestConfigParser::test_list_element_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set29]", "tests/test_config_parser.py::TestConfigParser::test_include_missing_file", "tests/test_config_parser.py::TestConfigParser::test_include_file", "tests/test_config_parser.py::TestConfigParser::test_resolve_package_path", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_include_required_file", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_string_with_duration[data_set13]", "tests/test_config_parser.py::TestConfigParser::test_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_unquoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_invalid_assignment", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set4]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set9]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set2]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set10]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set0]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set1]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set6]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set3]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set7]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set8]", "tests/test_config_parser.py::test_parse_string_with_duration_optional_units[data_set5]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-26 14:25:03+00:00
apache-2.0
1,575
chimpler__pyhocon-92
diff --git a/pyhocon/config_parser.py b/pyhocon/config_parser.py index 9e20236..27366a5 100644 --- a/pyhocon/config_parser.py +++ b/pyhocon/config_parser.py @@ -236,7 +236,7 @@ class ConfigParser(object): value_expr = number_expr | true_expr | false_expr | null_expr | string_expr - include_expr = (Keyword("include", caseless=True).suppress() - ( + include_expr = (Keyword("include", caseless=True).suppress() + ( quoted_string | ( (Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress()))) \ .setParseAction(include_config)
chimpler/pyhocon
abac1214ebcda0634960c29a16fba9a533266043
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index a0927f1..72d0114 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -1153,6 +1153,16 @@ class TestConfigParser(object): assert config['x'] == 42 assert config['y'] == 42 + def test_var_with_include_keyword(self): + config = ConfigFactory.parse_string( + """ + include-database=true + """) + + assert config == { + 'include-database': True + } + def test_substitution_override(self): config = ConfigFactory.parse_string( """
Syntax error while parsing variables of form include-blah-blah Trying to parse the following config: ``` { include-other-stuff = true } ``` with `conf = pyhocon.ConfigFactory.parse_file('/tmp/foo.conf')` results in the following stacktrace: ``` File "/home/blah/blahblah.py", line 53, in <module> conf = pyhocon.ConfigFactory.parse_file('/tmp/foo.conf') File "/opt/anaconda3/lib/python3.4/site-packages/pyhocon/config_parser.py", line 48, in parse_file return ConfigFactory.parse_string(content, os.path.dirname(filename), resolve) File "/opt/anaconda3/lib/python3.4/site-packages/pyhocon/config_parser.py", line 87, in parse_string return ConfigParser().parse(content, basedir, resolve) File "/opt/anaconda3/lib/python3.4/site-packages/pyhocon/config_parser.py", line 269, in parse config = config_expr.parseString(content, parseAll=True)[0] File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 1125, in parseString raise exc File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 1115, in parseString loc, tokens = self._parse( instring, 0 ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2378, in parseImpl loc, exprtokens = e._parse( instring, loc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2483, in parseImpl ret = e._parse( instring, loc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2624, in parseImpl return self.expr._parse( instring, loc, doActions, callPreParse=False ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2361, in parseImpl loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2369, in parseImpl loc, exprtokens = e._parse( instring, loc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2624, in parseImpl return self.expr._parse( instring, loc, doActions, callPreParse=False ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2739, in parseImpl loc, tmptokens = self.expr._parse( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2483, in parseImpl ret = e._parse( instring, loc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 989, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/opt/anaconda3/lib/python3.4/site-packages/pyparsing.py", line 2374, in parseImpl raise ParseSyntaxException(pe) pyparsing.ParseSyntaxException: Expected Re:('".*?"[ \t]*') (at char 13), (line:2, col:12) ```
0.0
abac1214ebcda0634960c29a16fba9a533266043
[ "tests/test_config_parser.py::TestConfigParser::test_var_with_include_keyword" ]
[ "tests/test_config_parser.py::TestConfigParser::test_bool_from_environment", "tests/test_config_parser.py::TestConfigParser::test_assign_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts_with_merge", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_merge", "tests/test_config_parser.py::TestConfigParser::test_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_substitution_flat_override", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_float_noeol", "tests/test_config_parser.py::TestConfigParser::test_int_from_environment", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_triple_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_multiple_substitutions", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_concat_string", "tests/test_config_parser.py::TestConfigParser::test_include_dict_from_samples", "tests/test_config_parser.py::TestConfigParser::test_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_cascade_optional_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_assign_list_strings_with_eol", "tests/test_config_parser.py::TestConfigParser::test_parse_null", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_assign_next_line", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append_plus_equals", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_dict", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_samples", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitiotion_dict_in_array", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_int_noeol", "tests/test_config_parser.py::TestConfigParser::test_list_element_substitution", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_plain_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts", "tests/test_config_parser.py::TestConfigParser::test_issue_75", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_invalid_dict", "tests/test_config_parser.py::TestConfigParser::test_quoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_with_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_string_opt_concat", "tests/test_config_parser.py::TestConfigParser::test_multiline_with_backslash", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_object", "tests/test_config_parser.py::TestConfigParser::test_dotted_notation_merge", "tests/test_config_parser.py::TestConfigParser::test_include_substitution", "tests/test_config_parser.py::TestConfigParser::test_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws", "tests/test_config_parser.py::TestConfigParser::test_parse_URL_from_invalid", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_nested_dict", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_quoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_self_append_array", "tests/test_config_parser.py::TestConfigParser::test_substitutions_overwrite", "tests/test_config_parser.py::TestConfigParser::test_dos_chars_with_unquoted_string_noeol", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists_with_merge", "tests/test_config_parser.py::TestConfigParser::test_substitution_cycle", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_fallback_self_ref_substitutions_append", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse2", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_otherfield_merged_in_mutual", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object2", "tests/test_config_parser.py::TestConfigParser::test_self_append_object", "tests/test_config_parser.py::TestConfigParser::test_self_append_nonexistent_array", "tests/test_config_parser.py::TestConfigParser::test_assign_list_numbers_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_recurse_part", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_path_hide", "tests/test_config_parser.py::TestConfigParser::test_string_substitutions_with_no_space", "tests/test_config_parser.py::TestConfigParser::test_list_of_lists", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_object", "tests/test_config_parser.py::TestConfigParser::test_multi_line_escape", "tests/test_config_parser.py::TestConfigParser::test_assign_number_with_eol", "tests/test_config_parser.py::TestConfigParser::test_one_line_quote_escape", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_array_to_dict", "tests/test_config_parser.py::TestConfigParser::test_include_list", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_substitution_list_with_append_substitution", "tests/test_config_parser.py::TestConfigParser::test_quoted_unquoted_strings_with_ws_substitutions", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_self_append_string", "tests/test_config_parser.py::TestConfigParser::test_substitution_nested_override", "tests/test_config_parser.py::TestConfigParser::test_object_concat", "tests/test_config_parser.py::TestConfigParser::test_fallback_substitutions_overwrite_file", "tests/test_config_parser.py::TestConfigParser::test_assign_dict_strings_no_equal_sign_with_eol", "tests/test_config_parser.py::TestConfigParser::test_self_ref_substitution_dict_merge", "tests/test_config_parser.py::TestConfigParser::test_bad_concat", "tests/test_config_parser.py::TestConfigParser::test_string_from_environment", "tests/test_config_parser.py::TestConfigParser::test_object_field_substitution", "tests/test_config_parser.py::TestConfigParser::test_invalid_assignment", "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object", "tests/test_config_parser.py::TestConfigParser::test_self_append_non_existent_string", "tests/test_config_parser.py::TestConfigParser::test_self_merge_ref_substitutions_object3", "tests/test_config_parser.py::TestConfigParser::test_substitution_override", "tests/test_config_parser.py::TestConfigParser::test_from_dict_with_ordered_dict", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-08-07 19:29:40+00:00
apache-2.0
1,576
chrahunt__hlp-15
diff --git a/hlp/cli.py b/hlp/cli.py index c3d2476..33ff11c 100644 --- a/hlp/cli.py +++ b/hlp/cli.py @@ -6,7 +6,7 @@ import shlex import sys from textwrap import dedent -from .compat import iter_modules +from .compat import builtins, iter_modules from .typing import MYPY_RUNNING from .util import getattr_recursive, sequences @@ -23,7 +23,9 @@ class NamedObject(object): def get_attr(self, name): # type: (str) -> NamedObject obj = getattr(self.obj, name) - return NamedObject("{}.{}".format(self.name, name), obj) + if self.name: + name = "{}.{}".format(self.name, name) + return NamedObject(name, obj) def import_module(spec): @@ -167,7 +169,9 @@ def autocomplete(current): return [context.name] options = children_autocomplete_names(context) else: - options = package_autocomplete_names() + options = list(package_autocomplete_names()) + # Include builtins + options.extend(name for name in dir(builtins) if not name.startswith("__")) return sorted(m for m in options if m.startswith(current)) diff --git a/hlp/compat.py b/hlp/compat.py index 4d0e3b0..f8d0175 100644 --- a/hlp/compat.py +++ b/hlp/compat.py @@ -9,6 +9,11 @@ if MYPY_RUNNING: PY2 = sys.version_info < (3,) +if PY2: + import __builtin__ as builtins # type: ignore +else: + import builtins as builtins # type: ignore + if PY2:
chrahunt/hlp
b9d32dd1b2e80733582df93363ac5443837dd993
diff --git a/tests/test_autocomplete.py b/tests/test_autocomplete.py index 8cadcc3..7e53f9f 100644 --- a/tests/test_autocomplete.py +++ b/tests/test_autocomplete.py @@ -65,7 +65,15 @@ def test_autocomplete_bash_empty(fake_packages, monkeypatch): monkeypatch.setenv("COMP_WORDS", "hlp") monkeypatch.setenv("COMP_CWORD", "1") result = autocomplete_bash() + # Builtins + assert "open" in result + assert "ord" in result + # Standard library modules + assert "string" in result + assert "multiprocessing" in result + # Our packages assert "pkg_aaa" in result + # Only name, no trailing '.' assert "pkg_aaa." not in result
Autocomplete builtin names Currently if autocompleting a prompt like ``` hlp | ``` we only look at top-level packages and modules. We should also be including names of builtins.
0.0
b9d32dd1b2e80733582df93363ac5443837dd993
[ "tests/test_autocomplete.py::test_autocomplete_bash_empty" ]
[ "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aa-expected0]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa-expected1]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.-expected2]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.m-expected3]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.-expected4]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.Test-expected5]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.Test.-expected6]", "tests/test_autocomplete.py::test_autocomplete_bash[words0-1-expected0]", "tests/test_autocomplete.py::test_autocomplete_bash[words1-1-expected1]", "tests/test_autocomplete.py::test_autocomplete_bash[words2-2-expected2]", "tests/test_autocomplete.py::test_autocomplete_bash[words3-2-expected3]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-29 21:20:01+00:00
mit
1,577
chrahunt__hlp-16
diff --git a/hlp/cli.py b/hlp/cli.py index c3d2476..fd11823 100644 --- a/hlp/cli.py +++ b/hlp/cli.py @@ -6,7 +6,7 @@ import shlex import sys from textwrap import dedent -from .compat import iter_modules +from .compat import builtins, iter_modules from .typing import MYPY_RUNNING from .util import getattr_recursive, sequences @@ -23,7 +23,9 @@ class NamedObject(object): def get_attr(self, name): # type: (str) -> NamedObject obj = getattr(self.obj, name) - return NamedObject("{}.{}".format(self.name, name), obj) + if self.name: + name = "{}.{}".format(self.name, name) + return NamedObject(name, obj) def import_module(spec): @@ -167,7 +169,9 @@ def autocomplete(current): return [context.name] options = children_autocomplete_names(context) else: - options = package_autocomplete_names() + options = list(package_autocomplete_names()) + # Include builtins + options.extend(name for name in dir(builtins) if not name.startswith("__")) return sorted(m for m in options if m.startswith(current)) @@ -239,11 +243,8 @@ def main(input_args=None): parser.add_argument( "--autocomplete-init", choices=["bash"], help="Output autocomplete code." ) - parser.add_argument( - "--autocomplete", - action="store_true", - help="Internal. Output autocomplete choices.", - ) + # Output autocomplete choices. + parser.add_argument("--autocomplete", action="store_true", help=argparse.SUPPRESS) parser.add_argument("query", nargs="*") args = parser.parse_args(input_args) diff --git a/hlp/compat.py b/hlp/compat.py index 4d0e3b0..f8d0175 100644 --- a/hlp/compat.py +++ b/hlp/compat.py @@ -9,6 +9,11 @@ if MYPY_RUNNING: PY2 = sys.version_info < (3,) +if PY2: + import __builtin__ as builtins # type: ignore +else: + import builtins as builtins # type: ignore + if PY2:
chrahunt/hlp
b9d32dd1b2e80733582df93363ac5443837dd993
diff --git a/tests/test_autocomplete.py b/tests/test_autocomplete.py index 8cadcc3..7e53f9f 100644 --- a/tests/test_autocomplete.py +++ b/tests/test_autocomplete.py @@ -65,7 +65,15 @@ def test_autocomplete_bash_empty(fake_packages, monkeypatch): monkeypatch.setenv("COMP_WORDS", "hlp") monkeypatch.setenv("COMP_CWORD", "1") result = autocomplete_bash() + # Builtins + assert "open" in result + assert "ord" in result + # Standard library modules + assert "string" in result + assert "multiprocessing" in result + # Our packages assert "pkg_aaa" in result + # Only name, no trailing '.' assert "pkg_aaa." not in result
Hide --autocomplete option from help text It's not user-facing, so no reason to have it visible.
0.0
b9d32dd1b2e80733582df93363ac5443837dd993
[ "tests/test_autocomplete.py::test_autocomplete_bash_empty" ]
[ "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aa-expected0]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa-expected1]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.-expected2]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.m-expected3]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.-expected4]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.Test-expected5]", "tests/test_autocomplete.py::test_autocomplete_basics[pkg_aaa.mod_a.Test.-expected6]", "tests/test_autocomplete.py::test_autocomplete_bash[words0-1-expected0]", "tests/test_autocomplete.py::test_autocomplete_bash[words1-1-expected1]", "tests/test_autocomplete.py::test_autocomplete_bash[words2-2-expected2]", "tests/test_autocomplete.py::test_autocomplete_bash[words3-2-expected3]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-29 21:22:43+00:00
mit
1,578
chriskuehl__lazy-build-16
diff --git a/lazy_build/cache.py b/lazy_build/cache.py index 27124d9..f1ec74a 100644 --- a/lazy_build/cache.py +++ b/lazy_build/cache.py @@ -20,10 +20,15 @@ class S3Backend(collections.namedtuple('S3Backend', ( def key_for_ctx(self, ctx): return self.path.rstrip('/') + '/' + ctx.hash + def artifact_paths(self, ctx): + key = self.key_for_ctx(ctx) + return key + '.tar.gz', key + '.json' + def has_artifact(self, ctx): + tarball, json = self.artifact_paths(ctx) # what a ridiculous dance we have to do here... try: - self.s3.Object(self.bucket, self.key_for_ctx(ctx)).load() + self.s3.Object(self.bucket, tarball).load() except botocore.exceptions.ClientError as ex: if ex.response['Error']['Code'] == '404': return False @@ -33,18 +38,20 @@ class S3Backend(collections.namedtuple('S3Backend', ( return True def get_artifact(self, ctx): + tarball, json = self.artifact_paths(ctx) fd, path = tempfile.mkstemp() os.close(fd) self.s3.Bucket(self.bucket).download_file( - self.key_for_ctx(ctx), + tarball, path, ) return path def store_artifact(self, ctx, path): + tarball, json = self.artifact_paths(ctx) self.s3.Bucket(self.bucket).upload_file( path, - self.key_for_ctx(ctx), + tarball, ) def invalidate_artifact(self, ctx): diff --git a/lazy_build/context.py b/lazy_build/context.py index eadebb9..d7e0009 100644 --- a/lazy_build/context.py +++ b/lazy_build/context.py @@ -96,7 +96,7 @@ def build_context(conf, command): def package_artifact(conf): fd, tmp = tempfile.mkstemp() os.close(fd) - with tarfile.TarFile(tmp, mode='w') as tf: + with tarfile.open(tmp, mode='w:gz') as tf: for output_path in conf.output: if os.path.isdir(output_path): for path, _, filenames in os.walk(output_path): @@ -115,5 +115,5 @@ def extract_artifact(conf, artifact): else: os.remove(output_path) - with tarfile.TarFile(artifact) as tf: + with tarfile.open(artifact, 'r:gz') as tf: tf.extractall()
chriskuehl/lazy-build
c53270b41e1d3716c301e65a283d99f86aa55bb9
diff --git a/tests/context_test.py b/tests/context_test.py index 1e58218..b3271f5 100644 --- a/tests/context_test.py +++ b/tests/context_test.py @@ -77,7 +77,7 @@ def test_package_artifact(tmpdir): after_download=None, )) try: - with tarfile.TarFile(tmp) as tf: + with tarfile.open(tmp, 'r:gz') as tf: members = {member.name for member in tf.getmembers()} finally: os.remove(tmp) @@ -94,7 +94,7 @@ def test_extract_artifact(tmpdir): tmpdir.join('a/b/sup').ensure() tar = tmpdir.join('my.tar').strpath - with tarfile.TarFile(tar, 'w') as tf: + with tarfile.open(tar, 'w:gz') as tf: for path in ('my.txt', 'hello/there.txt', 'a/b/c/d.txt'): ti = tarfile.TarInfo(path) ti.size = 6
gzip before upload In some common cases (e.g. node_modules), this reduces ~300MB artifacts to ~100MB artifacts. Probably worth the CPU time.
0.0
c53270b41e1d3716c301e65a283d99f86aa55bb9
[ "tests/context_test.py::test_package_artifact", "tests/context_test.py::test_extract_artifact" ]
[ "tests/context_test.py::test_should_ignore_true[patterns0-venv]", "tests/context_test.py::test_should_ignore_true[patterns1-venv]", "tests/context_test.py::test_should_ignore_true[patterns2-this/is/some/venv]", "tests/context_test.py::test_should_ignore_true[patterns3-this/is/some/venv/with/a/file]", "tests/context_test.py::test_should_ignore_true[patterns4-this/is/some/venv/with/a/file]", "tests/context_test.py::test_should_ignore_true[patterns5-something.swp]", "tests/context_test.py::test_should_ignore_true[patterns6-hello/there/something.swp]", "tests/context_test.py::test_should_ignore_true[patterns7-my/.thing.txt.swo]", "tests/context_test.py::test_should_ignore_false[patterns0-this/is/some/venv]", "tests/context_test.py::test_should_ignore_false[patterns1-this/is/some/venv]", "tests/context_test.py::test_should_ignore_false[patterns2-venv2]", "tests/context_test.py::test_build_context_simple" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-03-10 19:38:00+00:00
apache-2.0
1,579
chriskuehl__rustenv-12
diff --git a/rustenv.py b/rustenv.py index ac82bb7..4cdbbc2 100644 --- a/rustenv.py +++ b/rustenv.py @@ -47,6 +47,7 @@ deactivate_rustenv() {{ unset _RUSTENV_BIN_PATH unset _RUSTENV_OLD_PS1 unset _RUSTENV_OLD_PATH + unset -f deactivate_rustenv }} '''
chriskuehl/rustenv
b2f3ae3f74bb7407c18e59700112098394eac323
diff --git a/tests/integration_test.py b/tests/integration_test.py index 72088d5..e1b3e5c 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -22,6 +22,7 @@ report() {{ echo "[[$1-rustc:$(rustc --version 2>&1)]]" echo "[[$1-cargo:$(cargo --version 2>&1)]]" echo "[[$1-hello:$(hello 2>&1)]]" + echo "[[$1-deactivate_rustenv:$(type deactivate_rustenv | head -1)]]" }} report start
`deactivate_rustenv` doesn't remove `deactivate_rustenv` ```console (renv) asottile@babibox:/tmp $ deactivate_rustenv asottile@babibox:/tmp $ which cargo asottile@babibox:/tmp $ deactivate_rustenv ehco hi bash: ehco: No such file or directory echo hi hi ```
0.0
b2f3ae3f74bb7407c18e59700112098394eac323
[ "tests/integration_test.py::test_runenv_shell[bash-{}:" ]
[ "tests/integration_test.py::test_rustenv_looks_sane" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-08-13 23:11:19+00:00
apache-2.0
1,580
chriskuehl__rustenv-15
diff --git a/rustenv.py b/rustenv.py index 4cdbbc2..f2b8aff 100644 --- a/rustenv.py +++ b/rustenv.py @@ -31,15 +31,17 @@ _RUSTENV_NAME='{RUSTENV_NAME}' # TODO: it might be nice to intelligently add/remove from PATH/PS1 instead of # just restoring the old one -_RUSTENV_OLD_PS1="$PS1" +_RUSTENV_OLD_PS1="${{PS1-}}" _RUSTENV_OLD_PATH="$PATH" export PATH="$_RUSTENV_BIN_PATH:$PATH" -export PS1="($_RUSTENV_NAME) $PS1" +export PS1="($_RUSTENV_NAME) ${{PS1-}}" hash -r 2>/dev/null deactivate_rustenv() {{ - export PS1="$_RUSTENV_OLD_PS1" + if ! [ -z "${{_RUSTENV_OLD_PS1+_}}" ] ; then + export PS1="$_RUSTENV_OLD_PS1" + fi export PATH="$_RUSTENV_OLD_PATH" hash -r 2>/dev/null
chriskuehl/rustenv
dd94d714d6c1a96bf4b0f5fb0ea7a751b23df915
diff --git a/tests/integration_test.py b/tests/integration_test.py index e1b3e5c..073695d 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -102,3 +102,16 @@ def test_runenv_shell(shell, not_found_message, built_rustenv, tmpdir): assert stages['installed']['hello'] == 'Hello World!' assert stages['uninstalled'] == stages['activated'] + + [email protected]('shell', ('bash', 'zsh')) +def test_works_without_ps1(shell, built_rustenv, tmpdir): + test_script = tmpdir.join('test.sh') + test_script.write( + """ + unset PS1 + set -euo pipefail + . {}/bin/activate + """.format(built_rustenv.strpath), + ) + subprocess.check_output((shell, test_script.strpath))
activate script doesn't work if there's no PS1 and the shell is `set -e` This happens e.g. in bash scripts (as opposed to logged-in sessions). ``` $ cat test.sh #!/bin/bash set -euo pipefail . renv/bin/activate $ ./test.sh renv/bin/activate: line 6: PS1: unbound variable ``` It should probably skip setting the PS1 in this case entirely?
0.0
dd94d714d6c1a96bf4b0f5fb0ea7a751b23df915
[ "tests/integration_test.py::test_works_without_ps1[bash]" ]
[ "tests/integration_test.py::test_runenv_shell[bash-{}:", "tests/integration_test.py::test_rustenv_looks_sane" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-09-17 05:18:44+00:00
apache-2.0
1,581
churchmanlab__genewalk-5
diff --git a/README.md b/README.md index 2b734e3..ae5d980 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ GeneWalk always requires as input a text file containing a list with genes of in relevant to the biological context. For example, differentially expressed genes from a sequencing experiment that compares an experimental versus control condition. GeneWalk supports gene list files containing HGNC human gene symbols, -HGNC IDs, or MGI mouse gene IDs. Each line in the file contains a gene identifier of +HGNC IDs, Ensembl IDs, or MGI mouse gene IDs. Each line in the file contains a gene identifier of one of these types. ### GeneWalk command line interface @@ -63,10 +63,10 @@ required arguments: --genes GENES Path to a text file with a list of differentially expressed genes. Thetype of gene identifiers used in the text file are provided in the id_type argument. - --id_type {hgnc_symbol,hgnc_id,mgi_id} + --id_type {hgnc_symbol,hgnc_id,ensembl_id,mgi_id} The type of gene IDs provided in the text file in the genes argument. Possible values are: hgnc_symbol, - hgnc_id, and mgi_id. + hgnc_id, ensembl_id, and mgi_id. optional arguments: --stage {all,node_vectors,null_distribution,statistics} diff --git a/genewalk/cli.py b/genewalk/cli.py index e1ebb80..42b41b5 100644 --- a/genewalk/cli.py +++ b/genewalk/cli.py @@ -65,8 +65,9 @@ def main(): parser.add_argument('--id_type', help='The type of gene IDs provided in the text file ' 'in the genes argument. Possible values are: ' - 'hgnc_symbol, hgnc_id, and mgi_id.', - choices=['hgnc_symbol', 'hgnc_id', 'mgi_id'], + 'hgnc_symbol, hgnc_id, ensembl_id, and mgi_id.', + choices=['hgnc_symbol', 'hgnc_id', + 'ensembl_id', 'mgi_id'], required=True) parser.add_argument('--stage', default='all', help='The stage of processing to run. Default: ' diff --git a/genewalk/gene_lists.py b/genewalk/gene_lists.py index c42235b..9737914 100644 --- a/genewalk/gene_lists.py +++ b/genewalk/gene_lists.py @@ -17,7 +17,7 @@ def read_gene_list(fname, id_type): file corresponds to a single gene. id_type : str The type of identifier contained in each line of the gene list file. - Possible values are: hgnc_symbol, hgnc_id, mgi_id. + Possible values are: hgnc_symbol, hgnc_id, ensembl_id, mgi_id. Returns ------- @@ -38,6 +38,8 @@ def read_gene_list(fname, id_type): return map_hgnc_symbols(unique_lines) elif id_type == 'hgnc_id': return map_hgnc_ids(unique_lines) + elif id_type == 'ensembl_id': + return map_ensembl_ids(unique_lines) elif id_type == 'mgi_id': return map_mgi_ids(unique_lines) else: @@ -115,3 +117,31 @@ def map_mgi_ids(mgi_ids): ref['UP'] = uniprot_id refs.append(ref) return refs + + +def map_ensembl_ids(ensembl_ids): + """Return references based on a list of Ensembl IDs.""" + refs = [] + for ensembl_id in ensembl_ids: + ref = {'HGNC_SYMBOL': None, 'HGNC': None, 'UP': None, + 'ENSEMBL': ensembl_id} + hgnc_id = hgnc_client.get_hgnc_from_ensembl(ensembl_id) + if not hgnc_id: + logger.warning('Could not get HGNC ID for ENSEMBL ID %s' % + ensembl_id) + continue + ref['HGNC'] = hgnc_id + hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) + if not hgnc_name: + logger.warning('Could not get HGNC name for ID %s' % + hgnc_id) + continue + ref['HGNC_SYMBOL'] = hgnc_name + uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) + if not uniprot_id: + logger.warning('Could not get UniProt ID for HGNC ID %s' % + hgnc_id) + continue + ref['UP'] = uniprot_id + refs.append(ref) + return refs diff --git a/setup.py b/setup.py index f913a4b..dfb4d59 100755 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ with open(path.join(here, 'README.md'), encoding='utf-8') as f: def main(): install_list = ['numpy', 'pandas', 'networkx>=2.1', 'gensim', 'goatools', - 'indra', 'scipy>=1.3.0'] + 'indra>=1.14.1', 'scipy>=1.3.0'] setup(name='genewalk', version='1.1.0',
churchmanlab/genewalk
ebefe0f83f54acb0c8472bfe919129fa07b8b92d
diff --git a/genewalk/tests/test_gene_lists.py b/genewalk/tests/test_gene_lists.py index 9715a4c..ac9fd42 100644 --- a/genewalk/tests/test_gene_lists.py +++ b/genewalk/tests/test_gene_lists.py @@ -22,3 +22,8 @@ def test_map_lists(): assert refs[0]['HGNC'] == '6817', refs assert refs[0]['HGNC_SYMBOL'] == 'MAL', refs assert refs[0]['UP'] == 'P21145', refs + + refs = map_ensembl_ids(['ENSG00000157764']) + assert refs[0]['HGNC'] == '1097', refs + assert refs[0]['UP'] == 'P15056', refs + assert refs[0]['HGNC_SYMBOL'] == 'BRAF', refs
ENSEMBL IDs Hi, a quick question: Is it possible to support also ENSEMBL IDs as input?
0.0
ebefe0f83f54acb0c8472bfe919129fa07b8b92d
[ "genewalk/tests/test_gene_lists.py::test_map_lists" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-16 00:50:22+00:00
bsd-2-clause
1,582
ciena__afkak-106
diff --git a/CHANGES.md b/CHANGES.md index 767780c..b7dc291 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,12 +1,14 @@ Version Next ============== -* **Feature:** The repr of the `afkak.Consumer` class has been cleaned up to make log messages that include it less noisy. +- **Feature:** `afkak.KafkaClient` now accepts a sequence ``(host, port)`` tuples as its ``hosts`` argument and when passed to the ``update_cluster_hosts()`` method. + This permits passing IPv6 addresses and fixes [#41](https://github.com/ciena/afkak/issues/41). + +* **Feature:** The string representation of `afkak.Consumer` instances has been cleaned up to make log messages that include it less noisy. It now looks like ``<Consumer topicname/0 running>`` where ``0`` is the partition number. * **Feature:** Additional contextual information has been added to several of `afkak.Consumer` debug log messages. - Version 19.8.0 ============== diff --git a/README.md b/README.md index 31213a0..8d9f8b9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # <img src="docs/_static/afkak.png" width="23" height="36" alt=""> Afkak: Twisted Python Kafka Client <a href="https://pypi.org/projects/afkak"><img src="https://img.shields.io/pypi/v/afkak.svg" alt="PyPI"></a> +<a href="https://calver.org/"><img src="https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg" alt="calver: YY.MM.MICRO"></a> <a href="./LICENSE"><img src="https://img.shields.io/pypi/l/afkak.svg" alt="Apache 2.0"></a> <a href="https://afkak.readthedocs.io/en/latest/"><img src="https://readthedocs.org/projects/pip/badge/" alt="Documentation"></a> <!-- diff --git a/afkak/client.py b/afkak/client.py index f90eaf8..7c48102 100644 --- a/afkak/client.py +++ b/afkak/client.py @@ -1258,8 +1258,14 @@ def _normalize_hosts(hosts): [('127.0.0.2', 2909), ('host', 9092)] :param hosts: - A list or comma-separated string of hostnames which may also include - port numbers. All of the following are valid:: + One of: + + - A comma-separated string of hostnames + - A sequence of strings of the form ``host`` or ``host:port`` + - A sequence of two-tuples of the form ``('host', port)`` + + Types are aggressively coerced for the sake of backwards compatibility, + so all of the following are valid:: b'host' u'host' @@ -1268,6 +1274,7 @@ def _normalize_hosts(hosts): b'host:1234 , host:2345 ' [u'host1', b'host2'] [b'host:1234', b'host:2345'] + [(b'host', 1234), (u'host', '234')] Hostnames must be ASCII (IDN is not supported). The default Kafka port of 9092 is implied when no port is given. @@ -1282,9 +1289,13 @@ def _normalize_hosts(hosts): result = set() for host_port in hosts: - # FIXME This won't handle IPv6 addresses - res = nativeString(host_port).split(':') - host = res[0].strip() - port = int(res[1].strip()) if len(res) > 1 else DefaultKafkaPort + if isinstance(host_port, (bytes, _unicode)): + res = nativeString(host_port).split(':') + host = res[0].strip() + port = int(res[1].strip()) if len(res) > 1 else DefaultKafkaPort + else: + host, port = host_port + host = nativeString(host) + port = int(port) result.add((host, port)) return sorted(result)
ciena/afkak
bd03cbdbe562dfec42299bd3d9927809bd204627
diff --git a/afkak/test/test_client.py b/afkak/test/test_client.py index 6f220fb..62e38cb 100644 --- a/afkak/test/test_client.py +++ b/afkak/test/test_client.py @@ -198,11 +198,27 @@ class TestKafkaClient(unittest.TestCase): self.assertRaises(Exception, KafkaClient, 'kafka.example.com', clientId='MyClient', timeout="100ms") self.assertRaises(TypeError, KafkaClient, 'kafka.example.com', clientId='MyClient', timeout=None) + def test_client_bad_hosts(self): + """ + `KafkaClient.__init__` raises an exception when passed an invalid + *hosts* argument. + """ + self.assertRaises(Exception, KafkaClient, hosts='foo:notaport') + def test_update_cluster_hosts(self): c = KafkaClient(hosts='www.example.com') c.update_cluster_hosts('meep.org') self.assertEqual(c._bootstrap_hosts, [('meep.org', 9092)]) + def test_update_cluster_hosts_empty(self): + """ + Attempting to set empty bootstrap hosts raises an exception. The + configured hosts don't change. + """ + c = KafkaClient(hosts=[('kafka.example.com', 1234)]) + self.assertRaises(Exception, c.update_cluster_hosts, ['foo:notaport']) + self.assertEqual(c._bootstrap_hosts, [('kafka.example.com', 1234)]) + def test_send_broker_unaware_request_bootstrap_fail(self): """ Broker unaware requests fail with `KafkaUnavailableError` when boostrap @@ -1671,3 +1687,30 @@ class NormalizeHostsTests(unittest.TestCase): self.assertEqual([('kafka', 1234)], _normalize_hosts(u'kafka:1234 ')) self.assertEqual([('kafka', 1234), ('kafka', 2345)], _normalize_hosts(u'kafka:1234 ,kafka:2345')) self.assertEqual([('1.2.3.4', 5555)], _normalize_hosts(b' 1.2.3.4:5555 ')) + + def test_sequence(self): + """ + The input may be a sequence of hostnames or host ports. The default + port is implied when none is given. + """ + self.assertEqual( + [('kafka', 9092)], + _normalize_hosts([u'kafka', b'kafka', ('kafka', 9092)]), + ) + self.assertEqual( + [('kafka1', 9092), ('kafka2', 9092)], + _normalize_hosts([('kafka2', 9092), ('kafka1', 9092)]), + ) + self.assertEqual( + [('kafka1', 1234), ('kafka2', 2345)], + _normalize_hosts([('kafka2', u'2345'), ('kafka1', b'1234')]), + ) + + def test_ipv6(self): + """ + IPv6 addresses may be passed as part of a sequence. + """ + self.assertEqual( + [('2001:db8::1', 2345), ('::1', 1234)], + _normalize_hosts([('2001:db8::1', '2345'), (b'::1', 1234)]), + )
KafkaUnavailableError due to bad hosts argument I passed a value like `[('host1', 1234), ('host2', 1234)]` as the first argument to `KafkaClient`, which isn't supported. Instead of a `ValueError` or `TypeError`, I got a `KafkaUnavailableError` at a later time which wrapped the appropriate `TypeError`: ``` Traceback (most recent call last): File "/home/tmost/dev/porch/afkak/.tox/py27-int-snappy-murmur/local/lib/python2.7/site-packages/twisted/internet /defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/home/tmost/dev/porch/afkak/afkak/client.py", line 346, in _handleMetadataErr "hosts: {!r}".format(err)) KafkaUnavailableError: Unable to load metadata from configured hosts: <twisted.python.failure.Failure exceptions.TypeError: not all arguments converted during string formatting> ``` In this case `TypeError` should be raised synchronously by the `KafkaClient` constructor.
0.0
bd03cbdbe562dfec42299bd3d9927809bd204627
[ "afkak/test/test_client.py::TestKafkaClient::test_update_cluster_hosts_empty", "afkak/test/test_client.py::NormalizeHostsTests::test_sequence", "afkak/test/test_client.py::NormalizeHostsTests::test_ipv6" ]
[ "afkak/test/test_client.py::TestKafkaClient::test_send_produce_request_raises_when_noleader", "afkak/test/test_client.py::TestKafkaClient::test_load_consumer_metadata_for_group_unavailable", "afkak/test/test_client.py::TestKafkaClient::test_repr", "afkak/test/test_client.py::TestKafkaClient::test_reset_topic_metadata_errors", "afkak/test/test_client.py::TestKafkaClient::test_get_leader_for_partitions_loads_metadata", "afkak/test/test_client.py::TestKafkaClient::test_send_request_to_coordinator", "afkak/test/test_client.py::TestKafkaClient::test_client_disconnect_on_timeout_true", "afkak/test/test_client.py::TestKafkaClient::test_client_close_during_metadata_load", "afkak/test/test_client.py::TestKafkaClient::test_get_leader_for_unassigned_partitions", "afkak/test/test_client.py::TestKafkaClient::test_client_close", "afkak/test/test_client.py::TestKafkaClient::test_has_metadata_for_topic", "afkak/test/test_client.py::TestKafkaClient::test_load_consumer_metadata_for_group", "afkak/test/test_client.py::TestKafkaClient::test_get_leader_cached", "afkak/test/test_client.py::TestKafkaClient::test_update_cluster_hosts", "afkak/test/test_client.py::TestKafkaClient::test_get_leader_returns_none_when_noleader", "afkak/test/test_client.py::TestKafkaClient::test_send_offset_commit_request", "afkak/test/test_client.py::TestKafkaClient::test_send_fetch_request_bad_timeout", "afkak/test/test_client.py::TestKafkaClient::test_send_offset_fetch_request_failure", "afkak/test/test_client.py::TestKafkaClient::test_client_bad_hosts", "afkak/test/test_client.py::TestKafkaClient::test_make_request_to_broker_min_timeout", "afkak/test/test_client.py::TestKafkaClient::test_send_produce_request", "afkak/test/test_client.py::TestKafkaClient::test_send_offset_commit_request_failure", "afkak/test/test_client.py::TestKafkaClient::test_make_request_to_broker_alerts_when_blocked", "afkak/test/test_client.py::TestKafkaClient::test_reset_all_metadata", "afkak/test/test_client.py::TestKafkaClient::test_send_broker_unaware_request_brokers_fail", "afkak/test/test_client.py::TestKafkaClient::test_client_topic_fully_replicated", "afkak/test/test_client.py::TestKafkaClient::test_send_offset_request", "afkak/test/test_client.py::TestKafkaClient::test_client_disconnect_on_timeout_false", "afkak/test/test_client.py::TestKafkaClient::test_client_bad_timeout", "afkak/test/test_client.py::TestKafkaClient::test_load_consumer_metadata_for_group_failure", "afkak/test/test_client.py::TestKafkaClient::test_get_brokerclient", "afkak/test/test_client.py::TestKafkaClient::test_send_broker_unaware_request_bootstrap_fail", "afkak/test/test_client.py::TestKafkaClient::test_client_close_poisons", "afkak/test/test_client.py::TestKafkaClient::test_send_offset_fetch_request", "afkak/test/test_client.py::TestKafkaClient::test_send_produce_request_timeout", "afkak/test/test_client.py::TestKafkaClient::test_load_metadata_for_topics", "afkak/test/test_client.py::TestKafkaClient::test_send_fetch_request", "afkak/test/test_client.py::TestKafkaClient::test_reset_topic_metadata", "afkak/test/test_client.py::TestKafkaClient::test_client_close_no_clients", "afkak/test/test_client.py::NormalizeHostsTests::test_string_with_ports", "afkak/test/test_client.py::NormalizeHostsTests::test_bare_host_string" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-09-19 00:35:09+00:00
apache-2.0
1,583
circus-tent__circus-1128
diff --git a/circus/util.py b/circus/util.py index 76bf43a7..e7324ce4 100644 --- a/circus/util.py +++ b/circus/util.py @@ -144,8 +144,8 @@ def bytes2human(n): for s in reversed(_SYMBOLS): if n >= prefix[s]: - value = int(float(n) / prefix[s]) - return '%s%s' % (value, s) + value = round(float(n) / prefix[s], 2) + return '{:.2f}{}'.format(value, s) return "%sB" % n
circus-tent/circus
422d64dbf5823bd5c81c08d0b2a881c296b3d603
diff --git a/circus/tests/test_util.py b/circus/tests/test_util.py index 1b4256d0..e74f48e1 100644 --- a/circus/tests/test_util.py +++ b/circus/tests/test_util.py @@ -92,8 +92,10 @@ class TestUtil(TestCase): self.assertEqual(util.convert_opt('test', 1), '1') def test_bytes2human(self): - self.assertEqual(bytes2human(10000), '9K') - self.assertEqual(bytes2human(100001221), '95M') + self.assertEqual(bytes2human(100), '100B') + self.assertEqual(bytes2human(10000), '9.77K') + self.assertEqual(bytes2human(100001221), '95.37M') + self.assertEqual(bytes2human(1024 * 1024 * 2047), '2.00G') self.assertRaises(TypeError, bytes2human, '1') def test_human2bytes(self): @@ -102,6 +104,8 @@ class TestUtil(TestCase): self.assertEqual(human2bytes('1129M'), 1183842304) self.assertEqual(human2bytes('67T'), 73667279060992) self.assertEqual(human2bytes('13P'), 14636698788954112) + self.assertEqual(human2bytes('1.99G'), 2136746229) + self.assertEqual(human2bytes('2.00G'), 2147483648) self.assertRaises(ValueError, human2bytes, '') self.assertRaises(ValueError, human2bytes, 'faoej') self.assertRaises(ValueError, human2bytes, '123KB')
mem_info not reliable The human friendly representation gives integer representation instead of float which gives unreliable stats. ``` >>> from circus.util import bytes2human >>> bytes2human(1024 * 1024 * 2047) '1G' >>> bytes2human(1024 * 1024 * 2048) '2G' ``` The first example should return `1.99G` ideally. This is not critical when talking about megas but when we start talking about gigas or more it gets problematic. Also why not always give a MiB representation in float (not string) ?
0.0
422d64dbf5823bd5c81c08d0b2a881c296b3d603
[ "circus/tests/test_util.py::TestUtil::test_bytes2human" ]
[ "circus/tests/test_util.py::TestUtil::test_convert_opt", "circus/tests/test_util.py::TestUtil::test_load_virtualenv", "circus/tests/test_util.py::TestUtil::test_get_python_version", "circus/tests/test_util.py::TestUtil::test_working_dir_return_pwd_when_paths_are_equals", "circus/tests/test_util.py::TestUtil::test_negative_uid_gid", "circus/tests/test_util.py::TestUtil::test_tobool", "circus/tests/test_util.py::TestUtil::test_human2bytes", "circus/tests/test_util.py::TestUtil::test_parse_env_str", "circus/tests/test_util.py::TestUtil::test_to_uidgid", "circus/tests/test_util.py::TestUtil::test_replace_gnu_args", "circus/tests/test_util.py::TestUtil::test_get_info", "circus/tests/test_util.py::TestUtil::test_to_uid", "circus/tests/test_util.py::TestUtil::test_get_info_still_works_when_denied_access", "circus/tests/test_util.py::TestUtil::test_to_gid_str", "circus/tests/test_util.py::TestUtil::test_to_uid_str" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-03-30 14:50:58+00:00
apache-2.0
1,584
cisagov__check-cve-2019-19781-10
diff --git a/src/check_cve/check.py b/src/check_cve/check.py index 25a8fab..ac27a0f 100755 --- a/src/check_cve/check.py +++ b/src/check_cve/check.py @@ -61,7 +61,7 @@ def is_vulnerable(host, retries=2, timeout=10): logging.debug(f"Response status: {response.status}") - decoded_data = response.data.decode() + decoded_data = response.data.decode("utf-8", errors="ignore") logging.debug(f"Data:\n{decoded_data}") return INSECURE_CONTENT in decoded_data
cisagov/check-cve-2019-19781
4142e02b96a537a4be5d367d564e242d9e8d3a84
diff --git a/tests/test_check_cve.py b/tests/test_check_cve.py index 8919e0c..d922e5d 100644 --- a/tests/test_check_cve.py +++ b/tests/test_check_cve.py @@ -128,3 +128,16 @@ def test_non_vuln_host(): mock_lib.PoolManager().request().status = 403 return_code = check_cve.check.main() assert return_code == 0, "main() should return success" + + +def test_non_utf8_response(): + """Verify the utility handles responses containing invalid utf-8 data.""" + # Hebrew string saying "forged" + bogus = "מזויף means bogus" + bogus_iso_8859_8 = bogus.encode("iso-8859-8") + with patch.object(sys, "argv", ["exe_name", "--log-level=debug", "github.com"]): + with patch("check_cve.check.urllib3") as mock_lib: + mock_lib.PoolManager().request().data = bogus_iso_8859_8 + mock_lib.PoolManager().request().status = 403 + return_code = check_cve.check.main() + assert return_code == 0, "main() should return success"
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1144: invalid start byte # 🐛 Bug Report ```console $ cve-2019-19781 citrix.beispiel.de Traceback (most recent call last): File "/home/ehret/.local/bin/cve-2019-19781", line 11, in <module> load_entry_point('cve-2019-19781', 'console_scripts', 'cve-2019-19781')() File "/tmp/check-cve-2019-19781/src/check_cve/check.py", line 117, in main if is_vulnerable(host, retries, timeout): File "/tmp/check-cve-2019-19781/src/check_cve/check.py", line 64, in is_vulnerable decoded_data = response.data.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1144: invalid start byte ```
0.0
4142e02b96a537a4be5d367d564e242d9e8d3a84
[ "tests/test_check_cve.py::test_non_utf8_response" ]
[ "tests/test_check_cve.py::test_stdout_version", "tests/test_check_cve.py::test_log_levels[debug]", "tests/test_check_cve.py::test_log_levels[info]", "tests/test_check_cve.py::test_log_levels[warning]", "tests/test_check_cve.py::test_log_levels[error]", "tests/test_check_cve.py::test_log_levels[critical]", "tests/test_check_cve.py::test_missing_host_arg", "tests/test_check_cve.py::test_connection_error", "tests/test_check_cve.py::test_valid_timeout", "tests/test_check_cve.py::test_invalid_timeout", "tests/test_check_cve.py::test_valid_retries", "tests/test_check_cve.py::test_invalid_retries", "tests/test_check_cve.py::test_vuln_host", "tests/test_check_cve.py::test_non_vuln_host" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-01-14 20:24:01+00:00
cc0-1.0
1,585
cityofaustin__knackpy-110
diff --git a/coverage.svg b/coverage.svg index ee07d4c..3438732 100644 --- a/coverage.svg +++ b/coverage.svg @@ -15,7 +15,7 @@ <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11"> <text x="31.5" y="15" fill="#010101" fill-opacity=".3">coverage</text> <text x="31.5" y="14">coverage</text> - <text x="80" y="15" fill="#010101" fill-opacity=".3">96%</text> - <text x="80" y="14">96%</text> + <text x="80" y="15" fill="#010101" fill-opacity=".3">97%</text> + <text x="80" y="14">97%</text> </g> </svg> diff --git a/knackpy/models.py b/knackpy/models.py index 1c64fd9..a39946c 100644 --- a/knackpy/models.py +++ b/knackpy/models.py @@ -16,6 +16,7 @@ FIELD_SETTINGS = { "name": {"use_knack_format": True, "subfields": ["first", "middle", "last", ]}, "timer": {"use_knack_format": True}, "id": {"use_knack_format": True}, # because there is no "raw" format for this field + "equation": {"use_knack_format": True} } TIMEZONES = [ diff --git a/setup.py b/setup.py index dd97d9b..3c30598 100644 --- a/setup.py +++ b/setup.py @@ -46,7 +46,7 @@ def build_config(env, readme="README.md"): "packages": ["knackpy"], "tests_require": ["pytest", "coverage"], "url": "http://github.com/cityofaustin/knackpy", - "version": "1.0.21", + "version": "1.1.0", }
cityofaustin/knackpy
0035913119e39a0c243603090370e862585a32ab
diff --git a/tests/_all_fields.json b/tests/_all_fields.json index 39e5ef5..c3fb90c 100644 --- a/tests/_all_fields.json +++ b/tests/_all_fields.json @@ -1,1 +1,1 @@ -{"records":[{"id":"5d7964422d7159001659b27a","field_11":1,"field_11_raw":1,"field_125":"1","field_125_raw":"1","field_6":"Extra Cheese","field_6_raw":"Extra Cheese","field_7":"hello","field_7_raw":"hello","field_8":"<p><strong>bold rich text</strong><span></span></p><h1>heading 1</h1><table><tbody><tr><td>tablerow</td><td>1</td><td>1</td></tr><tr><td>tablerow</td><td>23</td><td>25</td></tr></tbody></table>","field_8_raw":"<p><strong>bold rich text</strong><span></span></p><h1>heading 1</h1><table><tbody><tr><td>tablerow</td><td>1</td><td>1</td></tr><tr><td>tablerow</td><td>23</td><td>25</td></tr></tbody></table>","field_10":100,"field_10_raw":100,"field_12":"09/11/2019","field_12_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568160000000,"iso_timestamp":"2019-09-11T00:00:00.000Z","timestamp":"09/11/2019 12:00 am","time":720},"field_13":"07/03/2018 10:26","field_13_raw":{"date":"07/03/2018","date_formatted":"07/03/2018","hours":"10","minutes":"26","am_pm":"AM","unix_timestamp":1530613560000,"iso_timestamp":"2018-07-03T10:26:00.000Z","timestamp":"07/03/2018 10:26 am","time":626},"field_14":"4:14pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"14","am_pm":"PM","unix_timestamp":1325434440000,"iso_timestamp":"2012-01-01T16:14:00.000Z","timestamp":"01/01/2012 04:14 pm","time":974},"field_15":"09/11/2019 4:14pm to 5:14pm","field_15_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"14","am_pm":"PM","unix_timestamp":1568218440000,"iso_timestamp":"2019-09-11T16:14:00.000Z","timestamp":"09/11/2019 04:14 pm","time":974,"to":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"05","minutes":"14","am_pm":"PM","unix_timestamp":1568222040000,"iso_timestamp":"2019-09-11T17:14:00.000Z","timestamp":"09/11/2019 05:14 pm","time":1034}},"field_16":"<span>09/11/19</span>&nbsp;4:14pm to 5:14pm = 1:00 hours","field_16_raw":{"total_time":3600000,"times":[{"to":{"time":1034,"timestamp":"09/11/2019 05:14 pm","iso_timestamp":"2019-09-11T17:14:00.000Z","unix_timestamp":1568222040000,"am_pm":"PM","minutes":"14","hours":"05","date_formatted":"09/11/2019","date":"09/11/2019"},"from":{"time":974,"timestamp":"09/11/2019 04:14 pm","iso_timestamp":"2019-09-11T16:14:00.000Z","unix_timestamp":1568218440000,"am_pm":"PM","minutes":"14","hours":"04","date_formatted":"09/11/2019","date":"09/11/2019"}}]},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5d7967132be2bb0010892ce7\" data-file-name=\"0.omfbylawsapproved1.pdf\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d7967132be2bb0010892ce7/0.omfbylawsapproved1.pdf\">0.omfbylawsapproved1.pdf</a>","field_17_raw":{"id":"5d7967132be2bb0010892ce7","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"0.omfbylawsapproved1.pdf","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d7967132be2bb0010892ce7/0.omfbylawsapproved1.pdf","thumb_url":"","size":305741,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/thumb/my_car_mazda_q.jpg\" />","field_18_raw":{"id":"5d7966ecc8d68e0010c0834a","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"my_car_mazda_q.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/original/my_car_mazda_q.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/thumb/my_car_mazda_q.jpg","size":1219841,"field_key":"field_18"},"field_19":"the Hut, Pizza Danger","field_19_raw":{"first":"Pizza","middle":"Danger","last":"the Hut"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"8700 Cameron Rd<br />Suite 1<br />Austin, TX 78754","field_21_raw":{"zip":"78754","state":"TX","city":"Austin","street2":"Suite 1","street":"8700 Cameron Rd"},"field_22":"(512) 974-3546","field_22_raw":{"area":"512","number":"9743546","full":"5129743546","formatted":"(512) 974-3546"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzg5IiBoZWlnaHQ9Ijg5Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMTAgNjUgYyAwIC0wLjQyIC0wLjkyIC0xNi40MiAwIC0yNCBjIDAuNjggLTUuNiAyLjkzIC0xMS40NyA1IC0xNyBjIDEuOTQgLTUuMTYgNC40MiAtMTAuMzEgNyAtMTUgYyAxIC0xLjgxIDIuNTQgLTMuNTQgNCAtNSBjIDEuMTQgLTEuMTQgMi42NyAtMi44MyA0IC0zIGMgMy4yMSAtMC40IDkuMjcgLTAuMDkgMTIgMSBjIDEuMzIgMC41MyAyLjU4IDMuMjUgMyA1IGMgMS43NiA3LjI5IDMuMTEgMTUuOTggNCAyNCBjIDAuNDQgMy45NSAwLjcxIDguMzMgMCAxMiBjIC0wLjg4IDQuNTUgLTIuNjkgMTAgLTUgMTQgYyAtMi40MyA0LjIxIC02LjQgOC4yMiAtMTAgMTIgYyAtMy4xIDMuMjUgLTYuNDcgNi41MyAtMTAgOSBjIC0yLjkzIDIuMDUgLTYuNTggMy44MSAtMTAgNSBjIC00LjA4IDEuNDIgLTEzLjIgMy4xMSAtMTMgMyBjIDAuMzkgLTAuMjEgMTYuMiAtNS40MyAyNCAtOSBjIDguMyAtMy44MSAxNS45OSAtOC4zMyAyNCAtMTMgYyA0LjIzIC0yLjQ3IDguMTggLTUuMDMgMTIgLTggYyA1LjI2IC00LjA5IDEwLjMzIC04LjMzIDE1IC0xMyBjIDQuMDEgLTQuMDEgNi45NyAtMTEuMjQgMTEgLTEzIGMgNC45OCAtMi4xOCAxNy4wMyAtMS43MiAyMSAtMSBjIDAuOTYgMC4xNyAxLjczIDMuOTkgMSA1IGMgLTMuOTIgNS40NSAtMTcuNTUgMTcuMSAtMTkgMjAgYyAtMC40MyAwLjg3IDUuMzYgMS42OSA4IDIgYyAyLjg4IDAuMzQgNi4yMSAwLjYyIDkgMCBjIDguNzQgLTEuOTQgMjMuNzggLTcuNSAyNyAtOCBjIDAuNDcgLTAuMDcgLTAuMzMgMi45MiAtMSA0IGMgLTMuMzggNS40NiAtMTAuNDcgMTMuNzYgLTEyIDE3IGMgLTAuMjcgMC41NiAyLjE0IDIuMTggMyAyIGMgNC4wOSAtMC44NiAxMC43OCAtMy42NCAxNiAtNiBjIDUuMiAtMi4zNSAxMy44NSAtNy44MSAxNSAtOCBjIDAuNDUgLTAuMDggLTEuNzcgNC4yMiAtMyA2IGMgLTEuNjkgMi40NSAtNi4xMyA3LjEgLTYgNyBjIDAuNTggLTAuNDcgMzEuMTkgLTI3LjQ0IDMyIC0yOCBjIDAuMjkgLTAuMiAtNi43MiA4LjEyIC05IDEyIGMgLTAuNzggMS4zMiAtMC40NSAzLjU0IC0xIDUgYyAtMC4zOSAxLjAzIC0yIDIuMjEgLTIgMyBjIDAgMC43OSAxLjM1IDMuMTIgMiAzIGMgMS44NiAtMC4zNCA2LjIzIC00LjMxIDkgLTUgYyAxLjkgLTAuNDggNC42NCAwLjkyIDcgMSBjIDguMDIgMC4yNiAxNi4yMyAwLjYzIDI0IDAgYyA0LjMyIC0wLjM1IDguODYgLTEuNzggMTMgLTMgYyAxLjM5IC0wLjQxIDQgLTEuNTQgNCAtMiBsIC00IC0yIi8+PHBhdGggc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZT0icmdiKDg1LCA4NCwgODkpIiBmaWxsPSJub25lIiBkPSJNIDIxNCAxNCBsIDAgNDciLz48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMTk2IDQxIGMgMC45NiAwIDQ4Ljk5IDAuMzQgNTUgMCBjIDAuMzkgLTAuMDIgLTEuMTggLTIuMTggLTIgLTMgYyAtMy4zOSAtMy4zOSAtOC4yIC02LjQ2IC0xMSAtMTAgYyAtMS44NSAtMi4zNSAtMy45NSAtOS40NiAtNCAtOSBjIC0wLjIzIDIuMjcgLTQuODkgMzguNDUgMCA0OSBjIDMuNzcgOC4xMiAyMy42NyAxNS45NSAzMiAyMCBjIDEuMTkgMC41OCAzLjM3IC0xLjcgNSAtMiBjIDEuODIgLTAuMzMgNC4xOCAwLjM5IDYgMCBjIDIuNTkgLTAuNTYgNi4zOSAtMS4yOSA4IC0zIGMgMy4zMSAtMy41IDYuMzQgLTEzIDkgLTE1IGMgMS4xNiAtMC44NyA1LjI2IDMuMTUgNyAzIGMgMS40NyAtMC4xMiA0LjEyIC0yLjUzIDUgLTQgbCAxIC02Ii8+PHBhdGggc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZT0icmdiKDg1LCA4NCwgODkpIiBmaWxsPSJub25lIiBkPSJNIDMyNSAyMSBjIDAuMDIgMC4xIDAuOTUgMy45OCAxIDYgYyAwLjI4IDExLjYgLTAuMzkgMzEuOTYgMCAzNSBjIDAuMDYgMC40OSAyLjU2IC0yLjg4IDQgLTQgYyAxLjQ5IC0xLjE2IDMuMzcgLTIuOTQgNSAtMyBjIDYuNzUgLTAuMjMgMTcuNTYgMC44MSAyNCAyIGMgMS4xMyAwLjIxIDEuOTEgMi43OSAzIDMgYyAzLjM1IDAuNjMgOS40MSAxLjEgMTMgMCBjIDQuMjEgLTEuMyAxMyAtOCAxMyAtOCIvPjwvc3ZnPg==\" />","field_23_raw":{"base30":"1W0023344484340Z5aaa67Y68acccf4527681Z5644Y899855Z14332Y36aa5Z333Y36d64Z5412Y25477h584Z4_2QZae7a87530Y15ocec9521Z234678d553100Y5564520Z3212Y464432Z2453Y643Z26c44Y66533Z32Y100Z1222_8Q00000_1vb9c96_8y66hc86Z26522000Y1w568432751_1W000000Z35554YfcmkZ203744Y3Z46_cH10000458556376643_1C66bd5Z43Y1010300Z332","svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"389\" height=\"89\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 10 65 c 0 -0.42 -0.92 -16.42 0 -24 c 0.68 -5.6 2.93 -11.47 5 -17 c 1.94 -5.16 4.42 -10.31 7 -15 c 1 -1.81 2.54 -3.54 4 -5 c 1.14 -1.14 2.67 -2.83 4 -3 c 3.21 -0.4 9.27 -0.09 12 1 c 1.32 0.53 2.58 3.25 3 5 c 1.76 7.29 3.11 15.98 4 24 c 0.44 3.95 0.71 8.33 0 12 c -0.88 4.55 -2.69 10 -5 14 c -2.43 4.21 -6.4 8.22 -10 12 c -3.1 3.25 -6.47 6.53 -10 9 c -2.93 2.05 -6.58 3.81 -10 5 c -4.08 1.42 -13.2 3.11 -13 3 c 0.39 -0.21 16.2 -5.43 24 -9 c 8.3 -3.81 15.99 -8.33 24 -13 c 4.23 -2.47 8.18 -5.03 12 -8 c 5.26 -4.09 10.33 -8.33 15 -13 c 4.01 -4.01 6.97 -11.24 11 -13 c 4.98 -2.18 17.03 -1.72 21 -1 c 0.96 0.17 1.73 3.99 1 5 c -3.92 5.45 -17.55 17.1 -19 20 c -0.43 0.87 5.36 1.69 8 2 c 2.88 0.34 6.21 0.62 9 0 c 8.74 -1.94 23.78 -7.5 27 -8 c 0.47 -0.07 -0.33 2.92 -1 4 c -3.38 5.46 -10.47 13.76 -12 17 c -0.27 0.56 2.14 2.18 3 2 c 4.09 -0.86 10.78 -3.64 16 -6 c 5.2 -2.35 13.85 -7.81 15 -8 c 0.45 -0.08 -1.77 4.22 -3 6 c -1.69 2.45 -6.13 7.1 -6 7 c 0.58 -0.47 31.19 -27.44 32 -28 c 0.29 -0.2 -6.72 8.12 -9 12 c -0.78 1.32 -0.45 3.54 -1 5 c -0.39 1.03 -2 2.21 -2 3 c 0 0.79 1.35 3.12 2 3 c 1.86 -0.34 6.23 -4.31 9 -5 c 1.9 -0.48 4.64 0.92 7 1 c 8.02 0.26 16.23 0.63 24 0 c 4.32 -0.35 8.86 -1.78 13 -3 c 1.39 -0.41 4 -1.54 4 -2 l -4 -2\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 214 14 l 0 47\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 196 41 c 0.96 0 48.99 0.34 55 0 c 0.39 -0.02 -1.18 -2.18 -2 -3 c -3.39 -3.39 -8.2 -6.46 -11 -10 c -1.85 -2.35 -3.95 -9.46 -4 -9 c -0.23 2.27 -4.89 38.45 0 49 c 3.77 8.12 23.67 15.95 32 20 c 1.19 0.58 3.37 -1.7 5 -2 c 1.82 -0.33 4.18 0.39 6 0 c 2.59 -0.56 6.39 -1.29 8 -3 c 3.31 -3.5 6.34 -13 9 -15 c 1.16 -0.87 5.26 3.15 7 3 c 1.47 -0.12 4.12 -2.53 5 -4 l 1 -6\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 325 21 c 0.02 0.1 0.95 3.98 1 6 c 0.28 11.6 -0.39 31.96 0 35 c 0.06 0.49 2.56 -2.88 4 -4 c 1.49 -1.16 3.37 -2.94 5 -3 c 6.75 -0.23 17.56 0.81 24 2 c 1.13 0.21 1.91 2.79 3 3 c 3.35 0.63 9.41 1.1 13 0 c 4.21 -1.3 13 -8 13 -8\"/></svg>"},"field_24":"<a href=\"https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9\">https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9</a>","field_24_raw":{"url":"https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9"},"field_25":"0.00","field_25_raw":0,"field_9":"he two three (four)","field_9_raw":"he two three (four)","field_29":"No","field_29_raw":false,"field_30":"$100.43","field_30_raw":"100.43","field_37":"09/13/2019 2:43am","field_37_raw":{"date":"09/13/2019","date_formatted":"09/13/2019","hours":"02","minutes":"43","am_pm":"AM","unix_timestamp":1568342580000,"iso_timestamp":"2019-09-13T02:43:00.000Z","timestamp":"09/13/2019 02:43 am","time":163},"field_38":"No","field_38_raw":false,"field_50":"<img src=\"google.com\" />","field_50_raw":"google.com","field_44":"Bauchi ","field_44_raw":{"latitude":10,"longitude":10,"state":"Bauchi","country":"Nigeria"},"field_76":"July pizza Tuesday ","field_76_raw":"July pizza Tuesday ","field_126":"123 Calle Uno<br />Suite 22<br />Mexico City, State of Mexico 102392A","field_126_raw":{"street":"123 Calle Uno","street2":"Suite 22","city":"Mexico City","state":"State of Mexico","zip":"102392A"},"field_127":"123 Fake St<br />APT C<br />London, London ABC123<br />United Kingdom","field_127_raw":{"street":"123 Fake St","street2":"APT C","city":"London","state":"London","zip":"ABC123","country":"United Kingdom"},"field_128":"<span class=\"5ea46ad2b6ce4b0015000ae8\">Johnny C</span>","field_128_raw":[{"id":"5ea46ad2b6ce4b0015000ae8","identifier":"Johnny C"}],"field_129":10,"field_129_raw":10},{"id":"5d7968c8092e7f00106c6399","field_11":2,"field_11_raw":2,"field_125":"3","field_125_raw":"3","field_6":"Jalapeños","field_6_raw":"Jalapeños","field_7":"Hello SHort Text","field_7_raw":"Hello SHort Text","field_8":"<p>boring rich text</p>","field_8_raw":"<p>boring rich text</p>","field_10":0,"field_10_raw":0,"field_12":"09/11/2019","field_12_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568160000000,"iso_timestamp":"2019-09-11T00:00:00.000Z","timestamp":"09/11/2019 12:00 am","time":720},"field_13":"09/11/2019 16:35","field_13_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1568219700000,"iso_timestamp":"2019-09-11T16:35:00.000Z","timestamp":"09/11/2019 04:35 pm","time":995},"field_14":"4:35pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1325435700000,"iso_timestamp":"2012-01-01T16:35:00.000Z","timestamp":"01/01/2012 04:35 pm","time":995},"field_15":"09/11/2019 4:35pm to 5:35pm","field_15_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1568219700000,"iso_timestamp":"2019-09-11T16:35:00.000Z","timestamp":"09/11/2019 04:35 pm","time":995,"to":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"05","minutes":"35","am_pm":"PM","unix_timestamp":1568223300000,"iso_timestamp":"2019-09-11T17:35:00.000Z","timestamp":"09/11/2019 05:35 pm","time":1055}},"field_16":"<span>09/11/19</span>&nbsp;4:35pm to 5:35pm = 1:00 hours","field_16_raw":{"total_time":3600000,"times":[{"to":{"time":1055,"timestamp":"09/11/2019 05:35 pm","iso_timestamp":"2019-09-11T17:35:00.000Z","unix_timestamp":1568223300000,"am_pm":"PM","minutes":"35","hours":"05","date_formatted":"09/11/2019","date":"09/11/2019"},"from":{"time":995,"timestamp":"09/11/2019 04:35 pm","iso_timestamp":"2019-09-11T16:35:00.000Z","unix_timestamp":1568219700000,"am_pm":"PM","minutes":"35","hours":"04","date_formatted":"09/11/2019","date":"09/11/2019"}}]},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5d796903335a510011275b67\" data-file-name=\"ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d796903335a510011275b67/ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf\">ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf</a>","field_17_raw":{"id":"5d796903335a510011275b67","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d796903335a510011275b67/ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf","thumb_url":"","size":8619743,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/thumb/screenshot20190906at9.32.13am.png\" />","field_18_raw":{"id":"5d79691475f07d00103a3b0b","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"screenshot20190906at9.32.13am.png","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/original/screenshot20190906at9.32.13am.png","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/thumb/screenshot20190906at9.32.13am.png","size":3220795,"field_key":"field_18"},"field_19":"Lognestnameeverprobableimnotsure, Sally","field_19_raw":{"first":"Sally","last":"Lognestnameeverprobableimnotsure"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"1600 Pennsylvania Ave<br />Washington, DC ","field_21_raw":{"street":"1600 Pennsylvania Ave","street2":"","city":"Washington","state":"DC","zip":""},"field_22":"(800) 234-4444","field_22_raw":{"formatted":"(800) 234-4444","full":"8002344444","number":"2344444","area":"800"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzY1IiBoZWlnaHQ9Ijk5Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMSAzMiBjIDAuMDkgMC4wMyAzLjM1IDEuODQgNSAyIGMgNC45IDAuNDcgMTAuNzcgMC41NyAxNiAwIGMgNi45OSAtMC43NiAxNC40NyAtMi4wMiAyMSAtNCBjIDQuMSAtMS4yNCA4LjIgLTMuNjYgMTIgLTYgYyA0Ljg3IC0zIDExLjYzIC05LjQxIDE0IC0xMCBjIDAuODcgLTAuMjIgMS44MyA0LjAyIDIgNiBjIDAuNDYgNS4zMiAtMC41NiAxMS40IDAgMTcgYyAwLjc3IDcuNjggMS40OCAxNi4yNCA0IDIzIGMgMi41MSA2Ljc1IDcuMzUgMTQuMzIgMTIgMjAgYyAzLjk2IDQuODQgOS42NyAxMC45MSAxNSAxMyBjIDguNDMgMy4zIDIxLjkyIDYuNDggMzEgNSBjIDE1LjEgLTIuNDUgMzUuMTIgLTEwLjI5IDQ5IC0xOCBjIDguNDYgLTQuNyAxNS44NiAtMTQuMDkgMjMgLTIyIGMgOC4zIC05LjIgMTUuNDYgLTE5LjA0IDIzIC0yOSBjIDEuOTIgLTIuNTQgNC4xOSAtOC4xMiA1IC04IGMgMC43OSAwLjExIDEuOTMgNi4wMyAyIDkgYyAwLjI1IDEwLjY0IC0xLjY5IDI0LjQ3IC0xIDMzIGMgMC4xMiAxLjQ2IDIuNzIgNC4xMiA0IDQgYyA0LjI4IC0wLjM5IDEzLjA5IC0yLjcxIDE4IC02IGMgMTcuMTIgLTExLjUgNDUuMDUgLTM2LjE1IDUyIC00MSBjIDAuNDMgLTAuMyAxLjE1IDIuNzYgMSA0IGMgLTEuMDcgOC41NSAtNS42NSAyMy4yOCAtNSAyOCBjIDAuMjEgMS41IDcuMjggMi40NiA5IDEgYyAxMy44MiAtMTEuNzUgNDcuOTcgLTQ4LjcyIDUxIC01MiBsIC00IDEiLz48L3N2Zz4=\" />","field_23_raw":{"svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"365\" height=\"99\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 1 32 c 0.09 0.03 3.35 1.84 5 2 c 4.9 0.47 10.77 0.57 16 0 c 6.99 -0.76 14.47 -2.02 21 -4 c 4.1 -1.24 8.2 -3.66 12 -6 c 4.87 -3 11.63 -9.41 14 -10 c 0.87 -0.22 1.83 4.02 2 6 c 0.46 5.32 -0.56 11.4 0 17 c 0.77 7.68 1.48 16.24 4 23 c 2.51 6.75 7.35 14.32 12 20 c 3.96 4.84 9.67 10.91 15 13 c 8.43 3.3 21.92 6.48 31 5 c 15.1 -2.45 35.12 -10.29 49 -18 c 8.46 -4.7 15.86 -14.09 23 -22 c 8.3 -9.2 15.46 -19.04 23 -29 c 1.92 -2.54 4.19 -8.12 5 -8 c 0.79 0.11 1.93 6.03 2 9 c 0.25 10.64 -1.69 24.47 -1 33 c 0.12 1.46 2.72 4.12 4 4 c 4.28 -0.39 13.09 -2.71 18 -6 c 17.12 -11.5 45.05 -36.15 52 -41 c 0.43 -0.3 1.15 2.76 1 4 c -1.07 8.55 -5.65 23.28 -5 28 c 0.21 1.5 7.28 2.46 9 1 c 13.82 -11.75 47.97 -48.72 51 -52 l -4 1\"/></svg>","base30":"2A5glc86204cf1v1Nnf852Z100Y4ije9731Z221Y9ffa83Z4_1X20Z4655Y6hnkd5Zimja8Y9e9a4Z6fb852Y4b981Zgfa83Y1"},"field_24":"<a href=\"https://google.com\">https://google.com</a>","field_24_raw":{"url":"https://google.com"},"field_25":"0.00","field_25_raw":0,"field_9":"He two three (four)","field_9_raw":"He two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"<img src=\"pizza.com\" />","field_50_raw":"pizza.com","field_44":"Lexington, Texas 78947","field_44_raw":{"latitude":30.4042,"longitude":-97.20303,"city":"Lexington","state":"Texas","country":"United States","zip":"78947"},"field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":20,"field_129_raw":20},{"id":"5d7b026e58b1e6001064b4f0","field_11":3,"field_11_raw":3,"field_125":"6","field_125_raw":"6","field_6":"Mushrooms","field_6_raw":"Mushrooms","field_7":"boring short text","field_7_raw":"boring short text","field_8":"<p><a href=\"http://test.com\">test</a></p>","field_8_raw":"<p><a href=\"http://test.com\">test</a></p>","field_10":2555,"field_10_raw":2555,"field_12":"09/12/2019","field_12_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568246400000,"iso_timestamp":"2019-09-12T00:00:00.000Z","timestamp":"09/12/2019 12:00 am","time":720},"field_13":"09/12/2019 22:43","field_13_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1568328180000,"iso_timestamp":"2019-09-12T22:43:00.000Z","timestamp":"09/12/2019 10:43 pm","time":1363},"field_14":"10:43pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1325457780000,"iso_timestamp":"2012-01-01T22:43:00.000Z","timestamp":"01/01/2012 10:43 pm","time":1363},"field_15":"09/12/2019 10:43pm","field_15_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1568328180000,"iso_timestamp":"2019-09-12T22:43:00.000Z","timestamp":"09/12/2019 10:43 pm","time":1363},"field_16":"<span>01/05/20</span>&nbsp;5:07pm to 6:07pm = 1:00 hours","field_16_raw":{"times":[{"from":{"date":"01/05/2020","date_formatted":"01/05/2020","hours":"05","minutes":"07","am_pm":"PM","unix_timestamp":1578244020000,"iso_timestamp":"2020-01-05T17:07:00.000Z","timestamp":"01/05/2020 05:07 pm","time":1027},"to":{"date":"01/05/2020","date_formatted":"01/05/2020","hours":"06","minutes":"07","am_pm":"PM","unix_timestamp":1578247620000,"iso_timestamp":"2020-01-05T18:07:00.000Z","timestamp":"01/05/2020 06:07 pm","time":1087}}],"total_time":3600000},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5e126c4559ea6b00161acc32\" data-file-name=\"inventory_items_finance.json\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5e126c4559ea6b00161acc32/inventory_items_finance.json\">inventory_items_finance.json</a>","field_17_raw":{"id":"5e126c4559ea6b00161acc32","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"inventory_items_finance.json","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5e126c4559ea6b00161acc32/inventory_items_finance.json","thumb_url":"","size":776365,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/thumb/thumbnail_img_4826.jpg\" />","field_18_raw":{"id":"5e126c53ba5fb40017853a8a","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"thumbnail_img_4826.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/original/thumbnail_img_4826.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/thumb/thumbnail_img_4826.jpg","size":210668,"field_key":"field_18"},"field_19":"Nobody, Stu","field_19_raw":{"first":"Stu","last":"Nobody"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"Willow St<br />Robert Martinez<br />Austin, tx 78702","field_21_raw":{"street":"Willow St","street2":"Robert Martinez","city":"Austin","state":"tx","zip":"78702"},"field_22":"(333) 999-3333","field_22_raw":{"formatted":"(333) 999-3333","full":"3339993333","number":"9993333","area":"333"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzM0IiBoZWlnaHQ9Ijg2Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMSAzIGMgMC4xOCAwLjAyIDYuNTkgMC45OCAxMCAxIGMgNjAuMzIgMC4zMiAxMjQuOSAwLjg3IDE3OCAwIGMgMiAtMC4wMyA0Ljg0IC0zLjE1IDYgLTMgYyAwLjc4IDAuMSAyIDIuNjkgMiA0IGMgMCAxMi42MiAtMS41OSAyOC4xNiAtMiA0MyBjIC0wLjI4IDEwIC00Ljk4IDI3LjA2IDAgMjkgYyAxNi4zOCA2LjM4IDY4LjMyIDExLjI5IDk1IDggYyAxMy45MiAtMS43MSA0MyAtMjUgNDMgLTI1Ii8+PC9zdmc+\" />","field_23_raw":{"svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"334\" height=\"86\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 1 3 c 0.18 0.02 6.59 0.98 10 1 c 60.32 0.32 124.9 0.87 178 0 c 2 -0.03 4.84 -3.15 6 -3 c 0.78 0.1 2 2.69 2 4 c 0 12.62 -1.59 28.16 -2 43 c -0.28 10 -4.98 27.06 0 29 c 16.38 6.38 68.32 11.29 95 8 c 13.92 -1.71 43 -25 43 -25\"/></svg>","base30":"1Jam1xq1xrka762Z110Y3zhc644_1C100000000Z3Y4ipt8Za7332"},"field_24":"","field_25":"","field_9":"bo two three (four)","field_9_raw":"bo two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"09/13/2019 2:43am","field_37_raw":{"date":"09/13/2019","date_formatted":"09/13/2019","hours":"02","minutes":"43","am_pm":"AM","unix_timestamp":1568342580000,"iso_timestamp":"2019-09-13T02:43:00.000Z","timestamp":"09/13/2019 02:43 am","time":163},"field_38":"Yes","field_38_raw":true,"field_50":"<img src=\"nothing\" />","field_50_raw":"nothing","field_44":"","field_76":"September pizza Thursday ","field_76_raw":"September pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":30,"field_129_raw":30},{"id":"5f3b1e9037b59000158c48e6","field_11":1217,"field_11_raw":1217,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/17/2020 19:19","field_13_raw":{"date":"08/17/2020","date_formatted":"08/17/2020","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1597691940000,"iso_timestamp":"2020-08-17T19:19:00.000Z","timestamp":"08/17/2020 07:19 pm","time":1159},"field_14":"7:19pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1325445540000,"iso_timestamp":"2012-01-01T19:19:00.000Z","timestamp":"01/01/2012 07:19 pm","time":1159},"field_15":"08/17/2020 7:19pm","field_15_raw":{"date":"08/17/2020","date_formatted":"08/17/2020","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1597691940000,"iso_timestamp":"2020-08-17T19:19:00.000Z","timestamp":"08/17/2020 07:19 pm","time":1159},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":12170,"field_129_raw":12170},{"id":"5f3e05757972ef0015648984","field_11":1290,"field_11_raw":1290,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":12900,"field_129_raw":12900},{"id":"5f3e058d2abbbf001607c935","field_11":1296,"field_11_raw":1296,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f3e0591a33fe40015962d52","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":12960,"field_129_raw":12960},{"id":"5f3e076ae946bd00157429e8","field_11":1344,"field_11_raw":1344,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5f3e076ace60090015e1424e\" data-file-name=\"plaid.jpg\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5f3e076ace60090015e1424e/plaid.jpg\">plaid.jpg</a>","field_17_raw":{"id":"5f3e076ace60090015e1424e","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"plaid.jpg","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5f3e076ace60090015e1424e/plaid.jpg","thumb_url":"","size":121761,"field_key":"field_17"},"field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":13440,"field_129_raw":13440},{"id":"5f430decf50123001569bf7e","field_11":1475,"field_11_raw":1475,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/23/2020 19:46","field_13_raw":{"date":"08/23/2020","date_formatted":"08/23/2020","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1598211960000,"iso_timestamp":"2020-08-23T19:46:00.000Z","timestamp":"08/23/2020 07:46 pm","time":1186},"field_14":"7:46pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1325447160000,"iso_timestamp":"2012-01-01T19:46:00.000Z","timestamp":"01/01/2012 07:46 pm","time":1186},"field_15":"08/23/2020 7:46pm","field_15_raw":{"date":"08/23/2020","date_formatted":"08/23/2020","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1598211960000,"iso_timestamp":"2020-08-23T19:46:00.000Z","timestamp":"08/23/2020 07:46 pm","time":1186},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Sunday ","field_76_raw":"August pizza Sunday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":14750,"field_129_raw":14750},{"id":"5f434ea8598991001998ad25","field_11":1528,"field_11_raw":1528,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15280,"field_129_raw":15280},{"id":"5f435024f5012300156aad1a","field_11":1544,"field_11_raw":1544,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f435022f5012300156aad14","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15440,"field_129_raw":15440},{"id":"5f435026ba7b770019f97e91","field_11":1545,"field_11_raw":1545,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f43502a16c77200172503ae","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15450,"field_129_raw":15450},{"id":"5f43506ca2f3980015c2300e","field_11":1573,"field_11_raw":1573,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15730,"field_129_raw":15730},{"id":"5f4350b36d0ec100166c1680","field_11":1584,"field_11_raw":1584,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f4350b146dc4f00158d655f","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15840,"field_129_raw":15840},{"id":"5f4351174409a70015386b8b","field_11":1595,"field_11_raw":1595,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f4351164409a70015386b89","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":15950,"field_129_raw":15950},{"id":"5f4f8eb1516e17001534f2b4","field_11":1651,"field_11_raw":1651,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:23","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1599031380000,"iso_timestamp":"2020-09-02T07:23:00.000Z","timestamp":"09/02/2020 07:23 am","time":443},"field_14":"7:23am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1325402580000,"iso_timestamp":"2012-01-01T07:23:00.000Z","timestamp":"01/01/2012 07:23 am","time":443},"field_15":"09/02/2020 7:23am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1599031380000,"iso_timestamp":"2020-09-02T07:23:00.000Z","timestamp":"09/02/2020 07:23 am","time":443},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":16510,"field_129_raw":16510},{"id":"5f4f90c353d8a700156f8b00","field_11":1685,"field_11_raw":1685,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:32","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1599031920000,"iso_timestamp":"2020-09-02T07:32:00.000Z","timestamp":"09/02/2020 07:32 am","time":452},"field_14":"7:32am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1325403120000,"iso_timestamp":"2012-01-01T07:32:00.000Z","timestamp":"01/01/2012 07:32 am","time":452},"field_15":"09/02/2020 7:32am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1599031920000,"iso_timestamp":"2020-09-02T07:32:00.000Z","timestamp":"09/02/2020 07:32 am","time":452},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f4f90c253d8a700156f8af9","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":16850,"field_129_raw":16850},{"id":"5f4f911ad939540015e5debd","field_11":1698,"field_11_raw":1698,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:33","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1599031980000,"iso_timestamp":"2020-09-02T07:33:00.000Z","timestamp":"09/02/2020 07:33 am","time":453},"field_14":"7:33am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1325403180000,"iso_timestamp":"2012-01-01T07:33:00.000Z","timestamp":"01/01/2012 07:33 am","time":453},"field_15":"09/02/2020 7:33am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1599031980000,"iso_timestamp":"2020-09-02T07:33:00.000Z","timestamp":"09/02/2020 07:33 am","time":453},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f4f9119d939540015e5debb","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":16980,"field_129_raw":16980},{"id":"5f4f9231f50885001786f6d2","field_11":1712,"field_11_raw":1712,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:38","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1599032280000,"iso_timestamp":"2020-09-02T07:38:00.000Z","timestamp":"09/02/2020 07:38 am","time":458},"field_14":"7:38am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1325403480000,"iso_timestamp":"2012-01-01T07:38:00.000Z","timestamp":"01/01/2012 07:38 am","time":458},"field_15":"09/02/2020 7:38am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1599032280000,"iso_timestamp":"2020-09-02T07:38:00.000Z","timestamp":"09/02/2020 07:38 am","time":458},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":17120,"field_129_raw":17120},{"id":"5f4f9722d939540015e614a6","field_11":1735,"field_11_raw":1735,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:59","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1599033540000,"iso_timestamp":"2020-09-02T07:59:00.000Z","timestamp":"09/02/2020 07:59 am","time":479},"field_14":"7:59am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1325404740000,"iso_timestamp":"2012-01-01T07:59:00.000Z","timestamp":"01/01/2012 07:59 am","time":479},"field_15":"09/02/2020 7:59am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1599033540000,"iso_timestamp":"2020-09-02T07:59:00.000Z","timestamp":"09/02/2020 07:59 am","time":479},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":17350,"field_129_raw":17350},{"id":"5f4f986b59255d00152aa402","field_11":1748,"field_11_raw":1748,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 08:04","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1599033840000,"iso_timestamp":"2020-09-02T08:04:00.000Z","timestamp":"09/02/2020 08:04 am","time":484},"field_14":"8:04am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1325405040000,"iso_timestamp":"2012-01-01T08:04:00.000Z","timestamp":"01/01/2012 08:04 am","time":484},"field_15":"09/02/2020 8:04am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1599033840000,"iso_timestamp":"2020-09-02T08:04:00.000Z","timestamp":"09/02/2020 08:04 am","time":484},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/thumb/plaid.jpg\" />","field_18_raw":{"id":"5f4f986a0824970015e362da","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":17480,"field_129_raw":17480},{"id":"5fb59def08751b001cfe1cb5","field_11":1792,"field_11_raw":1792,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"11/18/2020 16:19","field_13_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1605716340000,"iso_timestamp":"2020-11-18T16:19:00.000Z","timestamp":"11/18/2020 04:19 pm","time":979},"field_14":"4:19pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1325434740000,"iso_timestamp":"2012-01-01T16:19:00.000Z","timestamp":"01/01/2012 04:19 pm","time":979},"field_15":"11/18/2020 4:19pm","field_15_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1605716340000,"iso_timestamp":"2020-11-18T16:19:00.000Z","timestamp":"11/18/2020 04:19 pm","time":979},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"November pizza Wednesday ","field_76_raw":"November pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":17920,"field_129_raw":17920},{"id":"5fb59e1da2dae5001ff4147b","field_11":1802,"field_11_raw":1802,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"11/18/2020 16:20","field_13_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1605716400000,"iso_timestamp":"2020-11-18T16:20:00.000Z","timestamp":"11/18/2020 04:20 pm","time":980},"field_14":"4:20pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1325434800000,"iso_timestamp":"2012-01-01T16:20:00.000Z","timestamp":"01/01/2012 04:20 pm","time":980},"field_15":"11/18/2020 4:20pm","field_15_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1605716400000,"iso_timestamp":"2020-11-18T16:20:00.000Z","timestamp":"11/18/2020 04:20 pm","time":980},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"November pizza Wednesday ","field_76_raw":"November pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":18020,"field_129_raw":18020},{"id":"6010bf647f630d001c9717e4","field_11":1909,"field_11_raw":1909,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"01/26/2021 19:18","field_13_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1611688680000,"iso_timestamp":"2021-01-26T19:18:00.000Z","timestamp":"01/26/2021 07:18 pm","time":1158},"field_14":"7:18pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1325445480000,"iso_timestamp":"2012-01-01T19:18:00.000Z","timestamp":"01/01/2012 07:18 pm","time":1158},"field_15":"01/26/2021 7:18pm","field_15_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1611688680000,"iso_timestamp":"2021-01-26T19:18:00.000Z","timestamp":"01/26/2021 07:18 pm","time":1158},"field_16":"","field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"6010bf71767cc0001bd10a0c\" data-file-name=\"plaid.jpg\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010bf71767cc0001bd10a0c/plaid.jpg\">plaid.jpg</a>","field_17_raw":{"id":"6010bf71767cc0001bd10a0c","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"plaid.jpg","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010bf71767cc0001bd10a0c/plaid.jpg","thumb_url":"","size":121761,"field_key":"field_17"},"field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"No","field_29_raw":false,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"January pizza Tuesday ","field_76_raw":"January pizza Tuesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":19090,"field_129_raw":19090}]} \ No newline at end of file +{"records":[{"id":"5d7964422d7159001659b27a","field_11":1,"field_11_raw":1,"field_125":"1","field_125_raw":"1","field_6":"Extra Cheese","field_6_raw":"Extra Cheese","field_7":"hello","field_7_raw":"hello","field_8":"<p><strong>bold rich text</strong><span></span></p><h1>heading 1</h1><table><tbody><tr><td>tablerow</td><td>1</td><td>1</td></tr><tr><td>tablerow</td><td>23</td><td>25</td></tr></tbody></table>","field_8_raw":"<p><strong>bold rich text</strong><span></span></p><h1>heading 1</h1><table><tbody><tr><td>tablerow</td><td>1</td><td>1</td></tr><tr><td>tablerow</td><td>23</td><td>25</td></tr></tbody></table>","field_10":100,"field_10_raw":100,"field_12":"09/11/2019","field_12_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568160000000,"iso_timestamp":"2019-09-11T00:00:00.000Z","timestamp":"09/11/2019 12:00 am","time":720},"field_13":"07/03/2018 10:26","field_13_raw":{"date":"07/03/2018","date_formatted":"07/03/2018","hours":"10","minutes":"26","am_pm":"AM","unix_timestamp":1530613560000,"iso_timestamp":"2018-07-03T10:26:00.000Z","timestamp":"07/03/2018 10:26 am","time":626},"field_14":"4:14pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"14","am_pm":"PM","unix_timestamp":1325434440000,"iso_timestamp":"2012-01-01T16:14:00.000Z","timestamp":"01/01/2012 04:14 pm","time":974},"field_15":"09/11/2019 4:14pm to 5:14pm","field_15_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"14","am_pm":"PM","unix_timestamp":1568218440000,"iso_timestamp":"2019-09-11T16:14:00.000Z","timestamp":"09/11/2019 04:14 pm","time":974,"to":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"05","minutes":"14","am_pm":"PM","unix_timestamp":1568222040000,"iso_timestamp":"2019-09-11T17:14:00.000Z","timestamp":"09/11/2019 05:14 pm","time":1034}},"field_16":"<span>09/11/19</span>&nbsp;4:14pm to 5:14pm = 1:00 hours","field_16_raw":{"total_time":3600000,"times":[{"to":{"time":1034,"timestamp":"09/11/2019 05:14 pm","iso_timestamp":"2019-09-11T17:14:00.000Z","unix_timestamp":1568222040000,"am_pm":"PM","minutes":"14","hours":"05","date_formatted":"09/11/2019","date":"09/11/2019"},"from":{"time":974,"timestamp":"09/11/2019 04:14 pm","iso_timestamp":"2019-09-11T16:14:00.000Z","unix_timestamp":1568218440000,"am_pm":"PM","minutes":"14","hours":"04","date_formatted":"09/11/2019","date":"09/11/2019"}}]},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5d7967132be2bb0010892ce7\" data-file-name=\"0.omfbylawsapproved1.pdf\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d7967132be2bb0010892ce7/0.omfbylawsapproved1.pdf\">0.omfbylawsapproved1.pdf</a>","field_17_raw":{"id":"5d7967132be2bb0010892ce7","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"0.omfbylawsapproved1.pdf","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d7967132be2bb0010892ce7/0.omfbylawsapproved1.pdf","thumb_url":"","size":305741,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/original/my_car_mazda_q.jpg\" />","field_18_raw":{"id":"5d7966ecc8d68e0010c0834a","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"my_car_mazda_q.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/original/my_car_mazda_q.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d7966ecc8d68e0010c0834a/thumb/my_car_mazda_q.jpg","size":1219841,"field_key":"field_18"},"field_19":"the Hut, Pizza Danger","field_19_raw":{"first":"Pizza","middle":"Danger","last":"the Hut"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"8700 Cameron Rd<br />Suite 1<br />Austin, TX 78754","field_21_raw":{"zip":"78754","state":"TX","city":"Austin","street2":"Suite 1","street":"8700 Cameron Rd"},"field_22":"(512) 974-3546","field_22_raw":{"area":"512","number":"9743546","full":"5129743546","formatted":"(512) 974-3546"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzg5IiBoZWlnaHQ9Ijg5Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMTAgNjUgYyAwIC0wLjQyIC0wLjkyIC0xNi40MiAwIC0yNCBjIDAuNjggLTUuNiAyLjkzIC0xMS40NyA1IC0xNyBjIDEuOTQgLTUuMTYgNC40MiAtMTAuMzEgNyAtMTUgYyAxIC0xLjgxIDIuNTQgLTMuNTQgNCAtNSBjIDEuMTQgLTEuMTQgMi42NyAtMi44MyA0IC0zIGMgMy4yMSAtMC40IDkuMjcgLTAuMDkgMTIgMSBjIDEuMzIgMC41MyAyLjU4IDMuMjUgMyA1IGMgMS43NiA3LjI5IDMuMTEgMTUuOTggNCAyNCBjIDAuNDQgMy45NSAwLjcxIDguMzMgMCAxMiBjIC0wLjg4IDQuNTUgLTIuNjkgMTAgLTUgMTQgYyAtMi40MyA0LjIxIC02LjQgOC4yMiAtMTAgMTIgYyAtMy4xIDMuMjUgLTYuNDcgNi41MyAtMTAgOSBjIC0yLjkzIDIuMDUgLTYuNTggMy44MSAtMTAgNSBjIC00LjA4IDEuNDIgLTEzLjIgMy4xMSAtMTMgMyBjIDAuMzkgLTAuMjEgMTYuMiAtNS40MyAyNCAtOSBjIDguMyAtMy44MSAxNS45OSAtOC4zMyAyNCAtMTMgYyA0LjIzIC0yLjQ3IDguMTggLTUuMDMgMTIgLTggYyA1LjI2IC00LjA5IDEwLjMzIC04LjMzIDE1IC0xMyBjIDQuMDEgLTQuMDEgNi45NyAtMTEuMjQgMTEgLTEzIGMgNC45OCAtMi4xOCAxNy4wMyAtMS43MiAyMSAtMSBjIDAuOTYgMC4xNyAxLjczIDMuOTkgMSA1IGMgLTMuOTIgNS40NSAtMTcuNTUgMTcuMSAtMTkgMjAgYyAtMC40MyAwLjg3IDUuMzYgMS42OSA4IDIgYyAyLjg4IDAuMzQgNi4yMSAwLjYyIDkgMCBjIDguNzQgLTEuOTQgMjMuNzggLTcuNSAyNyAtOCBjIDAuNDcgLTAuMDcgLTAuMzMgMi45MiAtMSA0IGMgLTMuMzggNS40NiAtMTAuNDcgMTMuNzYgLTEyIDE3IGMgLTAuMjcgMC41NiAyLjE0IDIuMTggMyAyIGMgNC4wOSAtMC44NiAxMC43OCAtMy42NCAxNiAtNiBjIDUuMiAtMi4zNSAxMy44NSAtNy44MSAxNSAtOCBjIDAuNDUgLTAuMDggLTEuNzcgNC4yMiAtMyA2IGMgLTEuNjkgMi40NSAtNi4xMyA3LjEgLTYgNyBjIDAuNTggLTAuNDcgMzEuMTkgLTI3LjQ0IDMyIC0yOCBjIDAuMjkgLTAuMiAtNi43MiA4LjEyIC05IDEyIGMgLTAuNzggMS4zMiAtMC40NSAzLjU0IC0xIDUgYyAtMC4zOSAxLjAzIC0yIDIuMjEgLTIgMyBjIDAgMC43OSAxLjM1IDMuMTIgMiAzIGMgMS44NiAtMC4zNCA2LjIzIC00LjMxIDkgLTUgYyAxLjkgLTAuNDggNC42NCAwLjkyIDcgMSBjIDguMDIgMC4yNiAxNi4yMyAwLjYzIDI0IDAgYyA0LjMyIC0wLjM1IDguODYgLTEuNzggMTMgLTMgYyAxLjM5IC0wLjQxIDQgLTEuNTQgNCAtMiBsIC00IC0yIi8+PHBhdGggc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZT0icmdiKDg1LCA4NCwgODkpIiBmaWxsPSJub25lIiBkPSJNIDIxNCAxNCBsIDAgNDciLz48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMTk2IDQxIGMgMC45NiAwIDQ4Ljk5IDAuMzQgNTUgMCBjIDAuMzkgLTAuMDIgLTEuMTggLTIuMTggLTIgLTMgYyAtMy4zOSAtMy4zOSAtOC4yIC02LjQ2IC0xMSAtMTAgYyAtMS44NSAtMi4zNSAtMy45NSAtOS40NiAtNCAtOSBjIC0wLjIzIDIuMjcgLTQuODkgMzguNDUgMCA0OSBjIDMuNzcgOC4xMiAyMy42NyAxNS45NSAzMiAyMCBjIDEuMTkgMC41OCAzLjM3IC0xLjcgNSAtMiBjIDEuODIgLTAuMzMgNC4xOCAwLjM5IDYgMCBjIDIuNTkgLTAuNTYgNi4zOSAtMS4yOSA4IC0zIGMgMy4zMSAtMy41IDYuMzQgLTEzIDkgLTE1IGMgMS4xNiAtMC44NyA1LjI2IDMuMTUgNyAzIGMgMS40NyAtMC4xMiA0LjEyIC0yLjUzIDUgLTQgbCAxIC02Ii8+PHBhdGggc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZT0icmdiKDg1LCA4NCwgODkpIiBmaWxsPSJub25lIiBkPSJNIDMyNSAyMSBjIDAuMDIgMC4xIDAuOTUgMy45OCAxIDYgYyAwLjI4IDExLjYgLTAuMzkgMzEuOTYgMCAzNSBjIDAuMDYgMC40OSAyLjU2IC0yLjg4IDQgLTQgYyAxLjQ5IC0xLjE2IDMuMzcgLTIuOTQgNSAtMyBjIDYuNzUgLTAuMjMgMTcuNTYgMC44MSAyNCAyIGMgMS4xMyAwLjIxIDEuOTEgMi43OSAzIDMgYyAzLjM1IDAuNjMgOS40MSAxLjEgMTMgMCBjIDQuMjEgLTEuMyAxMyAtOCAxMyAtOCIvPjwvc3ZnPg==\" />","field_23_raw":{"base30":"1W0023344484340Z5aaa67Y68acccf4527681Z5644Y899855Z14332Y36aa5Z333Y36d64Z5412Y25477h584Z4_2QZae7a87530Y15ocec9521Z234678d553100Y5564520Z3212Y464432Z2453Y643Z26c44Y66533Z32Y100Z1222_8Q00000_1vb9c96_8y66hc86Z26522000Y1w568432751_1W000000Z35554YfcmkZ203744Y3Z46_cH10000458556376643_1C66bd5Z43Y1010300Z332","svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"389\" height=\"89\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 10 65 c 0 -0.42 -0.92 -16.42 0 -24 c 0.68 -5.6 2.93 -11.47 5 -17 c 1.94 -5.16 4.42 -10.31 7 -15 c 1 -1.81 2.54 -3.54 4 -5 c 1.14 -1.14 2.67 -2.83 4 -3 c 3.21 -0.4 9.27 -0.09 12 1 c 1.32 0.53 2.58 3.25 3 5 c 1.76 7.29 3.11 15.98 4 24 c 0.44 3.95 0.71 8.33 0 12 c -0.88 4.55 -2.69 10 -5 14 c -2.43 4.21 -6.4 8.22 -10 12 c -3.1 3.25 -6.47 6.53 -10 9 c -2.93 2.05 -6.58 3.81 -10 5 c -4.08 1.42 -13.2 3.11 -13 3 c 0.39 -0.21 16.2 -5.43 24 -9 c 8.3 -3.81 15.99 -8.33 24 -13 c 4.23 -2.47 8.18 -5.03 12 -8 c 5.26 -4.09 10.33 -8.33 15 -13 c 4.01 -4.01 6.97 -11.24 11 -13 c 4.98 -2.18 17.03 -1.72 21 -1 c 0.96 0.17 1.73 3.99 1 5 c -3.92 5.45 -17.55 17.1 -19 20 c -0.43 0.87 5.36 1.69 8 2 c 2.88 0.34 6.21 0.62 9 0 c 8.74 -1.94 23.78 -7.5 27 -8 c 0.47 -0.07 -0.33 2.92 -1 4 c -3.38 5.46 -10.47 13.76 -12 17 c -0.27 0.56 2.14 2.18 3 2 c 4.09 -0.86 10.78 -3.64 16 -6 c 5.2 -2.35 13.85 -7.81 15 -8 c 0.45 -0.08 -1.77 4.22 -3 6 c -1.69 2.45 -6.13 7.1 -6 7 c 0.58 -0.47 31.19 -27.44 32 -28 c 0.29 -0.2 -6.72 8.12 -9 12 c -0.78 1.32 -0.45 3.54 -1 5 c -0.39 1.03 -2 2.21 -2 3 c 0 0.79 1.35 3.12 2 3 c 1.86 -0.34 6.23 -4.31 9 -5 c 1.9 -0.48 4.64 0.92 7 1 c 8.02 0.26 16.23 0.63 24 0 c 4.32 -0.35 8.86 -1.78 13 -3 c 1.39 -0.41 4 -1.54 4 -2 l -4 -2\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 214 14 l 0 47\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 196 41 c 0.96 0 48.99 0.34 55 0 c 0.39 -0.02 -1.18 -2.18 -2 -3 c -3.39 -3.39 -8.2 -6.46 -11 -10 c -1.85 -2.35 -3.95 -9.46 -4 -9 c -0.23 2.27 -4.89 38.45 0 49 c 3.77 8.12 23.67 15.95 32 20 c 1.19 0.58 3.37 -1.7 5 -2 c 1.82 -0.33 4.18 0.39 6 0 c 2.59 -0.56 6.39 -1.29 8 -3 c 3.31 -3.5 6.34 -13 9 -15 c 1.16 -0.87 5.26 3.15 7 3 c 1.47 -0.12 4.12 -2.53 5 -4 l 1 -6\"/><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 325 21 c 0.02 0.1 0.95 3.98 1 6 c 0.28 11.6 -0.39 31.96 0 35 c 0.06 0.49 2.56 -2.88 4 -4 c 1.49 -1.16 3.37 -2.94 5 -3 c 6.75 -0.23 17.56 0.81 24 2 c 1.13 0.21 1.91 2.79 3 3 c 3.35 0.63 9.41 1.1 13 0 c 4.21 -1.3 13 -8 13 -8\"/></svg>"},"field_24":"<a href=\"https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9\">https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9</a>","field_24_raw":{"url":"https://data.austintexas.gov/Transportation-and-Mobility/Camera-Traffic-Counts-UT-CTR-TEST/sh59-i6y9"},"field_25":"0.00","field_25_raw":0,"field_9":"he two three (four)","field_9_raw":"he two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"$100.43","field_30_raw":"100.43","field_37":"09/13/2019 2:43am","field_37_raw":{"date":"09/13/2019","date_formatted":"09/13/2019","hours":"02","minutes":"43","am_pm":"AM","unix_timestamp":1568342580000,"iso_timestamp":"2019-09-13T02:43:00.000Z","timestamp":"09/13/2019 02:43 am","time":163},"field_38":"No","field_38_raw":false,"field_50":"<img src=\"google.com\" />","field_50_raw":"google.com","field_44":"Bauchi ","field_44_raw":{"latitude":10,"longitude":10,"state":"Bauchi","country":"Nigeria"},"field_76":"July pizza Tuesday ","field_76_raw":"July pizza Tuesday ","field_126":"123 Calle Uno<br />Suite 22<br />Mexico City, State of Mexico 102392A","field_126_raw":{"street":"123 Calle Uno","street2":"Suite 22","city":"Mexico City","state":"State of Mexico","zip":"102392A"},"field_127":"123 Fake St<br />APT C<br />London, London ABC123<br />United Kingdom","field_127_raw":{"street":"123 Fake St","street2":"APT C","city":"London","state":"London","zip":"ABC123","country":"United Kingdom"},"field_128":"<span class=\"5ea46ad2b6ce4b0015000ae8\">Johnny C</span>","field_128_raw":[{"id":"5ea46ad2b6ce4b0015000ae8","identifier":"Johnny C"}],"field_129":1,"field_129_raw":1.33333333},{"id":"5d7968c8092e7f00106c6399","field_11":2,"field_11_raw":2,"field_125":"3","field_125_raw":"3","field_6":"Jalapeños","field_6_raw":"Jalapeños","field_7":"Hello SHort Text","field_7_raw":"Hello SHort Text","field_8":"<p>boring rich text</p>","field_8_raw":"<p>boring rich text</p>","field_10":0,"field_10_raw":0,"field_12":"09/11/2019","field_12_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568160000000,"iso_timestamp":"2019-09-11T00:00:00.000Z","timestamp":"09/11/2019 12:00 am","time":720},"field_13":"09/11/2019 16:35","field_13_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1568219700000,"iso_timestamp":"2019-09-11T16:35:00.000Z","timestamp":"09/11/2019 04:35 pm","time":995},"field_14":"4:35pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1325435700000,"iso_timestamp":"2012-01-01T16:35:00.000Z","timestamp":"01/01/2012 04:35 pm","time":995},"field_15":"09/11/2019 4:35pm to 5:35pm","field_15_raw":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"04","minutes":"35","am_pm":"PM","unix_timestamp":1568219700000,"iso_timestamp":"2019-09-11T16:35:00.000Z","timestamp":"09/11/2019 04:35 pm","time":995,"to":{"date":"09/11/2019","date_formatted":"09/11/2019","hours":"05","minutes":"35","am_pm":"PM","unix_timestamp":1568223300000,"iso_timestamp":"2019-09-11T17:35:00.000Z","timestamp":"09/11/2019 05:35 pm","time":1055}},"field_16":"<span>09/11/19</span>&nbsp;4:35pm to 5:35pm = 1:00 hours","field_16_raw":{"total_time":3600000,"times":[{"to":{"time":1055,"timestamp":"09/11/2019 05:35 pm","iso_timestamp":"2019-09-11T17:35:00.000Z","unix_timestamp":1568223300000,"am_pm":"PM","minutes":"35","hours":"05","date_formatted":"09/11/2019","date":"09/11/2019"},"from":{"time":995,"timestamp":"09/11/2019 04:35 pm","iso_timestamp":"2019-09-11T16:35:00.000Z","unix_timestamp":1568219700000,"am_pm":"PM","minutes":"35","hours":"04","date_formatted":"09/11/2019","date":"09/11/2019"}}]},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5d796903335a510011275b67\" data-file-name=\"ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d796903335a510011275b67/ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf\">ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf</a>","field_17_raw":{"id":"5d796903335a510011275b67","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5d796903335a510011275b67/ibmdesignthinkingfieldguidewatsonbuildv3.5_ac.pdf","thumb_url":"","size":8619743,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/original/screenshot20190906at9.32.13am.png\" />","field_18_raw":{"id":"5d79691475f07d00103a3b0b","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"screenshot20190906at9.32.13am.png","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/original/screenshot20190906at9.32.13am.png","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5d79691475f07d00103a3b0b/thumb/screenshot20190906at9.32.13am.png","size":3220795,"field_key":"field_18"},"field_19":"Lognestnameeverprobableimnotsure, Sally","field_19_raw":{"first":"Sally","last":"Lognestnameeverprobableimnotsure"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"1600 Pennsylvania Ave<br />Washington, DC ","field_21_raw":{"street":"1600 Pennsylvania Ave","street2":"","city":"Washington","state":"DC","zip":""},"field_22":"(800) 234-4444","field_22_raw":{"formatted":"(800) 234-4444","full":"8002344444","number":"2344444","area":"800"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzY1IiBoZWlnaHQ9Ijk5Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMSAzMiBjIDAuMDkgMC4wMyAzLjM1IDEuODQgNSAyIGMgNC45IDAuNDcgMTAuNzcgMC41NyAxNiAwIGMgNi45OSAtMC43NiAxNC40NyAtMi4wMiAyMSAtNCBjIDQuMSAtMS4yNCA4LjIgLTMuNjYgMTIgLTYgYyA0Ljg3IC0zIDExLjYzIC05LjQxIDE0IC0xMCBjIDAuODcgLTAuMjIgMS44MyA0LjAyIDIgNiBjIDAuNDYgNS4zMiAtMC41NiAxMS40IDAgMTcgYyAwLjc3IDcuNjggMS40OCAxNi4yNCA0IDIzIGMgMi41MSA2Ljc1IDcuMzUgMTQuMzIgMTIgMjAgYyAzLjk2IDQuODQgOS42NyAxMC45MSAxNSAxMyBjIDguNDMgMy4zIDIxLjkyIDYuNDggMzEgNSBjIDE1LjEgLTIuNDUgMzUuMTIgLTEwLjI5IDQ5IC0xOCBjIDguNDYgLTQuNyAxNS44NiAtMTQuMDkgMjMgLTIyIGMgOC4zIC05LjIgMTUuNDYgLTE5LjA0IDIzIC0yOSBjIDEuOTIgLTIuNTQgNC4xOSAtOC4xMiA1IC04IGMgMC43OSAwLjExIDEuOTMgNi4wMyAyIDkgYyAwLjI1IDEwLjY0IC0xLjY5IDI0LjQ3IC0xIDMzIGMgMC4xMiAxLjQ2IDIuNzIgNC4xMiA0IDQgYyA0LjI4IC0wLjM5IDEzLjA5IC0yLjcxIDE4IC02IGMgMTcuMTIgLTExLjUgNDUuMDUgLTM2LjE1IDUyIC00MSBjIDAuNDMgLTAuMyAxLjE1IDIuNzYgMSA0IGMgLTEuMDcgOC41NSAtNS42NSAyMy4yOCAtNSAyOCBjIDAuMjEgMS41IDcuMjggMi40NiA5IDEgYyAxMy44MiAtMTEuNzUgNDcuOTcgLTQ4LjcyIDUxIC01MiBsIC00IDEiLz48L3N2Zz4=\" />","field_23_raw":{"svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"365\" height=\"99\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 1 32 c 0.09 0.03 3.35 1.84 5 2 c 4.9 0.47 10.77 0.57 16 0 c 6.99 -0.76 14.47 -2.02 21 -4 c 4.1 -1.24 8.2 -3.66 12 -6 c 4.87 -3 11.63 -9.41 14 -10 c 0.87 -0.22 1.83 4.02 2 6 c 0.46 5.32 -0.56 11.4 0 17 c 0.77 7.68 1.48 16.24 4 23 c 2.51 6.75 7.35 14.32 12 20 c 3.96 4.84 9.67 10.91 15 13 c 8.43 3.3 21.92 6.48 31 5 c 15.1 -2.45 35.12 -10.29 49 -18 c 8.46 -4.7 15.86 -14.09 23 -22 c 8.3 -9.2 15.46 -19.04 23 -29 c 1.92 -2.54 4.19 -8.12 5 -8 c 0.79 0.11 1.93 6.03 2 9 c 0.25 10.64 -1.69 24.47 -1 33 c 0.12 1.46 2.72 4.12 4 4 c 4.28 -0.39 13.09 -2.71 18 -6 c 17.12 -11.5 45.05 -36.15 52 -41 c 0.43 -0.3 1.15 2.76 1 4 c -1.07 8.55 -5.65 23.28 -5 28 c 0.21 1.5 7.28 2.46 9 1 c 13.82 -11.75 47.97 -48.72 51 -52 l -4 1\"/></svg>","base30":"2A5glc86204cf1v1Nnf852Z100Y4ije9731Z221Y9ffa83Z4_1X20Z4655Y6hnkd5Zimja8Y9e9a4Z6fb852Y4b981Zgfa83Y1"},"field_24":"<a href=\"https://google.com\">https://google.com</a>","field_24_raw":{"url":"https://google.com"},"field_25":"0.00","field_25_raw":0,"field_9":"He two three (four)","field_9_raw":"He two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"<img src=\"pizza.com\" />","field_50_raw":"pizza.com","field_44":"Lexington, Texas 78947","field_44_raw":{"latitude":30.4042,"longitude":-97.20303,"city":"Lexington","state":"Texas","country":"United States","zip":"78947"},"field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":3,"field_129_raw":2.66666666},{"id":"5d7b026e58b1e6001064b4f0","field_11":3,"field_11_raw":3,"field_125":"6","field_125_raw":"6","field_6":"Mushrooms","field_6_raw":"Mushrooms","field_7":"boring short text","field_7_raw":"boring short text","field_8":"<p><a href=\"http://test.com\">test</a></p>","field_8_raw":"<p><a href=\"http://test.com\">test</a></p>","field_10":2555,"field_10_raw":2555,"field_12":"09/12/2019","field_12_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1568246400000,"iso_timestamp":"2019-09-12T00:00:00.000Z","timestamp":"09/12/2019 12:00 am","time":720},"field_13":"09/12/2019 22:43","field_13_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1568328180000,"iso_timestamp":"2019-09-12T22:43:00.000Z","timestamp":"09/12/2019 10:43 pm","time":1363},"field_14":"10:43pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1325457780000,"iso_timestamp":"2012-01-01T22:43:00.000Z","timestamp":"01/01/2012 10:43 pm","time":1363},"field_15":"09/12/2019 10:43pm","field_15_raw":{"date":"09/12/2019","date_formatted":"09/12/2019","hours":"10","minutes":"43","am_pm":"PM","unix_timestamp":1568328180000,"iso_timestamp":"2019-09-12T22:43:00.000Z","timestamp":"09/12/2019 10:43 pm","time":1363},"field_16":"<span>01/05/20</span>&nbsp;5:07pm to 6:07pm = 1:00 hours","field_16_raw":{"times":[{"from":{"date":"01/05/2020","date_formatted":"01/05/2020","hours":"05","minutes":"07","am_pm":"PM","unix_timestamp":1578244020000,"iso_timestamp":"2020-01-05T17:07:00.000Z","timestamp":"01/05/2020 05:07 pm","time":1027},"to":{"date":"01/05/2020","date_formatted":"01/05/2020","hours":"06","minutes":"07","am_pm":"PM","unix_timestamp":1578247620000,"iso_timestamp":"2020-01-05T18:07:00.000Z","timestamp":"01/05/2020 06:07 pm","time":1087}}],"total_time":3600000},"field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5e126c4559ea6b00161acc32\" data-file-name=\"inventory_items_finance.json\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5e126c4559ea6b00161acc32/inventory_items_finance.json\">inventory_items_finance.json</a>","field_17_raw":{"id":"5e126c4559ea6b00161acc32","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"inventory_items_finance.json","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5e126c4559ea6b00161acc32/inventory_items_finance.json","thumb_url":"","size":776365,"field_key":"field_17"},"field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/original/thumbnail_img_4826.jpg\" />","field_18_raw":{"id":"5e126c53ba5fb40017853a8a","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"thumbnail_img_4826.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/original/thumbnail_img_4826.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5e126c53ba5fb40017853a8a/thumb/thumbnail_img_4826.jpg","size":210668,"field_key":"field_18"},"field_19":"Nobody, Stu","field_19_raw":{"first":"Stu","last":"Nobody"},"field_20":"<a href=\"mailto:[email protected]\">[email protected]</a>","field_20_raw":{"email":"[email protected]"},"field_21":"Willow St<br />Robert Martinez<br />Austin, tx 78702","field_21_raw":{"street":"Willow St","street2":"Robert Martinez","city":"Austin","state":"tx","zip":"78702"},"field_22":"(333) 999-3333","field_22_raw":{"formatted":"(333) 999-3333","full":"3339993333","number":"9993333","area":"333"},"field_23":"<img src=\"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMzM0IiBoZWlnaHQ9Ijg2Ij48cGF0aCBzdHJva2UtbGluZWpvaW49InJvdW5kIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSJyZ2IoODUsIDg0LCA4OSkiIGZpbGw9Im5vbmUiIGQ9Ik0gMSAzIGMgMC4xOCAwLjAyIDYuNTkgMC45OCAxMCAxIGMgNjAuMzIgMC4zMiAxMjQuOSAwLjg3IDE3OCAwIGMgMiAtMC4wMyA0Ljg0IC0zLjE1IDYgLTMgYyAwLjc4IDAuMSAyIDIuNjkgMiA0IGMgMCAxMi42MiAtMS41OSAyOC4xNiAtMiA0MyBjIC0wLjI4IDEwIC00Ljk4IDI3LjA2IDAgMjkgYyAxNi4zOCA2LjM4IDY4LjMyIDExLjI5IDk1IDggYyAxMy45MiAtMS43MSA0MyAtMjUgNDMgLTI1Ii8+PC9zdmc+\" />","field_23_raw":{"svg":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"334\" height=\"86\"><path stroke-linejoin=\"round\" stroke-linecap=\"round\" stroke-width=\"2\" stroke=\"rgb(85, 84, 89)\" fill=\"none\" d=\"M 1 3 c 0.18 0.02 6.59 0.98 10 1 c 60.32 0.32 124.9 0.87 178 0 c 2 -0.03 4.84 -3.15 6 -3 c 0.78 0.1 2 2.69 2 4 c 0 12.62 -1.59 28.16 -2 43 c -0.28 10 -4.98 27.06 0 29 c 16.38 6.38 68.32 11.29 95 8 c 13.92 -1.71 43 -25 43 -25\"/></svg>","base30":"1Jam1xq1xrka762Z110Y3zhc644_1C100000000Z3Y4ipt8Za7332"},"field_24":"","field_25":"","field_9":"bo two three (four)","field_9_raw":"bo two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"09/13/2019 2:43am","field_37_raw":{"date":"09/13/2019","date_formatted":"09/13/2019","hours":"02","minutes":"43","am_pm":"AM","unix_timestamp":1568342580000,"iso_timestamp":"2019-09-13T02:43:00.000Z","timestamp":"09/13/2019 02:43 am","time":163},"field_38":"Yes","field_38_raw":true,"field_50":"<img src=\"nothing\" />","field_50_raw":"nothing","field_44":"","field_76":"September pizza Thursday ","field_76_raw":"September pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":4,"field_129_raw":3.99999999},{"id":"5f3b1e9037b59000158c48e6","field_11":1217,"field_11_raw":1217,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/17/2020 19:19","field_13_raw":{"date":"08/17/2020","date_formatted":"08/17/2020","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1597691940000,"iso_timestamp":"2020-08-17T19:19:00.000Z","timestamp":"08/17/2020 07:19 pm","time":1159},"field_14":"7:19pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1325445540000,"iso_timestamp":"2012-01-01T19:19:00.000Z","timestamp":"01/01/2012 07:19 pm","time":1159},"field_15":"08/17/2020 7:19pm","field_15_raw":{"date":"08/17/2020","date_formatted":"08/17/2020","hours":"07","minutes":"19","am_pm":"PM","unix_timestamp":1597691940000,"iso_timestamp":"2020-08-17T19:19:00.000Z","timestamp":"08/17/2020 07:19 pm","time":1159},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":1623,"field_129_raw":1622.66666261},{"id":"5f3e05757972ef0015648984","field_11":1290,"field_11_raw":1290,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":1720,"field_129_raw":1719.9999957},{"id":"5f3e058d2abbbf001607c935","field_11":1296,"field_11_raw":1296,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/original/plaid.jpg\" />","field_18_raw":{"id":"5f3e0591a33fe40015962d52","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f3e0591a33fe40015962d52/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":1728,"field_129_raw":1727.99999568},{"id":"5f3e076ae946bd00157429e8","field_11":1344,"field_11_raw":1344,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/20/2020 00:00","field_13_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/20/2020 12:00am","field_15_raw":{"date":"08/20/2020","date_formatted":"08/20/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1597881600000,"iso_timestamp":"2020-08-20T00:00:00.000Z","timestamp":"08/20/2020 12:00 am","time":720},"field_16":"","field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"5f3e076ace60090015e1424e\" data-file-name=\"plaid.jpg\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5f3e076ace60090015e1424e/plaid.jpg\">plaid.jpg</a>","field_17_raw":{"id":"5f3e076ace60090015e1424e","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"plaid.jpg","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/5f3e076ace60090015e1424e/plaid.jpg","thumb_url":"","size":121761,"field_key":"field_17"},"field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Thursday ","field_76_raw":"August pizza Thursday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":1792,"field_129_raw":1791.99999552},{"id":"5f430decf50123001569bf7e","field_11":1475,"field_11_raw":1475,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/23/2020 19:46","field_13_raw":{"date":"08/23/2020","date_formatted":"08/23/2020","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1598211960000,"iso_timestamp":"2020-08-23T19:46:00.000Z","timestamp":"08/23/2020 07:46 pm","time":1186},"field_14":"7:46pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1325447160000,"iso_timestamp":"2012-01-01T19:46:00.000Z","timestamp":"01/01/2012 07:46 pm","time":1186},"field_15":"08/23/2020 7:46pm","field_15_raw":{"date":"08/23/2020","date_formatted":"08/23/2020","hours":"07","minutes":"46","am_pm":"PM","unix_timestamp":1598211960000,"iso_timestamp":"2020-08-23T19:46:00.000Z","timestamp":"08/23/2020 07:46 pm","time":1186},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Sunday ","field_76_raw":"August pizza Sunday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":1967,"field_129_raw":1966.66666175},{"id":"5f434ea8598991001998ad25","field_11":1528,"field_11_raw":1528,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2037,"field_129_raw":2037.33332824},{"id":"5f435024f5012300156aad1a","field_11":1544,"field_11_raw":1544,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/original/plaid.jpg\" />","field_18_raw":{"id":"5f435022f5012300156aad14","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f435022f5012300156aad14/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2059,"field_129_raw":2058.66666152},{"id":"5f435026ba7b770019f97e91","field_11":1545,"field_11_raw":1545,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/original/plaid.jpg\" />","field_18_raw":{"id":"5f43502a16c77200172503ae","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f43502a16c77200172503ae/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2060,"field_129_raw":2059.99999485},{"id":"5f43506ca2f3980015c2300e","field_11":1573,"field_11_raw":1573,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2097,"field_129_raw":2097.33332809},{"id":"5f4350b36d0ec100166c1680","field_11":1584,"field_11_raw":1584,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/original/plaid.jpg\" />","field_18_raw":{"id":"5f4350b146dc4f00158d655f","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4350b146dc4f00158d655f/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2112,"field_129_raw":2111.99999472},{"id":"5f4351174409a70015386b8b","field_11":1595,"field_11_raw":1595,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"08/24/2020 00:00","field_13_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_14":"12:00am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1325376000000,"iso_timestamp":"2012-01-01T00:00:00.000Z","timestamp":"01/01/2012 12:00 am","time":720},"field_15":"08/24/2020 12:00am","field_15_raw":{"date":"08/24/2020","date_formatted":"08/24/2020","hours":"12","minutes":"00","am_pm":"AM","unix_timestamp":1598227200000,"iso_timestamp":"2020-08-24T00:00:00.000Z","timestamp":"08/24/2020 12:00 am","time":720},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/original/plaid.jpg\" />","field_18_raw":{"id":"5f4351164409a70015386b89","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4351164409a70015386b89/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"August pizza Monday ","field_76_raw":"August pizza Monday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2127,"field_129_raw":2126.66666135},{"id":"5f4f8eb1516e17001534f2b4","field_11":1651,"field_11_raw":1651,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:23","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1599031380000,"iso_timestamp":"2020-09-02T07:23:00.000Z","timestamp":"09/02/2020 07:23 am","time":443},"field_14":"7:23am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1325402580000,"iso_timestamp":"2012-01-01T07:23:00.000Z","timestamp":"01/01/2012 07:23 am","time":443},"field_15":"09/02/2020 7:23am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"23","am_pm":"AM","unix_timestamp":1599031380000,"iso_timestamp":"2020-09-02T07:23:00.000Z","timestamp":"09/02/2020 07:23 am","time":443},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2201,"field_129_raw":2201.33332783},{"id":"5f4f90c353d8a700156f8b00","field_11":1685,"field_11_raw":1685,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:32","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1599031920000,"iso_timestamp":"2020-09-02T07:32:00.000Z","timestamp":"09/02/2020 07:32 am","time":452},"field_14":"7:32am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1325403120000,"iso_timestamp":"2012-01-01T07:32:00.000Z","timestamp":"01/01/2012 07:32 am","time":452},"field_15":"09/02/2020 7:32am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"32","am_pm":"AM","unix_timestamp":1599031920000,"iso_timestamp":"2020-09-02T07:32:00.000Z","timestamp":"09/02/2020 07:32 am","time":452},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/original/plaid.jpg\" />","field_18_raw":{"id":"5f4f90c253d8a700156f8af9","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f90c253d8a700156f8af9/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2247,"field_129_raw":2246.66666105},{"id":"5f4f911ad939540015e5debd","field_11":1698,"field_11_raw":1698,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:33","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1599031980000,"iso_timestamp":"2020-09-02T07:33:00.000Z","timestamp":"09/02/2020 07:33 am","time":453},"field_14":"7:33am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1325403180000,"iso_timestamp":"2012-01-01T07:33:00.000Z","timestamp":"01/01/2012 07:33 am","time":453},"field_15":"09/02/2020 7:33am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"33","am_pm":"AM","unix_timestamp":1599031980000,"iso_timestamp":"2020-09-02T07:33:00.000Z","timestamp":"09/02/2020 07:33 am","time":453},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/original/plaid.jpg\" />","field_18_raw":{"id":"5f4f9119d939540015e5debb","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f9119d939540015e5debb/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2264,"field_129_raw":2263.99999434},{"id":"5f4f9231f50885001786f6d2","field_11":1712,"field_11_raw":1712,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:38","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1599032280000,"iso_timestamp":"2020-09-02T07:38:00.000Z","timestamp":"09/02/2020 07:38 am","time":458},"field_14":"7:38am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1325403480000,"iso_timestamp":"2012-01-01T07:38:00.000Z","timestamp":"01/01/2012 07:38 am","time":458},"field_15":"09/02/2020 7:38am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"38","am_pm":"AM","unix_timestamp":1599032280000,"iso_timestamp":"2020-09-02T07:38:00.000Z","timestamp":"09/02/2020 07:38 am","time":458},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2283,"field_129_raw":2282.66666096},{"id":"5f4f9722d939540015e614a6","field_11":1735,"field_11_raw":1735,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 07:59","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1599033540000,"iso_timestamp":"2020-09-02T07:59:00.000Z","timestamp":"09/02/2020 07:59 am","time":479},"field_14":"7:59am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1325404740000,"iso_timestamp":"2012-01-01T07:59:00.000Z","timestamp":"01/01/2012 07:59 am","time":479},"field_15":"09/02/2020 7:59am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"07","minutes":"59","am_pm":"AM","unix_timestamp":1599033540000,"iso_timestamp":"2020-09-02T07:59:00.000Z","timestamp":"09/02/2020 07:59 am","time":479},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2313,"field_129_raw":2313.33332755},{"id":"5f4f986b59255d00152aa402","field_11":1748,"field_11_raw":1748,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"09/02/2020 08:04","field_13_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1599033840000,"iso_timestamp":"2020-09-02T08:04:00.000Z","timestamp":"09/02/2020 08:04 am","time":484},"field_14":"8:04am","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1325405040000,"iso_timestamp":"2012-01-01T08:04:00.000Z","timestamp":"01/01/2012 08:04 am","time":484},"field_15":"09/02/2020 8:04am","field_15_raw":{"date":"09/02/2020","date_formatted":"09/02/2020","hours":"08","minutes":"04","am_pm":"AM","unix_timestamp":1599033840000,"iso_timestamp":"2020-09-02T08:04:00.000Z","timestamp":"09/02/2020 08:04 am","time":484},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/original/plaid.jpg\" />","field_18_raw":{"id":"5f4f986a0824970015e362da","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/5f4f986a0824970015e362da/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"September pizza Wednesday ","field_76_raw":"September pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2331,"field_129_raw":2330.66666084},{"id":"5fb59def08751b001cfe1cb5","field_11":1792,"field_11_raw":1792,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"11/18/2020 16:19","field_13_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1605716340000,"iso_timestamp":"2020-11-18T16:19:00.000Z","timestamp":"11/18/2020 04:19 pm","time":979},"field_14":"4:19pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1325434740000,"iso_timestamp":"2012-01-01T16:19:00.000Z","timestamp":"01/01/2012 04:19 pm","time":979},"field_15":"11/18/2020 4:19pm","field_15_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"19","am_pm":"PM","unix_timestamp":1605716340000,"iso_timestamp":"2020-11-18T16:19:00.000Z","timestamp":"11/18/2020 04:19 pm","time":979},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"November pizza Wednesday ","field_76_raw":"November pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2389,"field_129_raw":2389.33332736},{"id":"5fb59e1da2dae5001ff4147b","field_11":1802,"field_11_raw":1802,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"11/18/2020 16:20","field_13_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1605716400000,"iso_timestamp":"2020-11-18T16:20:00.000Z","timestamp":"11/18/2020 04:20 pm","time":980},"field_14":"4:20pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1325434800000,"iso_timestamp":"2012-01-01T16:20:00.000Z","timestamp":"01/01/2012 04:20 pm","time":980},"field_15":"11/18/2020 4:20pm","field_15_raw":{"date":"11/18/2020","date_formatted":"11/18/2020","hours":"04","minutes":"20","am_pm":"PM","unix_timestamp":1605716400000,"iso_timestamp":"2020-11-18T16:20:00.000Z","timestamp":"11/18/2020 04:20 pm","time":980},"field_16":"","field_17":"","field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"November pizza Wednesday ","field_76_raw":"November pizza Wednesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2403,"field_129_raw":2402.66666066},{"id":"6010bf647f630d001c9717e4","field_11":1909,"field_11_raw":1909,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"01/26/2021 19:18","field_13_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1611688680000,"iso_timestamp":"2021-01-26T19:18:00.000Z","timestamp":"01/26/2021 07:18 pm","time":1158},"field_14":"7:18pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1325445480000,"iso_timestamp":"2012-01-01T19:18:00.000Z","timestamp":"01/01/2012 07:18 pm","time":1158},"field_15":"01/26/2021 7:18pm","field_15_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"07","minutes":"18","am_pm":"PM","unix_timestamp":1611688680000,"iso_timestamp":"2021-01-26T19:18:00.000Z","timestamp":"01/26/2021 07:18 pm","time":1158},"field_16":"","field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"6010bf71767cc0001bd10a0c\" data-file-name=\"plaid.jpg\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010bf71767cc0001bd10a0c/plaid.jpg\">plaid.jpg</a>","field_17_raw":{"id":"6010bf71767cc0001bd10a0c","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"plaid.jpg","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010bf71767cc0001bd10a0c/plaid.jpg","thumb_url":"","size":121761,"field_key":"field_17"},"field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"January pizza Tuesday ","field_76_raw":"January pizza Tuesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2545,"field_129_raw":2545.33332697},{"id":"6010d262fb99b7001b8b38d3","field_11":1936,"field_11_raw":1936,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"01/26/2021 20:39","field_13_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"08","minutes":"39","am_pm":"PM","unix_timestamp":1611693540000,"iso_timestamp":"2021-01-26T20:39:00.000Z","timestamp":"01/26/2021 08:39 pm","time":1239},"field_14":"8:39pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"08","minutes":"39","am_pm":"PM","unix_timestamp":1325450340000,"iso_timestamp":"2012-01-01T20:39:00.000Z","timestamp":"01/01/2012 08:39 pm","time":1239},"field_15":"01/26/2021 8:39pm","field_15_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"08","minutes":"39","am_pm":"PM","unix_timestamp":1611693540000,"iso_timestamp":"2021-01-26T20:39:00.000Z","timestamp":"01/26/2021 08:39 pm","time":1239},"field_16":"","field_17":"","field_18":"<img src=\"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/6010d261002658001b4d0304/original/plaid.jpg\" />","field_18_raw":{"id":"6010d261002658001b4d0304","application_id":"5d79512148c4af00106d1507","s3":true,"type":"image","filename":"plaid.jpg","url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/6010d261002658001b4d0304/original/plaid.jpg","thumb_url":"https://s3.amazonaws.com/assets.knackhq.com/assets/5d79512148c4af00106d1507/6010d261002658001b4d0304/thumb/plaid.jpg","size":121761,"field_key":"field_18"},"field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"January pizza Tuesday ","field_76_raw":"January pizza Tuesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2581,"field_129_raw":2581.33332688},{"id":"6010d3e629ea96001bf95e4f","field_11":1976,"field_11_raw":1976,"field_125":"","field_6":"","field_7":"","field_8":"","field_10":0,"field_10_raw":0,"field_12":"","field_13":"01/26/2021 20:45","field_13_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"08","minutes":"45","am_pm":"PM","unix_timestamp":1611693900000,"iso_timestamp":"2021-01-26T20:45:00.000Z","timestamp":"01/26/2021 08:45 pm","time":1245},"field_14":"8:45pm","field_14_raw":{"date":"01/01/2012","date_formatted":"01/01/2012","hours":"08","minutes":"45","am_pm":"PM","unix_timestamp":1325450700000,"iso_timestamp":"2012-01-01T20:45:00.000Z","timestamp":"01/01/2012 08:45 pm","time":1245},"field_15":"01/26/2021 8:45pm","field_15_raw":{"date":"01/26/2021","date_formatted":"01/26/2021","hours":"08","minutes":"45","am_pm":"PM","unix_timestamp":1611693900000,"iso_timestamp":"2021-01-26T20:45:00.000Z","timestamp":"01/26/2021 08:45 pm","time":1245},"field_16":"","field_17":"<a class=\"kn-view-asset\" data-field-key=\"field_17\" data-asset-id=\"6010d3e634694d001b8fc18c\" data-file-name=\"plaid.jpg\" href=\"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010d3e634694d001b8fc18c/plaid.jpg\">plaid.jpg</a>","field_17_raw":{"id":"6010d3e634694d001b8fc18c","application_id":"5d79512148c4af00106d1507","s3":true,"type":"file","filename":"plaid.jpg","url":"https://api.knack.com/v1/applications/5d79512148c4af00106d1507/download/asset/6010d3e634694d001b8fc18c/plaid.jpg","thumb_url":"","size":121761,"field_key":"field_17"},"field_18":"","field_19":"","field_20":"","field_21":"","field_22":"","field_23":"","field_24":"","field_25":"","field_9":" two three (four)","field_9_raw":" two three (four)","field_29":"Yes","field_29_raw":true,"field_30":"","field_37":"","field_38":"No","field_38_raw":false,"field_50":"","field_44":"","field_76":"January pizza Tuesday ","field_76_raw":"January pizza Tuesday ","field_126":"","field_127":"","field_128":"","field_128_raw":[],"field_129":2635,"field_129_raw":2634.66666008}]} \ No newline at end of file diff --git a/tests/test_record.py b/tests/test_record.py index 324ca62..4dc4ece 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -6,6 +6,7 @@ import pytest OBJ_KEY = "object_3" FIELD_TO_FORMAT = {"key": "field_127", "name": "address_international_with_country"} FIELD_TO_NOT_FORMAT = {"key": "field_126", "name": "address_international"} +EQUATION_FIELD_TO_TEST = {"key": "field_129"} @pytest.fixture @@ -67,6 +68,20 @@ def test_format_record_value_list(app, records): ) +def test_use_knack_format(records): + """ + Were testing that Knack's formatted value is returned from an equation field + which uses the `use_knack_format` setting = True. The equation field itself + is set to calculate a decimal (auto-increment * 1.333333) and render + an integer + """ + formatted_record = records[0].format(keys=False) + raw_value = records[0][EQUATION_FIELD_TO_TEST["key"]] + formatted_value = formatted_record[EQUATION_FIELD_TO_TEST["key"]] + assert isinstance(raw_value, float) + assert isinstance(formatted_value, int) + + def test_names(records): record = records[0] field_names = record.names()
Knack formatting for equation type fields is not preserved For equation fields, knackpy saves the same (raw) value as both the raw and formatted version of the value. However, the knack formatted version is preferred sometimes, such as when it is a datetime equation. The solution is likely to be adding a function for equation fields to the formatter. So, here are a couple of snippets from the debugger when using knackpy: ``` records[0].fields['field_377'].formatted 372171.3180000782 records[0].fields['field_377'].raw 372171.3180000782 records_formatted[0]['Days Waiting - Security Review'] 372171.3180000782 ``` And here's a snippet from what we get from our knack script (run in debugger): ``` self.data_raw[0]['field_377'] 4 self.data_raw[0]['field_377_raw'] 372171.3180000782 ``` Note that `372171.3180000782 / (60*60*24) = ~4.3` - in other words, the "raw" version returns the value in seconds, while the knack formatted version returns the value in days. Here's another example (different record) - a snippet from the JSON export of the object: `"field_377":5,"field_377_raw":434357.5299999714,`
0.0
0035913119e39a0c243603090370e862585a32ab
[ "tests/test_record.py::test_use_knack_format" ]
[ "tests/test_record.py::test_basic_constructor", "tests/test_record.py::test_record_repr", "tests/test_record.py::test_format_record_keys_values_default", "tests/test_record.py::test_format_record_values_only", "tests/test_record.py::test_format_record_keys_only", "tests/test_record.py::test_format_record_key_list", "tests/test_record.py::test_format_record_value_list", "tests/test_record.py::test_names", "tests/test_record.py::test_keys", "tests/test_record.py::test_get_by_name", "tests/test_record.py::test_get_by_key", "tests/test_record.py::test_unifom_length" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-04-13 22:30:33+00:00
cc0-1.0
1,586
claranet__ssha-63
diff --git a/README.md b/README.md index ca01c66..5031e43 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,13 @@ discover { name of the config that was selected by the user. */ Environment = "${config.name}" - Service = "bastion" + } + + /* + TagsNotEqual can be used to exclude instances with matching tags. + */ + TagsNotEqual { + Service = "k8s" } } diff --git a/ssha/ec2.py b/ssha/ec2.py index 8c51e56..d60c327 100644 --- a/ssha/ec2.py +++ b/ssha/ec2.py @@ -1,5 +1,7 @@ from __future__ import print_function +import operator + from . import aws, config, errors, ssm @@ -42,19 +44,27 @@ def _instance_sort_key(instance): return result -def _rules_pass(obj, rules): +def _rules_pass(obj, rules, compare=operator.eq): for key, expected_value in rules.items(): - if key not in obj: - return False - if isinstance(expected_value, dict): - nested_rules = expected_value - if not _rules_pass(obj[key], nested_rules): + + if key.endswith('NotEqual'): + nested_compare = operator.ne + key = key[:-len('NotEqual')] + else: + nested_compare = compare + + nested_rules_passed = _rules_pass( + obj=obj.get(key) or {}, + rules=expected_value, + compare=nested_compare, + ) + if not nested_rules_passed: return False - elif obj[key] != expected_value: + elif not compare(obj.get(key), expected_value): return False return True
claranet/ssha
66de5fc0b726aaf076b57c843f7e7d04dbd9641c
diff --git a/tests/test_ec2.py b/tests/test_ec2.py new file mode 100644 index 0000000..d44e071 --- /dev/null +++ b/tests/test_ec2.py @@ -0,0 +1,49 @@ +import unittest + +from ssha import ec2 + + +class TestEC2(unittest.TestCase): + + def test_rules_pass(self): + + bastion_instance = { + 'State': { + 'Name': 'Running', + }, + 'Tags': { + 'Service': 'bastion', + }, + } + + web_instance = { + 'State': { + 'Name': 'Running', + }, + 'Tags': { + 'Service': 'web', + }, + } + + is_bastion = { + 'State': { + 'Name': 'Running', + }, + 'Tags': { + 'Service': 'bastion', + } + } + + is_not_bastion = { + 'State': { + 'Name': 'Running', + }, + 'TagsNotEqual': { + 'Service': 'bastion', + } + } + + self.assertTrue(ec2._rules_pass(bastion_instance, is_bastion)) + self.assertTrue(ec2._rules_pass(web_instance, is_not_bastion)) + self.assertFalse(ec2._rules_pass(web_instance, is_bastion)) + self.assertFalse(ec2._rules_pass(bastion_instance, is_not_bastion))
Exclude instances The `discover` and `bastion` blocks allow filters on tags and such. It could be useful to exclude instances with certain tags too.
0.0
66de5fc0b726aaf076b57c843f7e7d04dbd9641c
[ "tests/test_ec2.py::TestEC2::test_rules_pass" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-10-23 17:37:51+00:00
mit
1,587
clarketm__wait-for-it-26
diff --git a/wait_for_it/wait_for_it.py b/wait_for_it/wait_for_it.py index b9f7549..95e856a 100644 --- a/wait_for_it/wait_for_it.py +++ b/wait_for_it/wait_for_it.py @@ -54,7 +54,7 @@ async def _wait_until_available(host, port): if sys.version_info[:2] >= (3, 7): await writer.wait_closed() break - except (socket.gaierror, ConnectionError): + except (socket.gaierror, ConnectionError, OSError, TypeError): pass await asyncio.sleep(1)
clarketm/wait-for-it
6d21debe387243e646be8f61f780a360b8e11429
diff --git a/wait_for_it/test_wait_for_it.py b/wait_for_it/test_wait_for_it.py index 42e0e72..2baa4bc 100644 --- a/wait_for_it/test_wait_for_it.py +++ b/wait_for_it/test_wait_for_it.py @@ -51,10 +51,10 @@ def _start_server_thread(): return server -def _occupy_free_tcp_port(): +def _occupy_free_tcp_port(host): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(("127.0.0.1", _ANY_FREE_PORT)) - host, port = sock.getsockname() + sock.bind((host, _ANY_FREE_PORT)) + _, port = sock.getsockname() return host, port, sock @@ -100,9 +100,18 @@ class CliTest(TestCase): finally: server.stop() - @parameterized.expand([("parallel", ["-p"], 2), ("serial", [], 1)]) - def test_service_unavailable(self, _label, extra_argv, expected_report_count): - host, port, sock = _occupy_free_tcp_port() + @parameterized.expand( + [ + ("parallel", ["-p"], 2, "127.0.0.1"), + ("parallel", ["-p"], 2, "0.0.0.0"), + ("parallel", ["-p"], 2, "localhost"), + ("serial", [], 1, "127.0.0.1"), + ("serial", [], 1, "0.0.0.0"), + ("serial", [], 1, "localhost"), + ] + ) + def test_service_unavailable(self, _label, extra_argv, expected_report_count, host): + _, port, sock = _occupy_free_tcp_port(host) try: result = self._runner.invoke( cli,
Exception when connecting to an unreachable local host. ```console wait-for-it -s localhost:1234 ``` ``` [*] Waiting 15 seconds for localhost:1234 Traceback (most recent call last): File "/usr/local/bin/wait-for-it", line 8, in <module> sys.exit(cli()) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 98, in cli _connect_all_serial(service, timeout) File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 183, in _connect_all_serial connect(service, timeout) File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 191, in connect _asyncio_run(_wait_until_available_and_report(reporter, host, port)) File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 24, in _asyncio_run return asyncio.run(*args, **kvargs) File "/usr/local/Cellar/[email protected]/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 43, in run return loop.run_until_complete(main) File "/usr/local/Cellar/[email protected]/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 51, in _wait_until_available_and_report await _wait_until_available(host, port) File "/usr/local/lib/python3.8/site-packages/wait_for_it/wait_for_it.py", line 39, in _wait_until_available _reader, writer = await asyncio.open_connection(host, port) File "/usr/local/Cellar/[email protected]/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/streams.py", line 52, in open_connection transport, _ = await loop.create_connection( File "/usr/local/Cellar/[email protected]/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1033, in create_connection raise OSError('Multiple exceptions: {}'.format( OSError: Multiple exceptions: [Errno 61] Connect call failed ('127.0.0.1', 1234), [Errno 61] Connect call failed ('::1', 1234, 0, 0) ```
0.0
6d21debe387243e646be8f61f780a360b8e11429
[ "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_2_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_5_serial" ]
[ "wait_for_it/test_wait_for_it.py::CliTest::test_command_invocation_forwards_exit_code_0", "wait_for_it/test_wait_for_it.py::CliTest::test_command_invocation_forwards_exit_code_1", "wait_for_it/test_wait_for_it.py::CliTest::test_help", "wait_for_it/test_wait_for_it.py::CliTest::test_service_available_0_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_available_1_serial", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_0_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_1_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_3_serial", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_4_serial", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_0__1_1234", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_1_domain_ext_1", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_2_domain_ext_65536", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_3_domain_ext_1_2", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_0__1_1234", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_1_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_2_domain_ext_0", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_3_domain_ext_1", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_4_domain_ext_65535", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_5_http_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_6_http_domain_ext_path_", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_7_https_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_8_https_domain_ext_path_" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-07-30 05:29:35+00:00
mit
1,588
clarketm__wait-for-it-29
diff --git a/.github/workflows/python-package.yaml b/.github/workflows/python-package.yaml index b70a10b..18fe05a 100644 --- a/.github/workflows/python-package.yaml +++ b/.github/workflows/python-package.yaml @@ -5,7 +5,8 @@ jobs: strategy: matrix: python-version: [3.6, 3.7, 3.8] - runs-on: ubuntu-latest + runs-on: [macos-latest, ubuntu-latest] + runs-on: ${{ matrix.runs-on }} steps: - name: Checkout uses: actions/checkout@v2 diff --git a/wait_for_it/wait_for_it.py b/wait_for_it/wait_for_it.py index 467f259..b9f7549 100644 --- a/wait_for_it/wait_for_it.py +++ b/wait_for_it/wait_for_it.py @@ -7,6 +7,7 @@ import subprocess import sys import time from contextlib import contextmanager +from enum import Enum from urllib.parse import urlparse import click @@ -14,6 +15,15 @@ import click from wait_for_it import __version__ +class _WaitForItException(Exception): + """Base class for all exceptions custom to wait-for-it""" + + +class _MalformedServiceSyntaxException(_WaitForItException): + def __init__(self, service): + super().__init__(f"{service!r} is not a supported syntax for a service") + + def _asyncio_run(*args, **kvargs): """ Cheap backport of asyncio.run of Python 3.7+ to Python 3.6. @@ -27,9 +37,12 @@ def _asyncio_run(*args, **kvargs): def _determine_host_and_port_for(service): scheme, _, host = service.rpartition(r"//") - url = urlparse(f"{scheme}//{host}", scheme="http") - host = url.hostname - port = url.port or (443 if url.scheme == "https" else 80) + try: + url = urlparse(f"{scheme}//{host}", scheme="http") + host = url.hostname + port = url.port or (443 if url.scheme == "https" else 80) + except ValueError: + raise _MalformedServiceSyntaxException(service) return host, port @@ -86,9 +99,16 @@ async def _wait_until_available_and_report(reporter, host, port): help="Timeout in seconds, 0 for no timeout", ) @click.argument("commands", nargs=-1) -def cli(service, quiet, parallel, timeout, commands): +def cli(**kwargs): """Wait for service(s) to be available before executing a command.""" + try: + _cli_internal(**kwargs) + except _WaitForItException as e: + _Messenger.tell_failure(str(e)) + sys.exit(1) + +def _cli_internal(service, quiet, parallel, timeout, commands): if quiet: sys.stdout = open(os.devnull, "w") @@ -102,11 +122,31 @@ def cli(service, quiet, parallel, timeout, commands): sys.exit(result.returncode) -class _ConnectionJobReporter: - _SUCCESS = "[+] " - _FAILURE = "[-] " - _NEUTRAL = "[*] " +class _Messenger: + class _MessageType(Enum): + SUCCESS = "[+] " + FAILURE = "[-] " + NEUTRAL = "[*] " + @classmethod + def _tell(cls, message_type, message): + prefix = message_type.value + print(f"{prefix}{message}") + + @classmethod + def tell_success(cls, message): + cls._tell(cls._MessageType.SUCCESS, message) + + @classmethod + def tell_failure(cls, message): + cls._tell(cls._MessageType.FAILURE, message) + + @classmethod + def tell_neutral(cls, message): + cls._tell(cls._MessageType.NEUTRAL, message) + + +class _ConnectionJobReporter: def __init__(self, host, port, timeout): self._friendly_name = f"{host}:{port}" self._timeout = timeout @@ -115,24 +155,23 @@ class _ConnectionJobReporter: def on_before_start(self): if self._timeout: - print( - f"{self._NEUTRAL}Waiting {self._timeout} seconds for {self._friendly_name}" - ) + message = f"Waiting {self._timeout} seconds for {self._friendly_name}" else: - print(f"{self._NEUTRAL}Waiting for {self._friendly_name} without a timeout") + message = f"Waiting for {self._friendly_name} without a timeout" + + _Messenger.tell_neutral(message) self._started_at = time.time() def on_success(self): seconds = round(time.time() - self._started_at) - print( - f"{self._SUCCESS}{self._friendly_name} is available after {seconds} seconds" + _Messenger.tell_success( + f"{self._friendly_name} is available after {seconds} seconds" ) self.job_successful = True def on_timeout(self): - print( - f"{self._FAILURE}Timeout occurred after waiting {self._timeout} seconds" - f" for {self._friendly_name}" + _Messenger.tell_failure( + f"Timeout occurred after waiting {self._timeout} seconds" )
clarketm/wait-for-it
18a1043d25242ac3bab76ecf6104c0ee9c0afcf0
diff --git a/wait_for_it/test_wait_for_it.py b/wait_for_it/test_wait_for_it.py index aa04023..42e0e72 100644 --- a/wait_for_it/test_wait_for_it.py +++ b/wait_for_it/test_wait_for_it.py @@ -10,7 +10,11 @@ from unittest import TestCase from click.testing import CliRunner from parameterized import parameterized -from .wait_for_it import cli, _determine_host_and_port_for +from .wait_for_it import ( + cli, + _determine_host_and_port_for, + _MalformedServiceSyntaxException, +) _ANY_FREE_PORT = 0 @@ -113,15 +117,30 @@ class CliTest(TestCase): class DetermineHostAndPortForTest(TestCase): @parameterized.expand( [ - ("domain.ext", 80), - ("domain.ext:123", 123), - ("http://domain.ext", 80), - ("http://domain.ext/path/", 80), - ("https://domain.ext", 443), - ("https://domain.ext/path/", 443), + ("[::1]:1234", "::1", 1234), + ("domain.ext", "domain.ext", 80), + ("domain.ext:0", "domain.ext", 80), + ("domain.ext:1", "domain.ext", 1), + ("domain.ext:65535", "domain.ext", 65535), + ("http://domain.ext", "domain.ext", 80), + ("http://domain.ext/path/", "domain.ext", 80), + ("https://domain.ext", "domain.ext", 443), + ("https://domain.ext/path/", "domain.ext", 443), ] ) - def test_supportec(self, service, expected_port): + def test_supported(self, service, expected_host, expected_port): actual_host, actual_port = _determine_host_and_port_for(service) - assert actual_host == "domain.ext" + assert actual_host == expected_host assert actual_port == expected_port + + @parameterized.expand( + [ + ("::1:1234",), # needs "[::1]:1234", instead + ("domain.ext:-1",), + ("domain.ext:65536",), + ("domain.ext:1.2",), + ] + ) + def test_rejected(self, service): + with self.assertRaises(_MalformedServiceSyntaxException): + _determine_host_and_port_for(service)
"wait-for-it -s ::1:1234" crashes with ValueError: invalid literal for int() with base 10: ':1:1234' ``` $ wait-for-it -s ::1:1234 Traceback (most recent call last): File "/tmp/tmp.EpOU9tyqoz/py3/bin/wait-for-it", line 33, in <module> sys.exit(load_entry_point('wait-for-it', 'console_scripts', 'wait-for-it')()) File "/tmp/tmp.EpOU9tyqoz/py3/lib/python3.7/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/tmp/tmp.EpOU9tyqoz/py3/lib/python3.7/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/tmp/tmp.EpOU9tyqoz/py3/lib/python3.7/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/tmp/tmp.EpOU9tyqoz/py3/lib/python3.7/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/tmp/tmp.EpOU9tyqoz/wait-for-it/wait_for_it/wait_for_it.py", line 98, in cli _connect_all_serial(service, timeout) File "/tmp/tmp.EpOU9tyqoz/wait-for-it/wait_for_it/wait_for_it.py", line 183, in _connect_all_serial connect(service, timeout) File "/tmp/tmp.EpOU9tyqoz/wait-for-it/wait_for_it/wait_for_it.py", line 187, in connect host, port = _determine_host_and_port_for(service) File "/tmp/tmp.EpOU9tyqoz/wait-for-it/wait_for_it/wait_for_it.py", line 32, in _determine_host_and_port_for port = url.port or (443 if url.scheme == "https" else 80) File "/usr/lib/python3.7/urllib/parse.py", line 169, in port port = int(port, 10) ValueError: invalid literal for int() with base 10: ':1:1234' ``` This is caused by the URL service format support introduced at https://github.com/clarketm/wait-for-it/commit/9d8f631939bb686d7d1587766e0381211e83bfe0#diff-ae5818251477f1a9e950145b0ae260dcR36-R41 . The core is the difference between these two cases: ``` In [18]: urlparse('https://[::1]:1234', scheme="http").port Out[18]: 1234 In [19]: urlparse('https://::1:1234', scheme="http").port [..] ValueError: invalid literal for int() with base 10: ':1:1234' ``` I wonder if a user can expect `::1:1234` or rather `[::1]:1234` to work with `wait-for-it`. The square bracket syntax is from [RFC 3986 section 3.2.2](https://tools.ietf.org/html/rfc3986#section-3.2.2) but we don't always have a full URI here. What do you think? What's the best other tool to check how they handle this issue, especially disambiguation of the colon? PS: This is not a recently introduced issue so maybe it doesn't need to block the upcoming release but just my 2 cents.
0.0
18a1043d25242ac3bab76ecf6104c0ee9c0afcf0
[ "wait_for_it/test_wait_for_it.py::CliTest::test_command_invocation_forwards_exit_code_0", "wait_for_it/test_wait_for_it.py::CliTest::test_command_invocation_forwards_exit_code_1", "wait_for_it/test_wait_for_it.py::CliTest::test_help", "wait_for_it/test_wait_for_it.py::CliTest::test_service_available_0_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_available_1_serial", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_0_parallel", "wait_for_it/test_wait_for_it.py::CliTest::test_service_unavailable_1_serial", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_0__1_1234", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_1_domain_ext_1", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_2_domain_ext_65536", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_rejected_3_domain_ext_1_2", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_0__1_1234", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_1_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_2_domain_ext_0", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_3_domain_ext_1", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_4_domain_ext_65535", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_5_http_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_6_http_domain_ext_path_", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_7_https_domain_ext", "wait_for_it/test_wait_for_it.py::DetermineHostAndPortForTest::test_supported_8_https_domain_ext_path_" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-08-01 16:31:32+00:00
mit
1,589
claudep__swiss-qr-bill-76
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index e03592e..d2906f1 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -3,6 +3,10 @@ ChangeLog ========= +Unreleased +---------- +- Replaced ``##`` with ``//`` as separator in additional informations (#75). + 0.7.1 (2022-03-07) ------------------ - Fixed bad position of amount rect on receipt part (#74). diff --git a/qrbill/bill.py b/qrbill/bill.py index 92b38b4..f9476e8 100644 --- a/qrbill/bill.py +++ b/qrbill/bill.py @@ -675,9 +675,9 @@ class QRBill: if self.extra_infos: add_header(self.label("Additional information")) - if '##' in self.extra_infos: - extra_infos = self.extra_infos.split('##') - extra_infos[1] = '##' + extra_infos[1] + if '//' in self.extra_infos: + extra_infos = self.extra_infos.split('//') + extra_infos[1] = '//' + extra_infos[1] else: extra_infos = [self.extra_infos] # TODO: handle line breaks for long infos (mandatory 5mm margin)
claudep/swiss-qr-bill
1945115b01638f8b2344a62979bb9cfe3e36db4f
diff --git a/tests/test_qrbill.py b/tests/test_qrbill.py index 8e7a010..02339da 100644 --- a/tests/test_qrbill.py +++ b/tests/test_qrbill.py @@ -293,7 +293,7 @@ class QRBillTests(unittest.TestCase): }, ref_number='210000000003139471430009017', extra_infos=( - 'Order of 15.09.2019##S1/01/20170309/11/10201409/20/1400' + 'Order of 15.09.2019//S1/01/20170309/11/10201409/20/1400' '0000/22/36958/30/CH106017086/40/1020/41/3010' ) ) @@ -311,7 +311,7 @@ class QRBillTests(unittest.TestCase): 'Rue du Lac\r\n1268\r\n2501\r\nBiel\r\nCH\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n' '1949.70\r\nCHF\r\nS\r\nPia-Maria Rutschmann-Schnyder\r\nGrosse Marktgasse\r\n' '28\r\n9400\r\nRorschach\r\nCH\r\nQRR\r\n210000000003139471430009017\r\n' - 'Order of 15.09.2019##S1/01/20170309/11/10201409/20/14000000/22/36958/30/CH106017086' + 'Order of 15.09.2019//S1/01/20170309/11/10201409/20/14000000/22/36958/30/CH106017086' '/40/1020/41/3010\r\nEPD' ) with tempfile.NamedTemporaryFile(suffix='.svg') as fh:
postfinance doesnt accept generated qr-code Hi, our postfinance doesnt accept our generated qr-code because there are characters in line 30 that are not allowed (extra_infos, '##' character for visual line split). Is it possible to remove the character after line split (line 680 in bill.py)? Currently its readded after line split.
0.0
1945115b01638f8b2344a62979bb9cfe3e36db4f
[ "tests/test_qrbill.py::QRBillTests::test_spec_example1" ]
[ "tests/test_qrbill.py::AddressTests::test_combined", "tests/test_qrbill.py::AddressTests::test_name_limit", "tests/test_qrbill.py::AddressTests::test_newlines", "tests/test_qrbill.py::AddressTests::test_split_lines", "tests/test_qrbill.py::QRBillTests::test_account", "tests/test_qrbill.py::QRBillTests::test_alt_procs", "tests/test_qrbill.py::QRBillTests::test_amount", "tests/test_qrbill.py::QRBillTests::test_as_svg_filelike", "tests/test_qrbill.py::QRBillTests::test_country", "tests/test_qrbill.py::QRBillTests::test_currency", "tests/test_qrbill.py::QRBillTests::test_font_factor", "tests/test_qrbill.py::QRBillTests::test_full_page", "tests/test_qrbill.py::QRBillTests::test_mandatory_fields", "tests/test_qrbill.py::QRBillTests::test_minimal_data", "tests/test_qrbill.py::QRBillTests::test_reference", "tests/test_qrbill.py::QRBillTests::test_ultimate_creditor", "tests/test_qrbill.py::CommandLineTests::test_combined_address", "tests/test_qrbill.py::CommandLineTests::test_minimal_args", "tests/test_qrbill.py::CommandLineTests::test_no_args", "tests/test_qrbill.py::CommandLineTests::test_svg_result", "tests/test_qrbill.py::CommandLineTests::test_text_result" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-03-24 19:46:07+00:00
mit
1,590
claudep__swiss-qr-bill-77
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index d2906f1..ab31a95 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,9 @@ ChangeLog Unreleased ---------- - Replaced ``##`` with ``//`` as separator in additional informations (#75). +- Print scissors symbol on horizontal separation line when not in full page. + WARNING: the resulting bill is 1 millimiter higher to be able to show the + entire symbol (#65). 0.7.1 (2022-03-07) ------------------ diff --git a/qrbill/bill.py b/qrbill/bill.py index f9476e8..889eeda 100644 --- a/qrbill/bill.py +++ b/qrbill/bill.py @@ -18,7 +18,7 @@ AMOUNT_REGEX = r'^\d{1,9}\.\d{2}$' DATE_REGEX = r'(\d{4})-(\d{2})-(\d{2})' MM_TO_UU = 3.543307 -BILL_HEIGHT = '105mm' +BILL_HEIGHT = 106 # 105mm + 1mm for horizontal scissors to show up. RECEIPT_WIDTH = '62mm' PAYMENT_WIDTH = '148mm' MAX_CHARS_PAYMENT_LINE = 72 @@ -471,12 +471,12 @@ class QRBill: ) else: dwg = svgwrite.Drawing( - size=(A4[0], BILL_HEIGHT), # A4 width, A6 height. + size=(A4[0], f'{BILL_HEIGHT}mm'), # A4 width, A6 height. viewBox=('0 0 %f %f' % (mm(A4[0]), mm(BILL_HEIGHT))), ) dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), fill='white')) # Force white background - bill_group = self.draw_bill(dwg) + bill_group = self.draw_bill(dwg, horiz_scissors=not full_page) if full_page: self.transform_to_full_page(dwg, bill_group) @@ -498,7 +498,7 @@ class QRBill: # add text snippet x_center = mm(A4[0]) / 2 - y_pos = y_offset - mm(2) + y_pos = y_offset - mm(1) dwg.add(dwg.text( self.label("Separate before paying in"), @@ -508,19 +508,20 @@ class QRBill: **self.font_info) ) - def draw_bill(self, dwg): + def draw_bill(self, dwg, horiz_scissors=True): """Draw the bill in SVG format.""" margin = mm(5) payment_left = add_mm(RECEIPT_WIDTH, margin) payment_detail_left = add_mm(payment_left, mm(46 + 5)) - currency_top = mm(72) + above_padding = 1 # 1mm added for scissors display + currency_top = mm(72 + above_padding) grp = dwg.add(dwg.g()) # Receipt - y_pos = 15 + y_pos = 15 + above_padding line_space = 3.5 receipt_head_font = self.head_font_info(part='receipt') - grp.add(dwg.text(self.label("Receipt"), (margin, mm(10)), **self.title_font_info)) + grp.add(dwg.text(self.label("Receipt"), (margin, mm(y_pos - 5)), **self.title_font_info)) grp.add(dwg.text(self.label("Account / Payable to"), (margin, mm(y_pos)), **receipt_head_font)) y_pos += line_space grp.add(dwg.text( @@ -572,21 +573,32 @@ class QRBill: # Right-aligned grp.add(dwg.text( - self.label("Acceptance point"), (add_mm(RECEIPT_WIDTH, margin * -1), mm(86)), + self.label("Acceptance point"), (add_mm(RECEIPT_WIDTH, margin * -1), mm(86 + above_padding)), text_anchor='end', **receipt_head_font )) # Top separation line if self.top_line: grp.add(dwg.line( - start=(0, mm(0.141)), end=(add_mm(RECEIPT_WIDTH, PAYMENT_WIDTH), mm(0.141)), + start=(0, mm(0.141 + above_padding)), + end=(add_mm(RECEIPT_WIDTH, PAYMENT_WIDTH), mm(0.141 + above_padding)), stroke='black', stroke_dasharray='2 2', fill='none' )) + if horiz_scissors: + # Scissors on horizontal line + path = dwg.path( + d=SCISSORS_SVG_PATH, + style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none", + ) + path.scale(1.9) + path.translate(tx=24, ty=0) + grp.add(path) # Separation line between receipt and payment parts if self.payment_line: grp.add(dwg.line( - start=(mm(RECEIPT_WIDTH), 0), end=(mm(RECEIPT_WIDTH), mm(BILL_HEIGHT)), + start=(mm(RECEIPT_WIDTH), mm(above_padding)), + end=(mm(RECEIPT_WIDTH), mm(BILL_HEIGHT - above_padding)), stroke='black', stroke_dasharray='2 2', fill='none' )) # Scissors on vertical line @@ -601,7 +613,7 @@ class QRBill: # Payment part payment_head_font = self.head_font_info(part='payment') - grp.add(dwg.text(self.label("Payment part"), (payment_left, mm(10)), **self.title_font_info)) + grp.add(dwg.text(self.label("Payment part"), (payment_left, mm(10 + above_padding)), **self.title_font_info)) # Get QR code SVG from qrcode lib, read it and redraw path in svgwrite drawing. buff = BytesIO() @@ -623,16 +635,16 @@ class QRBill: scale_factor = mm(45.8) / im.width qr_left = payment_left - qr_top = 60 + qr_top = 60 + above_padding path.translate(tx=qr_left, ty=qr_top) path.scale(scale_factor) grp.add(path) - self.draw_swiss_cross(dwg, grp, (payment_left, 60), im.width * scale_factor) + self.draw_swiss_cross(dwg, grp, (payment_left, qr_top), im.width * scale_factor) grp.add(dwg.text(self.label("Currency"), (payment_left, currency_top), **payment_head_font)) grp.add(dwg.text(self.label("Amount"), (add_mm(payment_left, mm(12)), currency_top), **payment_head_font)) - grp.add(dwg.text(self.currency, (payment_left, mm(77)), **self.font_info)) + grp.add(dwg.text(self.currency, (payment_left, mm(currency_top + 5)), **self.font_info)) if self.amount: grp.add(dwg.text( format_amount(self.amount), @@ -646,7 +658,7 @@ class QRBill: ) # Right side of the bill - y_pos = 10 + y_pos = 10 + above_padding line_space = 3.5 def add_header(text, first=False):
claudep/swiss-qr-bill
ca496deaef5cd52a16677b101c6cbb1a07ff3c8c
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 579a28d..37d0ba7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.6", "3.7", "3.8", "3.9"] + python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} diff --git a/tests/test_qrbill.py b/tests/test_qrbill.py index 02339da..8c5f220 100644 --- a/tests/test_qrbill.py +++ b/tests/test_qrbill.py @@ -329,21 +329,21 @@ class QRBillTests(unittest.TestCase): '<text {font9} x="{x}" y="{y5}">Payable by </text>' '<text {font10} x="{x}" y="{y6}">31.10.2019</text>'.format( font9=font9, font10=font10, x='418.11023', - y1=mm(57.5), y2=mm(61), y3=mm(64.5), y4=mm(68), y5=mm(74.5), y6=mm(78), + y1=mm(58.5), y2=mm(62), y3=mm(65.5), y4=mm(69), y5=mm(75.5), y6=mm(79), ) ) self.assertIn(expected, content) # IBAN formatted self.assertIn( '<text {font10} x="{x}" y="{y}">CH44 3199 9123 0008 8901 2</text>'.format( - font10=font10, x=mm(5), y=mm(18.5), + font10=font10, x=mm(5), y=mm(19.5), ), content ) # amount formatted self.assertIn( '<text {font10} x="{x}" y="{y}">1 949.70</text>'.format( - font10=font10, x=mm(17), y=mm(77), + font10=font10, x=mm(17), y=mm(78), ), content ) @@ -437,14 +437,17 @@ class QRBillTests(unittest.TestCase): }, font_factor=1.5 ) + content = strip_svg_path(self._produce_svg(bill)) self.assertIn( '<text font-family="Helvetica" font-size="18.0" font-weight="bold"' - ' x="17.71654" y="35.43307">Receipt</text>' + ' x="17.71654" y="{y1}">Receipt</text>' '<text font-family="Helvetica" font-size="12.0" font-weight="bold"' - ' x="17.71654" y="53.14961">Account / Payable to</text>' + ' x="17.71654" y="{y2}">Account / Payable to</text>' '<text font-family="Helvetica" font-size="15.0" x="17.71654"' - ' y="65.55118">CH53 8000 5000 0102 8366 4</text>', - self._produce_svg(bill) + ' y="{y3}">CH53 8000 5000 0102 8366 4</text>'.format( + y1=mm(11), y2=mm(16), y3=mm(19.5) + ), + content )
Scissors missing on top seperation line Currently the scissor is only shown on the vertical seperation line. However; in the standard it says that a scissor symbol should appear on both of those lines. I tried adding it to the top line, but my attempt doesn't look great: ```python grp.add(dwg.text( "✂", insert=(add_mm(60, mm(-1.5)), 10), font_size=16, font_family='Helvetica' )) ``` Possibly you could come up with a better way and help me out?
0.0
ca496deaef5cd52a16677b101c6cbb1a07ff3c8c
[ "tests/test_qrbill.py::QRBillTests::test_font_factor", "tests/test_qrbill.py::QRBillTests::test_spec_example1" ]
[ "tests/test_qrbill.py::AddressTests::test_combined", "tests/test_qrbill.py::AddressTests::test_name_limit", "tests/test_qrbill.py::AddressTests::test_newlines", "tests/test_qrbill.py::AddressTests::test_split_lines", "tests/test_qrbill.py::QRBillTests::test_account", "tests/test_qrbill.py::QRBillTests::test_alt_procs", "tests/test_qrbill.py::QRBillTests::test_amount", "tests/test_qrbill.py::QRBillTests::test_as_svg_filelike", "tests/test_qrbill.py::QRBillTests::test_country", "tests/test_qrbill.py::QRBillTests::test_currency", "tests/test_qrbill.py::QRBillTests::test_full_page", "tests/test_qrbill.py::QRBillTests::test_mandatory_fields", "tests/test_qrbill.py::QRBillTests::test_minimal_data", "tests/test_qrbill.py::QRBillTests::test_reference", "tests/test_qrbill.py::QRBillTests::test_ultimate_creditor", "tests/test_qrbill.py::CommandLineTests::test_combined_address", "tests/test_qrbill.py::CommandLineTests::test_minimal_args", "tests/test_qrbill.py::CommandLineTests::test_no_args", "tests/test_qrbill.py::CommandLineTests::test_svg_result", "tests/test_qrbill.py::CommandLineTests::test_text_result" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-25 19:04:41+00:00
mit
1,591
claudep__swiss-qr-bill-87
diff --git a/qrbill/bill.py b/qrbill/bill.py index 53bee98..4b1ca0c 100644 --- a/qrbill/bill.py +++ b/qrbill/bill.py @@ -404,7 +404,7 @@ class QRBill: values.extend([ self.ref_type or '', self.reference_number or '', - self.additional_information or '', + replace_linebreaks(self.additional_information), ]) values.append('EPD') values.extend(self.alt_procs) @@ -794,7 +794,13 @@ def format_amount(amount_): def wrap_infos(infos): - for text in infos: - while(text): - yield text[:MAX_CHARS_PAYMENT_LINE] - text = text[MAX_CHARS_PAYMENT_LINE:] + for line in infos: + for text in line.splitlines(): + while text: + yield text[:MAX_CHARS_PAYMENT_LINE] + text = text[MAX_CHARS_PAYMENT_LINE:] + + +def replace_linebreaks(text): + text = text or '' + return ' '.join(text.splitlines())
claudep/swiss-qr-bill
eb12fae5e39cbd10e6d82adbf6a3736363f8def8
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 37d0ba7..47eb061 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,8 +7,8 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 with: python-version: "3.9" - name: Install dependencies @@ -25,9 +25,9 @@ jobs: matrix: python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 + uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies diff --git a/tests/test_qrbill.py b/tests/test_qrbill.py index 9ef2c93..3f571dc 100644 --- a/tests/test_qrbill.py +++ b/tests/test_qrbill.py @@ -238,6 +238,27 @@ class QRBillTests(unittest.TestCase): self.assertEqual(bill.amount, expected) self.assertEqual(format_amount(bill.amount), printed) + def test_additionnal_info_break(self): + """ + Line breaks in additional_information are converted to space in QR data + (but still respected on info display) + """ + bill = QRBill( + account="CH 53 8000 5000 0102 83664", + creditor={ + 'name': 'Jane', 'pcode': '1000', 'city': 'Lausanne', + }, + additional_information="Hello\nLine break", + ) + self.assertEqual( + bill.qr_data(), + 'SPC\r\n0200\r\n1\r\nCH5380005000010283664\r\nS\r\nJane\r\n\r\n\r\n' + '1000\r\nLausanne\r\nCH\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nCHF\r\n' + '\r\n\r\n\r\n\r\n\r\n\r\n\r\nNON\r\n\r\nHello Line break\r\nEPD' + ) + with open("test1.svg", 'w') as fh: + bill.as_svg(fh.name) + def test_minimal_data(self): bill = QRBill( account="CH 53 8000 5000 0102 83664",
line break in additional_information isnt shown and breaks many scanners Providing a line break character "\n" in the string for the additional_information parameter will cause problems with many scanners. steps to reproduce: QRBill(additional_information= f"Hello \n Line break") The line break will not be visible in the human-readable text field, and will cause an error in the encoded bytes data of the qr code, which many scanners will be unable to decode Even though some scanners can properly decode the resulting bytes, I do suggest sanitizing line breaks from the provided string, because the line break itself isnt properly displayed anyway, and this might cause many issues for users trying to use multiple lines in this section.
0.0
eb12fae5e39cbd10e6d82adbf6a3736363f8def8
[ "tests/test_qrbill.py::QRBillTests::test_additionnal_info_break" ]
[ "tests/test_qrbill.py::AddressTests::test_combined", "tests/test_qrbill.py::AddressTests::test_name_limit", "tests/test_qrbill.py::AddressTests::test_newlines", "tests/test_qrbill.py::AddressTests::test_split_lines", "tests/test_qrbill.py::QRBillTests::test_account", "tests/test_qrbill.py::QRBillTests::test_alt_procs", "tests/test_qrbill.py::QRBillTests::test_amount", "tests/test_qrbill.py::QRBillTests::test_as_svg_filelike", "tests/test_qrbill.py::QRBillTests::test_country", "tests/test_qrbill.py::QRBillTests::test_currency", "tests/test_qrbill.py::QRBillTests::test_font_factor", "tests/test_qrbill.py::QRBillTests::test_full_page", "tests/test_qrbill.py::QRBillTests::test_mandatory_fields", "tests/test_qrbill.py::QRBillTests::test_minimal_data", "tests/test_qrbill.py::QRBillTests::test_reference", "tests/test_qrbill.py::QRBillTests::test_spec_example1", "tests/test_qrbill.py::QRBillTests::test_ultimate_creditor", "tests/test_qrbill.py::CommandLineTests::test_combined_address", "tests/test_qrbill.py::CommandLineTests::test_minimal_args", "tests/test_qrbill.py::CommandLineTests::test_no_args", "tests/test_qrbill.py::CommandLineTests::test_svg_result", "tests/test_qrbill.py::CommandLineTests::test_text_result" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-09-20 16:15:55+00:00
mit
1,592
cldf__csvw-49
diff --git a/README.md b/README.md index a90bdd4..dc0d42b 100644 --- a/README.md +++ b/README.md @@ -72,14 +72,36 @@ probably never will) implement the full extent of this spec. description. +## Compatibility with [Frictionless Data Specs](https://specs.frictionlessdata.io/) + +The CSVW-described dataset is basically equivalent to a [Frictionless DataPackage] where all [Data Resources](https://specs.frictionlessdata.io/data-resource/) are [Tabular Data](https://specs.frictionlessdata.io/tabular-data-resource/). +Thus, the `csvw` package provides some conversion functionality. To +"read CSVW data from a Data Package", there's the `csvw.TableGroup.from_frictionless_datapackage` method: +```python +from csvw import TableGroup +tg = TableGroup.from_frictionless_datapackage('PATH/TO/datapackage.json') +``` +To convert the metadata, the `TableGroup` can then be serialzed: +```python +tg.to_file('csvw-metadata.json') +``` + +Note that the CSVW metadata file must be written to the Data Package's directory +to make sure relative paths to data resources work. + +This functionality - together with the schema inference capabilities +of [`frictionless describe`](https://frictionlessdata.io/tooling/python/describing-data/#describe-functions) - provides +a convenient way to bootstrap CSVW metadata for a set of "raw" CSV +files. + + ## See also - https://www.w3.org/2013/csvw/wiki/Main_Page - https://github.com/CLARIAH/COW - https://github.com/CLARIAH/ruminator - https://github.com/bloomberg/pycsvw -- https://github.com/frictionlessdata/goodtables-py -- https://github.com/frictionlessdata/tableschema-py +- https://specs.frictionlessdata.io/table-schema/ - https://github.com/theodi/csvlint.rb - https://github.com/ruby-rdf/rdf-tabular - https://github.com/rdf-ext/rdf-parser-csvw diff --git a/src/csvw/frictionless.py b/src/csvw/frictionless.py new file mode 100644 index 0000000..eca4f22 --- /dev/null +++ b/src/csvw/frictionless.py @@ -0,0 +1,222 @@ +""" +Functionality to convert tabular data in Frictionless Data Packages to CSVW. + +We translate [table schemas](https://specs.frictionlessdata.io/table-schema/) defined +for [data resources](https://specs.frictionlessdata.io/data-resource/) in a +[data package](https://specs.frictionlessdata.io/data-package/) to a CVSW TableGroup. + +This functionality can be used together with the `frictionless describe` command to add +CSVW metadata to "raw" CSV tables. +""" +import json +import pathlib + + +def convert_column_spec(spec): + """ + https://specs.frictionlessdata.io/table-schema/#field-descriptors + + :param spec: + :return: + """ + typemap = { + 'year': 'gYear', + 'yearmonth': 'gYearMonth', + } + + titles = [t for t in [spec.get('title')] if t] + + res = {'name': spec['name'], 'datatype': {'base': 'string'}} + if 'type' in spec: + if spec['type'] == 'string' and spec.get('format') == 'binary': + res['datatype']['base'] = 'binary' + elif spec['type'] == 'string' and spec.get('format') == 'uri': + res['datatype']['base'] = 'anyURI' + elif spec['type'] in typemap: + res['datatype']['base'] = typemap[spec['type']] + elif spec['type'] in [ + 'string', 'number', 'integer', 'boolean', 'date', 'time', 'datetime', 'duration', + ]: + res['datatype']['base'] = spec['type'] + if spec['type'] == 'string' and spec.get('format'): + res['datatype']['dc:format'] = spec['format'] + if spec['type'] == 'boolean' and spec.get('trueValues') and spec.get('falseValues'): + res['datatype']['format'] = '{}|{}'.format( + spec['trueValues'][0], spec['falseValues'][0]) + if spec['type'] in ['number', 'integer']: + if spec.get('bareNumber') is True: # pragma: no cover + raise NotImplementedError( + 'bareNumber is not supported in CSVW. It may be possible to translate to ' + 'a number pattern, though. See ' + 'https://www.w3.org/TR/2015/REC-tabular-data-model-20151217/' + '#formats-for-numeric-types') + if any(prop in spec for prop in ['decimalChar', 'groupChar']): + res['datatype']['format'] = {} + for p in ['decimalChar', 'groupChar']: + if spec.get(p): + res['datatype']['format'][p] = spec[p] + elif spec['type'] in ['object', 'array']: + res['datatype']['base'] = 'json' + res['datatype']['dc:format'] = 'application/json' + elif spec['type'] == 'geojson': + res['datatype']['base'] = 'json' + res['datatype']['dc:format'] = 'application/geo+json' + + if titles: + res['titles'] = titles + if 'description' in spec: + res['dc:description'] = [spec['description']] + if 'rdfType' in spec: + res['propertyUrl'] = spec['rdfType'] + + constraints = spec.get('constraints', {}) + for prop in ['required', 'minLength', 'maxLength', 'minimum', 'maximum']: + if prop in constraints: + res['datatype'][prop] = constraints[prop] + if ('pattern' in constraints) and ('format' not in res['datatype']): + res['datatype']['format'] = constraints['pattern'] + # FIXME: we could transform the "enum" constraint for string into + # a regular expression in the "format" property. + return res + + +def convert_foreignKey(rsc_name, fk, resource_map): + """ + https://specs.frictionlessdata.io/table-schema/#foreign-keys + """ + # Rename "fields" to "columnReference" and map resource name to url (resolving self-referential + # foreign keys). + return dict( + columnReference=fk['fields'], + reference=dict( + columnReference=fk['reference']['fields'], + resource=resource_map[fk['reference']['resource'] or rsc_name], + ) + ) + + +def convert_table_schema(rsc_name, schema, resource_map): + """ + :param rsc_name: `name` property of the resource the schema belongs to. Needed to resolve \ + self-referential foreign keys. + :param schema: `dict` parsed from JSON representing a frictionless Table Schema object. + :param resource_map: `dict` mapping resource names to resource paths, needed to convert foreign\ + key constraints. + :return: `dict` suitable for instantiating a `csvw.metadata.Schema` object. + """ + res = dict( + columns=[convert_column_spec(f) for f in schema['fields']], + ) + for prop in [ + ('missingValues', 'null'), + 'primaryKey', + 'foreignKeys', + ]: + if isinstance(prop, tuple): + prop, toprop = prop + else: + toprop = prop + if prop in schema: + res[toprop] = schema[prop] + if prop == 'foreignKeys': + res[toprop] = [convert_foreignKey(rsc_name, fk, resource_map) for fk in res[toprop]] + return res + + +def convert_dialect(rsc): + """ + https://specs.frictionlessdata.io/csv-dialect/ + """ + d = rsc.get('dialect', {}) + res = {} + if d.get('delimiter'): + res['delimiter'] = d['delimiter'] + if rsc.get('encoding'): + res['encoding'] = rsc['encoding'] + for prop in [ + 'delimiter', + 'quoteChar', + 'doubleQuote', + 'skipInitialSpace', + 'header', + ]: + if prop in d: + res[prop] = d[prop] + if 'lineTerminator' in d: + res['lineTerminators'] = [d['lineTerminator']] + if 'commentChar' in d: + res['commentPrefix'] = d['commentChar'] + return res + + +class DataPackage: + def __init__(self, spec, directory=None): + if isinstance(spec, DataPackage): + self.json = spec.json + self.dir = spec.dir + return + if isinstance(spec, dict): + # already a parsed JSON object + self.dir = pathlib.Path(directory or '.') + elif isinstance(spec, pathlib.Path): + self.dir = directory or spec.parent + spec = json.loads(spec.read_text(encoding='utf8')) + else: # assume a JSON formatted string + spec = json.loads(spec) + self.dir = pathlib.Path(directory or '.') + + self.json = spec + + def to_tablegroup(self, cls=None): + from csvw import TableGroup + + md = {} + # Package metadata: + md['dc:replaces'] = json.dumps(self.json) + + # version, + # image, + + for flprop, csvwprop in [ + ('id', 'dc:identifier'), + ('licenses', 'dc:license'), + ('title', 'dc:title'), + ('homepage', 'dcat:accessURL'), + ('description', 'dc:description'), + ('sources', 'dc:source'), + ('contributors', 'dc:contributor'), + ('profile', 'dc:conformsTo'), + ('keywords', 'dc:subject'), + ('created', 'dc:created'), + ]: + if flprop in self.json: + md[csvwprop] = self.json[flprop] + + if 'name' in self.json: + if 'id' not in self.json: + md['dc:identifier'] = self.json['name'] + elif 'title' not in self.json: + md['dc:title'] = self.json['name'] + + # Data Resource metadata: + resources = [rsc for rsc in self.json.get('resources', []) if 'path' in rsc] + resource_map = {rsc['name']: rsc['path'] for rsc in resources if 'name' in rsc} + for rsc in resources: + schema = rsc.get('schema') + if schema and \ + rsc.get('profile') == 'tabular-data-resource' and \ + rsc.get('scheme') == 'file' and \ + rsc.get('format') == 'csv': + # Table Schema: + md.setdefault('tables', []) + table = dict( + url=rsc['path'], + tableSchema=convert_table_schema(rsc.get('name'), schema, resource_map), + dialect=convert_dialect(rsc), + ) + md['tables'].append(table) + + cls = cls or TableGroup + res = cls.fromvalue(md) + res._fname = self.dir / 'csvw-metadata.json' + return res diff --git a/src/csvw/metadata.py b/src/csvw/metadata.py index 4c69354..9c71fe8 100644 --- a/src/csvw/metadata.py +++ b/src/csvw/metadata.py @@ -8,7 +8,6 @@ This module implements (partially) the W3C recommendation .. seealso:: https://www.w3.org/TR/tabular-metadata/ """ import io -import re import json import shutil import pathlib @@ -27,6 +26,7 @@ import uritemplate from . import utils from .datatypes import DATATYPES from .dsv import Dialect, UnicodeReaderWithLineNumber, UnicodeWriter +from .frictionless import DataPackage DEFAULT = object() @@ -38,11 +38,6 @@ __all__ = [ ] -# Level 1 variable names according to https://tools.ietf.org/html/rfc6570#section-2.3: -_varchar = r'([a-zA-Z0-9_]|\%[a-fA-F0-9]{2})' -_varname = re.compile('(' + _varchar + '([.]?' + _varchar + ')*)$') - - def log_or_raise(msg, log=None, level='warning', exception_cls=ValueError): if log: getattr(log, level)(msg) @@ -368,9 +363,7 @@ class Description(DescriptionBase): @attr.s class Column(Description): - name = attr.ib( - default=None, - validator=utils.attr_valid_re(_varname, nullable=True)) + name = attr.ib(default=None) suppressOutput = attr.ib(default=False) titles = attr.ib( default=None, @@ -783,6 +776,10 @@ class TableGroup(TableLike): for table in self.tables: table._parent = self + @classmethod + def from_frictionless_datapackage(cls, dp): + return DataPackage(dp).to_tablegroup(cls) + def read(self): """ Read all data of a TableGroup diff --git a/src/csvw/utils.py b/src/csvw/utils.py index 6cf85a0..c423732 100644 --- a/src/csvw/utils.py +++ b/src/csvw/utils.py @@ -30,26 +30,6 @@ def attr_asdict(obj, omit_defaults=True, omit_private=True): return res -def attr_valid_re(regex_or_pattern, nullable=False): - if hasattr(regex_or_pattern, 'match'): - pattern = regex_or_pattern - else: - pattern = re.compile(regex_or_pattern) - - msg = '{0} is not a valid {1}' - - if nullable: - def valid_re(instance, attribute, value): - if value is not None and pattern.match(value) is None: - raise ValueError(msg.format(value, attribute.name)) - else: - def valid_re(instance, attribute, value): - if pattern.match(value) is None: - raise ValueError(msg.format(value, attribute.name)) - - return valid_re - - class lazyproperty(object): """Non-data descriptor caching the computed result as instance attribute. >>> import itertools
cldf/csvw
f53756f7d2888d621bf745791e85979d1907a445
diff --git a/tests/fixtures/datapackage.json b/tests/fixtures/datapackage.json new file mode 100644 index 0000000..57c9221 --- /dev/null +++ b/tests/fixtures/datapackage.json @@ -0,0 +1,59 @@ +{ + "profile": "data-package", + "resources": [ + { + "path": "frictionless-data.csv", + "stats": { + "hash": "b36e8c21563ab32645052c11510bddb7", "bytes": 131, "fields": 3, "rows": 9 + }, + "control": {"newline": ""}, + "encoding": "utf-8", + "dialect": {"delimiter": "|", "commentChar": "#", "lineTerminator": "+\n"}, + "schema": { + "fields": [ + {"name": "FK", "type": "string"}, + {"name": "Year", "type": "integer", "rdfType": "http://example.com"}, + {"name": "Location name", "type": "string"}, + {"name": "Value", "type": "integer", "groupChar": "-"}, + {"name": "binary", "type": "string", "format": "binary"}, + {"name": "anyURI", "type": "string", "format": "uri"}, + {"name": "email", "type": "string", "format": "email"}, + {"name": "boolean", "type": "boolean", "trueValues": ["ja"], "falseValues": ["nein"]}, + {"name": "array", "type": "array", "description": "empty"}, + {"name": "geojson", "type": "geojson", "title": "a point"} + ], + "foreignKeys": [ + {"fields": ["FK"], "reference": {"resource": "tsv", "fields": ["class"]}} + ] + }, + "name": "test", + "profile": "tabular-data-resource", + "scheme": "file", + "format": "csv", + "hashing": "md5", + "compression": "no", + "compressionPath": "", + "query": {} + }, + { + "path": "tsv.txt", + "control": {"newline": ""}, + "encoding": "utf-8", + "dialect": {"delimiter": "\t"}, + "schema": { + "fields": [ + {"name": "class", "type": "string"}, + {"name": "a-name", "type": "string"} + ] + }, + "name": "tsv", + "profile": "tabular-data-resource", + "scheme": "file", + "format": "csv", + "hashing": "md5", + "compression": "no", + "compressionPath": "", + "query": {} + } + ] +} diff --git a/tests/fixtures/frictionless-data.csv b/tests/fixtures/frictionless-data.csv new file mode 100644 index 0000000..f931adf --- /dev/null +++ b/tests/fixtures/frictionless-data.csv @@ -0,0 +1,11 @@ +FK|Year|Location name|Value|binary|anyURI|email|boolean|array|geojson+ +a|2010||10-123|eA==|http://example.com|[email protected]|ja|[]|{}+ +a|2011||20||||nein||+ +c|2012||30||||||+ +#+ +e|2010|Urban|12||||||+ +e|2011|Urban|22||||||+ +e|2012|Urban|32||||||+ +e|2010|Rural|14||||||+ +e|2011|Rural|24||||||+ +x|2012|Rural|34||||||+ diff --git a/tests/test_frictionless.py b/tests/test_frictionless.py new file mode 100644 index 0000000..150bdf1 --- /dev/null +++ b/tests/test_frictionless.py @@ -0,0 +1,84 @@ +import json +import shutil +import pathlib + +import pytest + +from csvw.dsv import UnicodeWriter +from csvw import TableGroup +from csvw.frictionless import DataPackage + +FIXTURES = pathlib.Path(__file__).parent / 'fixtures' + + [email protected] +def tmpfixtures(tmpdir): + shutil.copytree(str(pathlib.Path(__file__).parent / 'fixtures'), str(tmpdir.join('fixtures'))) + return pathlib.Path(str(tmpdir)) / 'fixtures' + + [email protected] +def datafactory(tmpdir): + def make(fields, data): + p = pathlib.Path(str(tmpdir)) / 'datapackage.json' + with p.open(mode='wt') as f: + rsc = dict( + profile='tabular-data-resource', + scheme='file', + format='csv', + path='data.csv', + schema=dict(fields=fields), + ) + json.dump(dict(resources=[rsc]), f) + with UnicodeWriter(p.parent / 'data.csv') as w: + w.writerow([f['name'] for f in fields]) + w.writerows(data) + return p + return make + + +def test_DataPackage_init(): + dp = DataPackage(dict(resources=[], name='x')) + dp = DataPackage(dp) + assert dp.to_tablegroup().common_props['dc:identifier'] == 'x' + dp = DataPackage('{"resources": [], "name": "x", "id": "y"}') + assert dp.to_tablegroup().common_props['dc:identifier'] == 'y' + assert dp.to_tablegroup().common_props['dc:title'] == 'x' + + +def test_DataPackage_constraints(datafactory): + dp = datafactory([{'name': 'col', 'constraints': {'maxLength': 3}}], [['abcd']]) + with pytest.raises(ValueError): + _ = list(DataPackage(dp).to_tablegroup().tables[0]) + + dp = datafactory([{'name': 'col', 'constraints': {'pattern': '[a-z]{2}'}}], [['abcd']]) + with pytest.raises(ValueError): + _ = list(DataPackage(dp).to_tablegroup().tables[0]) + + dp = datafactory( + [{'name': 'col', 'type': 'year', 'constraints': {'pattern': '[2].*'}}], [['1990']]) + with pytest.raises(ValueError): + _ = list(DataPackage(dp).to_tablegroup().tables[0]) + + +def test_DataPackage(tmpfixtures): + dp = DataPackage(tmpfixtures / 'datapackage.json') + tg = dp.to_tablegroup() + rows = list(tg.tables[0]) + assert len(rows) == 9 + assert rows[-1]['Year'] == 2012 + assert rows[-1]['Location name'] == 'Rural' + with pytest.raises(ValueError): + tg.check_referential_integrity() + schema = tg.tables[0].tableSchema + for c in ['binary', 'anyURI']: + assert schema.columndict[c].datatype.base == c + assert rows[0]['boolean'] is True and rows[1]['boolean'] is False + assert rows[0]['Value'] == 10123 + assert list(rows[0].values())[-1] != '+', "custom line terminator must be stripped" + + tg.to_file(tmpfixtures / 'metadata.json') + tg = TableGroup.from_file(tmpfixtures / 'metadata.json') + rows = list(tg.tables[0]) + assert len(rows) == 9 + assert rows[-1]['Year'] == 2012 diff --git a/tests/test_metadata.py b/tests/test_metadata.py index c840947..7f461fb 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -29,12 +29,6 @@ def test_Link(): assert li.resolve(pathlib.Path('.')) == pathlib.Path('abc.csv') -def test_column_init(): - with pytest.raises(ValueError): - # column names mustn't start with a -! - csvw.Column(name='-abd') - - class TestColumnAccess(object): def test_get_column(self): @@ -279,6 +273,10 @@ class TestTableGroup(object): return _make_table_like( csvw.TableGroup, tmpdir, data=data, metadata=metadata, mdname='csv.txt-metadata.json') + def test_from_frictionless(self): + tg = csvw.TableGroup.from_frictionless_datapackage(FIXTURES / 'datapackage.json') + assert list(tg.tables[0]) + def test_iteritems_column_renaming(self, tmpdir): t = csvw.TableGroup.from_file(FIXTURES / 'test.tsv-metadata.json') items = list(t.tables[0]) diff --git a/tests/test_utils.py b/tests/test_utils.py index 20e88b0..0fc3956 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,14 +1,6 @@ -import pytest - from csvw import utils -def test_attr_valid_re(mocker): - validator = utils.attr_valid_re('[0-9]+') - with pytest.raises(ValueError): - validator(None, mocker.Mock(), 'x') - - def test_lazyproperty(): import itertools
Example of programmatically creating metadata from scratch Hello, I was wondering if it would be possible to provide an example of creating the metadata from scratch. My goal is to create a metadata file by programmatically examining a CSV file to determine the schema. No worries if this is out of scope for the library. Thank you!
0.0
f53756f7d2888d621bf745791e85979d1907a445
[ "tests/test_frictionless.py::test_DataPackage_init", "tests/test_frictionless.py::test_DataPackage_constraints", "tests/test_frictionless.py::test_DataPackage", "tests/test_metadata.py::test_URITemplate", "tests/test_metadata.py::test_Link", "tests/test_metadata.py::TestColumnAccess::test_get_column", "tests/test_metadata.py::TestDialect::test_doubleQuote", "tests/test_metadata.py::TestNaturalLanguage::test_string", "tests/test_metadata.py::TestNaturalLanguage::test_array", "tests/test_metadata.py::TestNaturalLanguage::test_object", "tests/test_metadata.py::TestNaturalLanguage::test_error", "tests/test_metadata.py::TestNaturalLanguage::test_serialize", "tests/test_metadata.py::TestColumn::test_read_rite_with_separator", "tests/test_metadata.py::TestColumn::test_read_required_empty_string", "tests/test_metadata.py::TestColumn::test_read_required_empty_string_no_null", "tests/test_metadata.py::TestColumn::test_reuse_datatype", "tests/test_metadata.py::test_Schema", "tests/test_metadata.py::TestLink::test_link", "tests/test_metadata.py::TestTable::test_roundtrip", "tests/test_metadata.py::TestTable::test_read_write", "tests/test_metadata.py::TestTable::test_iteritems_column_renaming", "tests/test_metadata.py::TestTable::test_unspecified_column_in_table_without_url", "tests/test_metadata.py::TestTableGroup::test_from_frictionless", "tests/test_metadata.py::TestTableGroup::test_iteritems_column_renaming", "tests/test_metadata.py::TestTableGroup::test_roundtrip", "tests/test_metadata.py::TestTableGroup::test_copy", "tests/test_metadata.py::TestTableGroup::test_write_all", "tests/test_metadata.py::TestTableGroup::test_all", "tests/test_metadata.py::TestTableGroup::test_separator", "tests/test_metadata.py::TestTableGroup::test_None_value_in_common_props", "tests/test_metadata.py::TestTableGroup::test_virtual_columns1", "tests/test_metadata.py::TestTableGroup::test_virtual_columns2", "tests/test_metadata.py::TestTableGroup::test_required_column1", "tests/test_metadata.py::TestTableGroup::test_write", "tests/test_metadata.py::TestTableGroup::test_spec_examples", "tests/test_metadata.py::TestTableGroup::test_foreign_keys", "tests/test_metadata.py::TestTableGroup::test_foreignkeys", "tests/test_metadata.py::TestTableGroup::test_foreignkeys_2", "tests/test_metadata.py::TestTableGroup::test_remote_schema", "tests/test_metadata.py::TestTableGroup::test_missing_data", "tests/test_metadata.py::test_zip_support", "tests/test_utils.py::test_lazyproperty", "tests/test_utils.py::test_normalize_name", "tests/test_utils.py::test_slug" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-05 13:39:02+00:00
apache-2.0
1,593
cldf__csvw-51
diff --git a/src/csvw/frictionless.py b/src/csvw/frictionless.py index eca4f22..2341419 100644 --- a/src/csvw/frictionless.py +++ b/src/csvw/frictionless.py @@ -125,6 +125,8 @@ def convert_table_schema(rsc_name, schema, resource_map): def convert_dialect(rsc): """ + Limitations: lineTerminator is not supported. + https://specs.frictionlessdata.io/csv-dialect/ """ d = rsc.get('dialect', {}) @@ -142,8 +144,6 @@ def convert_dialect(rsc): ]: if prop in d: res[prop] = d[prop] - if 'lineTerminator' in d: - res['lineTerminators'] = [d['lineTerminator']] if 'commentChar' in d: res['commentPrefix'] = d['commentChar'] return res diff --git a/src/csvw/metadata.py b/src/csvw/metadata.py index 9c71fe8..5d0dda6 100644 --- a/src/csvw/metadata.py +++ b/src/csvw/metadata.py @@ -8,6 +8,7 @@ This module implements (partially) the W3C recommendation .. seealso:: https://www.w3.org/TR/tabular-metadata/ """ import io +import re import json import shutil import pathlib @@ -17,7 +18,7 @@ import warnings import itertools import contextlib import collections -from urllib.parse import urljoin +from urllib.parse import urljoin, urlparse, urlunparse from urllib.request import urlopen import attr @@ -35,9 +36,14 @@ __all__ = [ 'Table', 'Column', 'ForeignKey', 'Link', 'NaturalLanguage', 'Datatype', + 'is_url', ] +def is_url(s): + return re.match(r'https?://', str(s)) + + def log_or_raise(msg, log=None, level='warning', exception_cls=ValueError): if log: getattr(log, level)(msg) @@ -171,7 +177,7 @@ class NaturalLanguage(collections.OrderedDict): class DescriptionBase(object): """Container for - common properties (see http://w3c.github.io/csvw/metadata/#common-properties) - - @-properies. + - @-properties. """ common_props = attr.ib(default=attr.Factory(dict)) @@ -538,6 +544,8 @@ class TableLike(Description): @classmethod def from_file(cls, fname): if not isinstance(fname, pathlib.Path): + if is_url(fname): + return cls.from_url(str(fname)) fname = pathlib.Path(fname) with json_open(str(fname)) as f: data = json.load(f) @@ -545,6 +553,16 @@ class TableLike(Description): res._fname = fname return res + @classmethod + def from_url(cls, url): + with io.TextIOWrapper(urlopen(url), encoding='utf8') as f: + data = json.load(f) + res = cls.fromvalue(data) + if 'base' not in res.at_props: + url = urlparse(url) + res.at_props['base'] = urlunparse((url.scheme, url.netloc, url.path, '', '', '')) + return res + def to_file(self, fname, omit_defaults=True): if not isinstance(fname, pathlib.Path): fname = pathlib.Path(fname) @@ -558,6 +576,9 @@ class TableLike(Description): """ We only support data in the filesystem, thus we make sure `base` is a `pathlib.Path`. """ + at_props = self._parent.at_props if self._parent else self.at_props + if 'base' in at_props: + return at_props['base'] return self._parent._fname.parent if self._parent else self._fname.parent @@ -682,15 +703,18 @@ class Table(TableLike): requiredcols.add(col.header) with contextlib.ExitStack() as stack: - handle = fname - fpath = pathlib.Path(fname) - if not fpath.exists(): - zipfname = fpath.parent.joinpath(fpath.name + '.zip') - if zipfname.exists(): - zipf = stack.enter_context(zipfile.ZipFile(str(zipfname))) - handle = io.TextIOWrapper( - zipf.open([n for n in zipf.namelist() if n.endswith(fpath.name)][0]), - encoding=dialect.encoding) + if is_url(fname): + handle = io.TextIOWrapper(urlopen(str(fname)), encoding=dialect.encoding) + else: + handle = fname + fpath = pathlib.Path(fname) + if not fpath.exists(): + zipfname = fpath.parent.joinpath(fpath.name + '.zip') + if zipfname.exists(): + zipf = stack.enter_context(zipfile.ZipFile(str(zipfname))) + handle = io.TextIOWrapper( + zipf.open([n for n in zipf.namelist() if n.endswith(fpath.name)][0]), + encoding=dialect.encoding) reader = stack.enter_context(UnicodeReaderWithLineNumber(handle, dialect=dialect)) reader = iter(reader)
cldf/csvw
76b503d5c049bbe6f136a3fea4202ae991cde300
diff --git a/tests/fixtures/datapackage.json b/tests/fixtures/datapackage.json index 57c9221..308a4f3 100644 --- a/tests/fixtures/datapackage.json +++ b/tests/fixtures/datapackage.json @@ -8,7 +8,7 @@ }, "control": {"newline": ""}, "encoding": "utf-8", - "dialect": {"delimiter": "|", "commentChar": "#", "lineTerminator": "+\n"}, + "dialect": {"delimiter": "|", "commentChar": "#", "lineTerminator": "\n"}, "schema": { "fields": [ {"name": "FK", "type": "string"}, diff --git a/tests/fixtures/frictionless-data.csv b/tests/fixtures/frictionless-data.csv index f931adf..1e40e59 100644 --- a/tests/fixtures/frictionless-data.csv +++ b/tests/fixtures/frictionless-data.csv @@ -1,11 +1,11 @@ -FK|Year|Location name|Value|binary|anyURI|email|boolean|array|geojson+ -a|2010||10-123|eA==|http://example.com|[email protected]|ja|[]|{}+ -a|2011||20||||nein||+ -c|2012||30||||||+ -#+ -e|2010|Urban|12||||||+ -e|2011|Urban|22||||||+ -e|2012|Urban|32||||||+ -e|2010|Rural|14||||||+ -e|2011|Rural|24||||||+ -x|2012|Rural|34||||||+ +FK|Year|Location name|Value|binary|anyURI|email|boolean|array|geojson +a|2010||10-123|eA==|http://example.com|[email protected]|ja|[]|{} +a|2011||20||||nein|| +c|2012||30|||||| +# +e|2010|Urban|12|||||| +e|2011|Urban|22|||||| +e|2012|Urban|32|||||| +e|2010|Rural|14|||||| +e|2011|Rural|24|||||| +x|2012|Rural|34|||||| diff --git a/tests/test_frictionless.py b/tests/test_frictionless.py index 150bdf1..4fbfea4 100644 --- a/tests/test_frictionless.py +++ b/tests/test_frictionless.py @@ -75,7 +75,6 @@ def test_DataPackage(tmpfixtures): assert schema.columndict[c].datatype.base == c assert rows[0]['boolean'] is True and rows[1]['boolean'] is False assert rows[0]['Value'] == 10123 - assert list(rows[0].values())[-1] != '+', "custom line terminator must be stripped" tg.to_file(tmpfixtures / 'metadata.json') tg = TableGroup.from_file(tmpfixtures / 'metadata.json') diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 7f461fb..fc85add 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -775,3 +775,12 @@ def test_zip_support(tmpdir): tg.write(out.parent / 'md.json', _zipped=True, **{'zipped.csv': res + res}) assert len(list(csvw.TableGroup.from_file(out.parent / 'md.json').tables[0])) == 4 + + +def test_from_url(mocker): + from io import BytesIO + mocker.patch( + 'csvw.metadata.urlopen', + lambda u: BytesIO(FIXTURES.joinpath(u.split('/')[-1]).read_bytes())) + t = csvw.Table.from_file('http://example.com/csv.txt-table-metadata.json') + assert len(list(t)) == 2
Add support for reading metadata and data from URLs
0.0
76b503d5c049bbe6f136a3fea4202ae991cde300
[ "tests/test_metadata.py::test_from_url" ]
[ "tests/test_frictionless.py::test_DataPackage_init", "tests/test_frictionless.py::test_DataPackage_constraints", "tests/test_frictionless.py::test_DataPackage", "tests/test_metadata.py::test_URITemplate", "tests/test_metadata.py::test_Link", "tests/test_metadata.py::TestColumnAccess::test_get_column", "tests/test_metadata.py::TestDialect::test_doubleQuote", "tests/test_metadata.py::TestNaturalLanguage::test_string", "tests/test_metadata.py::TestNaturalLanguage::test_array", "tests/test_metadata.py::TestNaturalLanguage::test_object", "tests/test_metadata.py::TestNaturalLanguage::test_error", "tests/test_metadata.py::TestNaturalLanguage::test_serialize", "tests/test_metadata.py::TestColumn::test_read_rite_with_separator", "tests/test_metadata.py::TestColumn::test_read_required_empty_string", "tests/test_metadata.py::TestColumn::test_read_required_empty_string_no_null", "tests/test_metadata.py::TestColumn::test_reuse_datatype", "tests/test_metadata.py::test_Schema", "tests/test_metadata.py::TestLink::test_link", "tests/test_metadata.py::TestTable::test_roundtrip", "tests/test_metadata.py::TestTable::test_read_write", "tests/test_metadata.py::TestTable::test_iteritems_column_renaming", "tests/test_metadata.py::TestTable::test_unspecified_column_in_table_without_url", "tests/test_metadata.py::TestTableGroup::test_from_frictionless", "tests/test_metadata.py::TestTableGroup::test_iteritems_column_renaming", "tests/test_metadata.py::TestTableGroup::test_roundtrip", "tests/test_metadata.py::TestTableGroup::test_copy", "tests/test_metadata.py::TestTableGroup::test_write_all", "tests/test_metadata.py::TestTableGroup::test_all", "tests/test_metadata.py::TestTableGroup::test_separator", "tests/test_metadata.py::TestTableGroup::test_None_value_in_common_props", "tests/test_metadata.py::TestTableGroup::test_virtual_columns1", "tests/test_metadata.py::TestTableGroup::test_virtual_columns2", "tests/test_metadata.py::TestTableGroup::test_required_column1", "tests/test_metadata.py::TestTableGroup::test_write", "tests/test_metadata.py::TestTableGroup::test_spec_examples", "tests/test_metadata.py::TestTableGroup::test_foreign_keys", "tests/test_metadata.py::TestTableGroup::test_foreignkeys", "tests/test_metadata.py::TestTableGroup::test_foreignkeys_2", "tests/test_metadata.py::TestTableGroup::test_remote_schema", "tests/test_metadata.py::TestTableGroup::test_missing_data", "tests/test_metadata.py::test_zip_support" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-08 14:49:55+00:00
apache-2.0
1,594
click-contrib__click-aliases-3
diff --git a/.travis.yml b/.travis.yml index 6144ff7..d4504af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,8 @@ install: script: - flake8 click_aliases examples tests setup.py -v --show-source - py.test tests --cov click_aliases --cov-report term-missing + - pip install 'click>6,<7' + - py.test tests --cov click_aliases --cov-report term-missing --cov-append after_success: - coveralls diff --git a/click_aliases/__init__.py b/click_aliases/__init__.py index 32e1f08..b49b0c8 100644 --- a/click_aliases/__init__.py +++ b/click_aliases/__init__.py @@ -5,6 +5,8 @@ import click +_click7 = click.__version__[0] >= '7' + class ClickAliasedGroup(click.Group): def __init__(self, *args, **kwargs): @@ -53,7 +55,13 @@ class ClickAliasedGroup(click.Group): def format_commands(self, ctx, formatter): rows = [] - for sub_command in self.list_commands(ctx): + + sub_commands = self.list_commands(ctx) + + max_len = max(len(cmd) for cmd in sub_commands) + limit = formatter.width - 6 - max_len + + for sub_command in sub_commands: cmd = self.get_command(ctx, sub_command) if cmd is None: continue @@ -62,8 +70,12 @@ class ClickAliasedGroup(click.Group): if sub_command in self._commands: aliases = ','.join(sorted(self._commands[sub_command])) sub_command = '{0} ({1})'.format(sub_command, aliases) - cmd_help = cmd.short_help or '' + if _click7: + cmd_help = cmd.get_short_help_str(limit) + else: + cmd_help = cmd.short_help or '' rows.append((sub_command, cmd_help)) + if rows: with formatter.section('Commands'): formatter.write_dl(rows) diff --git a/examples/foobar.py b/examples/foobar.py index bd70402..3de5fa2 100644 --- a/examples/foobar.py +++ b/examples/foobar.py @@ -1,4 +1,5 @@ import click + from click_aliases import ClickAliasedGroup diff --git a/examples/naval.py b/examples/naval.py index 66c22f0..ba82e50 100644 --- a/examples/naval.py +++ b/examples/naval.py @@ -1,4 +1,5 @@ import click + from click_aliases import ClickAliasedGroup diff --git a/tox.ini b/tox.ini index 1011ba9..52f509b 100644 --- a/tox.ini +++ b/tox.ini @@ -1,4 +1,10 @@ +[tox] +toxenv = py{27,34,35,36,36}-click{6,7} + [testenv] passenv = LANG -deps = pytest +deps = + click6: click>6,<7 + click7: click>=7,<8 + pytest commands = py.test
click-contrib/click-aliases
6fdb266540eab2e295363b6459e18cf110117fb3
diff --git a/tests/test_basic.py b/tests/test_basic.py index efbcbeb..077e6c0 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1,6 +1,8 @@ import click from click.testing import CliRunner -from click_aliases import ClickAliasedGroup + +from click_aliases import ClickAliasedGroup, _click7 + import pytest @@ -40,9 +42,9 @@ def test_foobar(runner): TEST_INVALID = """Usage: cli [OPTIONS] COMMAND [ARGS]... - +{} Error: No such command "bar". -""" +""".format('Try "cli --help" for help.\n' if _click7 else '') def test_invalid(runner): diff --git a/tests/test_foobar.py b/tests/test_foobar.py index c549561..fd6c4e6 100644 --- a/tests/test_foobar.py +++ b/tests/test_foobar.py @@ -1,6 +1,8 @@ import click from click.testing import CliRunner -from click_aliases import ClickAliasedGroup + +from click_aliases import ClickAliasedGroup, _click7 + import pytest @@ -41,9 +43,9 @@ def test_foobar(runner): TEST_INVALID = """Usage: cli [OPTIONS] COMMAND [ARGS]... - +{} Error: No such command "baz". -""" +""".format('Try "cli --help" for help.\n' if _click7 else '') def test_invalid(runner): diff --git a/tests/test_naval.py b/tests/test_naval.py index f4d41e7..35c23ff 100644 --- a/tests/test_naval.py +++ b/tests/test_naval.py @@ -1,6 +1,8 @@ import click from click.testing import CliRunner + from click_aliases import ClickAliasedGroup + import pytest
Broken with click 7 https://travis-ci.org/jayvdb/click-aliases/jobs/568251511 ``` runner = <click.testing.CliRunner object at 0x7fb65f97a550> def test_cli(runner): result = runner.invoke(cli) > assert result.output == TEST_CLI E AssertionError: assert 'Usage: cli [... ship (boat)\n' == 'Usage: cli [O...ages ships.\n' E Skipping 116 identical leading characters in diff, use -v to show E - ine (bomb) E - ship (boat) E + ine (bomb) Manages mines. E + ship (boat) Manages ships. tests/test_naval.py:88: AssertionError ________________________________ test_ship_help ________________________________ runner = <click.testing.CliRunner object at 0x7fb65f97b110> def test_ship_help(runner): for cmd in ['ship', 'boat']: result = runner.invoke(cli, [cmd]) > assert result.output == TEST_SHIP_HELP.format(cmd=cmd) E AssertionError: assert 'Usage: cli s...shoot (fire)\n' == 'Usage: cli sh...ire to X,Y.\n' E Skipping 134 identical leading characters in diff, use -v to show E - ,navigate) E - new (add,build,create) E - shoot (fire) E + ,navigate) Moves SHIP to the new location X,Y. E + new (add,build,create) Creates a new ship. E + shoot (fire) Makes SHIP fire to X,Y. ```
0.0
6fdb266540eab2e295363b6459e18cf110117fb3
[ "tests/test_basic.py::test_help", "tests/test_basic.py::test_foobar", "tests/test_foobar.py::test_help", "tests/test_foobar.py::test_foobar", "tests/test_naval.py::test_cli", "tests/test_naval.py::test_ship_help", "tests/test_naval.py::test_ship_move" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-06 10:55:25+00:00
mit
1,595
click-contrib__sphinx-click-94
diff --git a/sphinx_click/ext.py b/sphinx_click/ext.py index be645ab..4441588 100644 --- a/sphinx_click/ext.py +++ b/sphinx_click/ext.py @@ -73,21 +73,20 @@ def _get_help_record(opt): extras = [] - if opt.default is not None and opt.show_default: - if isinstance(opt.show_default, str): - # Starting from Click 7.0 this can be a string as well. This is - # mostly useful when the default is not a constant and - # documentation thus needs a manually written string. - extras.append(':default: %s' % opt.show_default) - else: - extras.append( - ':default: %s' - % ( - ', '.join(str(d) for d in opt.default) - if isinstance(opt.default, (list, tuple)) - else opt.default, - ) + if isinstance(opt.show_default, str): + # Starting from Click 7.0 show_default can be a string. This is + # mostly useful when the default is not a constant and + # documentation thus needs a manually written string. + extras.append(':default: %s' % opt.show_default) + elif opt.default is not None and opt.show_default: + extras.append( + ':default: %s' + % ( + ', '.join(str(d) for d in opt.default) + if isinstance(opt.default, (list, tuple)) + else opt.default, ) + ) if isinstance(opt.type, click.Choice): extras.append(':options: %s' % ' | '.join(str(x) for x in opt.type.choices))
click-contrib/sphinx-click
b9ce52d554c6a6fcf808cd77fc561954a8b9833f
diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 3a959d9..0cc8651 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -177,6 +177,10 @@ class CommandTestCase(unittest.TestCase): multiple=True, show_default=True, ) + @click.option( + '--only-show-default', + show_default="Some default computed at runtime!", + ) def foobar(bar): """A sample command.""" pass @@ -207,6 +211,10 @@ class CommandTestCase(unittest.TestCase): .. option:: --group <group> :default: ('foo', 'bar') + + .. option:: --only-show-default <only_show_default> + + :default: Some default computed at runtime! """ ).lstrip(), '\n'.join(output),
Display `show_default` string even when `default=None` # Current behavior The option ```python @click.option('--foo', show_default='mydefault') ``` will not have a default documented # Expected behavior The text `mydefault` is documented as the default value for this option. # What now? Looking at the code [here](https://github.com/click-contrib/sphinx-click/blob/6aeee375067483337b5cfda98233d4fb1a1addb1/sphinx_click/ext.py#L76), the fix seems relatively straightforward. I'd like to submit a PR if you agree :)
0.0
b9ce52d554c6a6fcf808cd77fc561954a8b9833f
[ "tests/test_formatter.py::CommandTestCase::test_defaults" ]
[ "tests/test_formatter.py::CommandTestCase::test_basic_parameters", "tests/test_formatter.py::CommandTestCase::test_help_epilog", "tests/test_formatter.py::CommandTestCase::test_hidden", "tests/test_formatter.py::CommandTestCase::test_no_line_wrapping_epilog", "tests/test_formatter.py::CommandTestCase::test_no_parameters", "tests/test_formatter.py::GroupTestCase::test_basic_parameters", "tests/test_formatter.py::GroupTestCase::test_no_parameters", "tests/test_formatter.py::NestedCommandsTestCase::test_nested_full", "tests/test_formatter.py::NestedCommandsTestCase::test_nested_none", "tests/test_formatter.py::NestedCommandsTestCase::test_nested_short", "tests/test_formatter.py::CommandFilterTestCase::test_no_commands", "tests/test_formatter.py::CommandFilterTestCase::test_order_of_commands", "tests/test_formatter.py::CustomMultiCommandTestCase::test_basics", "tests/test_formatter.py::CustomMultiCommandTestCase::test_hidden", "tests/test_formatter.py::CommandCollectionTestCase::test_basics" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-02-01 18:46:00+00:00
mit
1,596
clld__clldutils-27
diff --git a/clldutils/badge.py b/clldutils/badge.py index 14829b5..a74fca1 100644 --- a/clldutils/badge.py +++ b/clldutils/badge.py @@ -19,12 +19,8 @@ class Colors(object): blue = 'blue' -def badge(subject, status, color, fmt='svg', markdown=True, **kw): - query = '' - if kw: - query = '?' + urlencode(kw) +def badge(subject, status, color, fmt='svg', markdown=True, label=None, **kw): + label = label or ': '.join([subject, status]) url = 'https://img.shields.io/badge/{0}-{1}-{2}.{3}{4}'.format( - quote(subject), quote(status), color, fmt, query) - if markdown: - return '![{0}]({1} "{0}")'.format(': '.join([subject, status]), url) - return url + quote(subject), quote(status), color, fmt, '?' + urlencode(kw) if kw else '') + return '![{0}]({1} "{0}")'.format(label, url) if markdown else url
clld/clldutils
54679df634b93870ea9fec722a56b75e72017645
diff --git a/clldutils/tests/test_badge.py b/clldutils/tests/test_badge.py index 272560c..66bcabb 100644 --- a/clldutils/tests/test_badge.py +++ b/clldutils/tests/test_badge.py @@ -12,3 +12,4 @@ def test_badge(): '![cov: 20%](https://img.shields.io/badge/cov-20%25-orange.svg "cov: 20%")' assert _badge(markdown=False, style='plastic') == \ 'https://img.shields.io/badge/cov-20%25-orange.svg?style=plastic' + assert '[abc]' in badge('subject', 'status', 'color', label='abc')
The `badge` function should be more flexible `badge.badge` should accept all atomic parts of the label/URL it creates as input argument; such that it exposes all functionality of the `shields.io` service.
0.0
54679df634b93870ea9fec722a56b75e72017645
[ "clldutils/tests/test_badge.py::test_badge" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2017-01-11 09:11:55+00:00
apache-2.0
1,597
closeio__freezefrog-3
diff --git a/freezefrog/__init__.py b/freezefrog/__init__.py index 44a232a..60463f3 100644 --- a/freezefrog/__init__.py +++ b/freezefrog/__init__.py @@ -47,6 +47,12 @@ class FakeDateTime(with_metaclass(FakeDateTimeMeta, real_datetime)): cls._start = real_datetime.utcnow() return (real_datetime.utcnow() - cls._start) + cls.dt + @classmethod + def now(cls, *args, **kwargs): + raise NotImplementedError( + '{}.now() is not implemented yet'.format(cls.__name__) + ) + class FakeFixedDateTime(FakeDateTime): @classmethod
closeio/freezefrog
c7089ad8d9b3900f2528a94b43bfc842f62023c9
diff --git a/tests/__init__.py b/tests/__init__.py index dd74be2..093fc1c 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -27,3 +27,9 @@ class FreezeFrogTestCase(unittest.TestCase): end = datetime.datetime(2014, 1, 1, 0, 0, 1) self.assertTrue(start < dt < end) self.assertTrue(1388534400 < time.time() < 1388534401) + + def test_now(self): + regular_now = datetime.datetime.now() + self.assertTrue(regular_now) + with FreezeTime(datetime.datetime(2014, 1, 1)): + self.assertRaises(NotImplementedError, datetime.datetime.now)
FreezeFrog should also mock datetime.datetime.now FreezeFrog should raise an exception when datetime.datetime.now() is used without a TZ instead of not mocking it at all.
0.0
c7089ad8d9b3900f2528a94b43bfc842f62023c9
[ "tests/__init__.py::FreezeFrogTestCase::test_now" ]
[ "tests/__init__.py::FreezeFrogTestCase::test_freeze", "tests/__init__.py::FreezeFrogTestCase::test_freeze_tick" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-06-29 19:12:56+00:00
mit
1,598
closeio__limitlion-10
diff --git a/limitlion/throttle.lua b/limitlion/throttle.lua index f2aa58c..201832d 100644 --- a/limitlion/throttle.lua +++ b/limitlion/throttle.lua @@ -106,10 +106,12 @@ local window -- Lookup throttle knob settings local knobs_key = name .. ":knobs" +-- Use +-- HMSET <knobs_key> rps <rps> burst <burst> window <window> +-- to manually override the setting for any throttle. local knobs = redis.call("HMGET", knobs_key, "rps", "burst", "window") if knobs[1] == false then -- Set defaults if knobs hash is not found - redis.call("HMSET", knobs_key, "rps", default_rps, "burst", default_burst, "window", default_window) rps = tonumber(default_rps) burst = tonumber(default_burst) window = tonumber(default_window)
closeio/limitlion
2d36d9a4b864b3d8bb1fee6c3a6fb5166c80d694
diff --git a/tests/test_throttle.py b/tests/test_throttle.py index fe85319..8d89ad0 100644 --- a/tests/test_throttle.py +++ b/tests/test_throttle.py @@ -278,7 +278,8 @@ class TestThrottle(): self._freeze_redis_time(start_time, 0) - self._fake_work(throttle_name, 5, 2, 6) + limitlion.throttle_set(throttle_name, 5, 2, 6) + self._fake_work(throttle_name) tokens, refreshed, rps, burst, window = \ limitlion.throttle_get(throttle_name) assert int(tokens) == 59
Consider not setting defaults in Redis This line can probably be removed so that the defaults used in Python would always be used unless the Redis `:knobs` key was created. Can't think of a reason that the defaults need to exist in Redis. https://github.com/closeio/limitlion/blob/e6705996a2ee5ea87779689feb2e42d084424268/limitlion/throttle.lua#L112
0.0
2d36d9a4b864b3d8bb1fee6c3a6fb5166c80d694
[ "tests/test_throttle.py::TestThrottleNotConfigured::test_not_configured" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-12-20 22:30:52+00:00
mit
1,599
cloud-custodian__cloud-custodian-7826
diff --git a/c7n/filters/metrics.py b/c7n/filters/metrics.py index 9d89dd9d0..2e3760adc 100644 --- a/c7n/filters/metrics.py +++ b/c7n/filters/metrics.py @@ -3,6 +3,8 @@ """ CloudWatch Metrics suppport for resources """ +import re + from collections import namedtuple from concurrent.futures import as_completed from datetime import datetime, timedelta @@ -76,8 +78,7 @@ class MetricsFilter(Filter): 'patternProperties': { '^.*$': {'type': 'string'}}}, # Type choices - 'statistics': {'type': 'string', 'enum': [ - 'Average', 'Sum', 'Maximum', 'Minimum', 'SampleCount']}, + 'statistics': {'type': 'string'}, 'days': {'type': 'number'}, 'op': {'type': 'string', 'enum': list(OPERATORS.keys())}, 'value': {'type': 'number'}, @@ -125,11 +126,19 @@ class MetricsFilter(Filter): 'workspaces': 'AWS/WorkSpaces', } + standard_stats = {'Average', 'Sum', 'Maximum', 'Minimum', 'SampleCount'} + extended_stats_re = re.compile(r'^p\d{1,3}\.{0,1}\d{0,1}$') + def __init__(self, data, manager=None): super(MetricsFilter, self).__init__(data, manager) self.days = self.data.get('days', 14) def validate(self): + stats = self.data.get('statistics', 'Average') + if stats not in self.standard_stats and not self.extended_stats_re.match(stats): + raise PolicyValidationError( + "metrics filter statistics method %s not supported" % stats) + if self.days > 455: raise PolicyValidationError( "metrics filter days value (%s) cannot exceed 455" % self.days) @@ -230,15 +239,23 @@ class MetricsFilter(Filter): # means multiple filters within a policy using the same metric # across different periods or dimensions would be problematic. key = "%s.%s.%s.%s" % (self.namespace, self.metric, self.statistics, str(self.days)) + + params = dict( + Namespace=self.namespace, + MetricName=self.metric, + StartTime=self.start, + EndTime=self.end, + Period=self.period, + Dimensions=dimensions + ) + + stats_key = (self.statistics in self.standard_stats + and 'Statistics' or 'ExtendedStatistics') + params[stats_key] = [self.statistics] + if key not in collected_metrics: collected_metrics[key] = client.get_metric_statistics( - Namespace=self.namespace, - MetricName=self.metric, - Statistics=[self.statistics], - StartTime=self.start, - EndTime=self.end, - Period=self.period, - Dimensions=dimensions)['Datapoints'] + **params)['Datapoints'] # In certain cases CloudWatch reports no data for a metric. # If the policy specifies a fill value for missing data, add diff --git a/c7n/resources/appelb.py b/c7n/resources/appelb.py index a310e05cf..281b89142 100644 --- a/c7n/resources/appelb.py +++ b/c7n/resources/appelb.py @@ -338,7 +338,7 @@ class WafV2Enabled(Filter): state_map[arn] = True continue state_map[arn] = False - return [r for r in resources if state_map[r[arn_key]] == state] + return [r for r in resources if r[arn_key] in state_map and state_map[r[arn_key]] == state] @AppELB.action_registry.register('set-waf')
cloud-custodian/cloud-custodian
92b94b8ebc82307be5717894b6a2712f9c7e207c
diff --git a/tests/test_ebs.py b/tests/test_ebs.py index 18ea04b3f..07fd6f298 100644 --- a/tests/test_ebs.py +++ b/tests/test_ebs.py @@ -833,6 +833,29 @@ class EbsFaultToleranceTest(BaseTest): class PiopsMetricsFilterTest(BaseTest): + def test_metrics_validation(self): + policy = self.load_policy( + { + "name": "ebs-metrics-test", + "resource": "ebs", + "filters": [{ + "type": "metrics", + "name": "VOlumeConsumedReadWriteOps", + "value": 50, + "op": "gt"}]}) + metrics = policy.resource_manager.filters[0] + metrics.data['statistics'] = 'p99' + metrics.validate() + metrics.data['statistics'] = 'p99.5' + metrics.validate() + metrics.data['statistics'] = 'pabc' + try: + metrics.validate() + except PolicyValidationError: + pass + else: + self.fail() + def test_ebs_metrics_percent_filter(self): session = self.replay_flight_data("test_ebs_metrics_percent_filter") policy = self.load_policy(
Support percentile statistics in CloudWatch metrics filter ### Describe the feature I would like to be able to use percentile statistics (like p99) in the [AWS metrics filter](https://cloudcustodian.io/docs/aws/resources/aws-common-filters.html?highlight=metric#metrics). For example, I want to be able to write a rule like ```yaml policies: - name: ec2-underutilized resource: ec2 filters: - type: metrics name: CPUUtilization statistics: p99 period: 86400 days: 7 value: 1 op: less-than ``` to find EC2 instances where the 99th percentile CPU usage is less than 1 percent. The [CloudWatch:GetMetricStatistics API](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html) supports an `ExtendedStatistics` option for requesting percentile statistics, so I think it should be technically possible to support this. ### Extra information or context _No response_
0.0
92b94b8ebc82307be5717894b6a2712f9c7e207c
[ "tests/test_ebs.py::PiopsMetricsFilterTest::test_metrics_validation" ]
[ "tests/test_ebs.py::SnapshotQueryParse::test_invalid_query", "tests/test_ebs.py::SnapshotQueryParse::test_query", "tests/test_ebs.py::SnapshotErrorHandler::test_get_bad_snapshot_malformed", "tests/test_ebs.py::SnapshotErrorHandler::test_get_bad_snapshot_notfound", "tests/test_ebs.py::SnapshotErrorHandler::test_get_bad_volume_malformed", "tests/test_ebs.py::SnapshotErrorHandler::test_get_bad_volume_notfound", "tests/test_ebs.py::SnapshotErrorHandler::test_remove_snapshot", "tests/test_ebs.py::SnapshotErrorHandler::test_snapshot_copy_related_tags_missing_volumes", "tests/test_ebs.py::SnapshotErrorHandler::test_tag_error", "tests/test_ebs.py::SnapshotAccessTest::test_snapshot_access", "tests/test_ebs.py::SnapshotDetachTest::test_volume_detach", "tests/test_ebs.py::SnapshotCopyTest::test_snapshot_copy", "tests/test_ebs.py::SnapshotAmiSnapshotTest::test_snapshot_ami_snapshot_filter", "tests/test_ebs.py::SnapshotUnusedTest::test_snapshot_unused", "tests/test_ebs.py::SnapshotTrimTest::test_snapshot_trim", "tests/test_ebs.py::SnapshotSetPermissions::test_add", "tests/test_ebs.py::SnapshotSetPermissions::test_matched", "tests/test_ebs.py::SnapshotSetPermissions::test_reset", "tests/test_ebs.py::SnapshotVolumeFilter::test_ebs_volume_filter", "tests/test_ebs.py::AttachedInstanceTest::test_ebs_instance_filter", "tests/test_ebs.py::ResizeTest::test_resize_action", "tests/test_ebs.py::ResizeTest::test_resize_filter", "tests/test_ebs.py::CopyInstanceTagsTest::test_copy_instance_tags", "tests/test_ebs.py::VolumePostFindingTest::test_volume_post_finding", "tests/test_ebs.py::VolumeSnapshotTest::test_volume_snapshot", "tests/test_ebs.py::VolumeSnapshotTest::test_volume_snapshot_copy_tags", "tests/test_ebs.py::VolumeSnapshotTest::test_volume_snapshot_copy_volume_tags", "tests/test_ebs.py::VolumeSnapshotTest::test_volume_snapshot_default_description", "tests/test_ebs.py::VolumeSnapshotTest::test_volume_snapshot_description", "tests/test_ebs.py::VolumeDeleteTest::test_volume_delete_force", "tests/test_ebs.py::EncryptExtantVolumesTest::test_encrypt_volumes", "tests/test_ebs.py::TestKmsAlias::test_ebs_kms_alias", "tests/test_ebs.py::EbsFaultToleranceTest::test_ebs_fault_tolerant", "tests/test_ebs.py::EbsFaultToleranceTest::test_ebs_non_fault_tolerant", "tests/test_ebs.py::PiopsMetricsFilterTest::test_ebs_metrics_percent_filter", "tests/test_ebs.py::HealthEventsFilterTest::test_ebs_health_events_filter" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-03 12:56:35+00:00
apache-2.0
1,600
cloud-custodian__cloud-custodian-7832
diff --git a/c7n/policy.py b/c7n/policy.py index f3cb71f34..155517ce8 100644 --- a/c7n/policy.py +++ b/c7n/policy.py @@ -24,6 +24,7 @@ from c7n.provider import clouds, get_resource_class from c7n import deprecated, utils from c7n.version import version from c7n.query import RetryPageIterator +from c7n.varfmt import VarFormat log = logging.getLogger('c7n.policy') @@ -1231,7 +1232,9 @@ class Policy: Updates the policy data in-place. """ # format string values returns a copy - updated = utils.format_string_values(self.data, **variables) + var_fmt = VarFormat() + updated = utils.format_string_values( + self.data, formatter=var_fmt.format, **variables) # Several keys should only be expanded at runtime, perserve them. if 'member-role' in updated.get('mode', {}): diff --git a/c7n/utils.py b/c7n/utils.py index 3c0acf111..65c4ffb51 100644 --- a/c7n/utils.py +++ b/c7n/utils.py @@ -580,7 +580,7 @@ def set_value_from_jmespath(source, expression, value, is_first=True): source[current_key] = value -def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwargs): +def format_string_values(obj, err_fallback=(IndexError, KeyError), formatter=None, *args, **kwargs): """ Format all string values in an object. Return the updated object @@ -588,16 +588,19 @@ def format_string_values(obj, err_fallback=(IndexError, KeyError), *args, **kwar if isinstance(obj, dict): new = {} for key in obj.keys(): - new[key] = format_string_values(obj[key], *args, **kwargs) + new[key] = format_string_values(obj[key], formatter=formatter, *args, **kwargs) return new elif isinstance(obj, list): new = [] for item in obj: - new.append(format_string_values(item, *args, **kwargs)) + new.append(format_string_values(item, formatter=formatter, *args, **kwargs)) return new elif isinstance(obj, str): try: - return obj.format(*args, **kwargs) + if formatter: + return formatter(obj, *args, **kwargs) + else: + return obj.format(*args, **kwargs) except err_fallback: return obj else: diff --git a/c7n/varfmt.py b/c7n/varfmt.py new file mode 100644 index 000000000..bcf3c7c1b --- /dev/null +++ b/c7n/varfmt.py @@ -0,0 +1,98 @@ +from string import Formatter + + +class VarFormat(Formatter): + """Behaves exactly like the stdlib formatter, with one additional behavior. + + when a string has no format_spec and only contains a single expression, + retain the type of the source object. + + inspired by https://pypyr.io/docs/substitutions/format-string/ + """ + + def _vformat( + self, format_string, args, kwargs, used_args, recursion_depth, auto_arg_index=0 + ): + # This is mostly verbatim from stdlib format.Formatter._vformat + # https://github.com/python/cpython/blob/main/Lib/string.py + # + # we have to copy alot of std logic to override the str cast + + if recursion_depth < 0: + raise ValueError('Max string recursion exceeded') + result = [] + for literal_text, field_name, format_spec, conversion in self.parse( + format_string + ): + + # output the literal text + if literal_text: + result.append((literal_text, True, None)) + + # if there's a field, output it + if field_name is not None: + # this is some markup, find the object and do + # the formatting + + # handle arg indexing when empty field_names are given. + if field_name == '': + if auto_arg_index is False: + raise ValueError( + 'cannot switch from manual field ' + 'specification to automatic field ' + 'numbering' + ) + field_name = str(auto_arg_index) + auto_arg_index += 1 + elif field_name.isdigit(): + if auto_arg_index: + raise ValueError( + 'cannot switch from manual field ' + 'specification to automatic field ' + 'numbering' + ) + # disable auto arg incrementing, if it gets + # used later on, then an exception will be raised + auto_arg_index = False + + # given the field_name, find the object it references + # and the argument it came from + obj, arg_used = self.get_field(field_name, args, kwargs) + used_args.add(arg_used) + + # do any conversion on the resulting object + obj = self.convert_field(obj, conversion) + + # expand the format spec, if needed + format_spec, auto_arg_index = self._vformat( + format_spec, + args, + kwargs, + used_args, + recursion_depth - 1, + auto_arg_index=auto_arg_index, + ) + + # defer format + result.append((obj, False, format_spec)) + + # if input is a single expression (ie. '{expr}' don't cast + # source to string. + if len(result) == 1: + obj, is_literal, format_spec = result[0] + if is_literal: + return obj, auto_arg_index + if format_spec: + return self.format_field(obj, format_spec), auto_arg_index + else: + return obj, auto_arg_index + else: + return ( + ''.join( + [ + obj if is_literal else self.format_field(obj, format_spec) + for obj, is_literal, format_spec in result + ] + ), + auto_arg_index, + )
cloud-custodian/cloud-custodian
772f5461ac851a1b4ad4b1e8e82068d50c3270bc
diff --git a/tests/test_varfmt.py b/tests/test_varfmt.py new file mode 100644 index 000000000..0bb9a9271 --- /dev/null +++ b/tests/test_varfmt.py @@ -0,0 +1,78 @@ +import pytest + +from c7n.varfmt import VarFormat +from c7n.utils import parse_date, format_string_values + + +def test_format_mixed(): + assert VarFormat().format("{x} abc {Y}", x=2, Y='a') == '2 abc a' + + +def test_format_pass_list(): + assert VarFormat().format("{x}", x=[1, 2, 3]) == [1, 2, 3] + + +def test_format_pass_int(): + assert VarFormat().format("{x}", x=2) == 2 + + +def test_format_pass_empty(): + assert VarFormat().format("{x}", x=[]) == [] + assert VarFormat().format("{x}", x=None) is None + assert VarFormat().format("{x}", x={}) == {} + assert VarFormat().format("{x}", x=0) == 0 + + +def test_format_string_values_empty(): + formatter = VarFormat().format + assert format_string_values({'a': '{x}'}, x=None, formatter=formatter) == { + 'a': None + } + assert format_string_values({'a': '{x}'}, x={}, formatter=formatter) == {'a': {}} + assert format_string_values({'a': '{x}'}, x=[], formatter=formatter) == {'a': []} + assert format_string_values({'a': '{x}'}, x=0, formatter=formatter) == {'a': 0} + + +def test_format_manual_to_auto(): + # coverage check for stdlib impl behavior + with pytest.raises(ValueError) as err: + VarFormat().format("{0} {}", 1, 2) + assert str(err.value) == ( + 'cannot switch from manual field specification to automatic field numbering' + ) + + +def test_format_auto_to_manual(): + # coverage check for stdlib impl behavior + with pytest.raises(ValueError) as err: + VarFormat().format('{} {1}', 'a', 'b') + assert str(err.value) == ( + 'cannot switch from manual field specification to automatic field numbering' + ) + + +def test_format_date_fmt(): + d = parse_date("2018-02-02 12:00") + assert VarFormat().format("{:%Y-%m-%d}", d, "2018-02-02") + assert VarFormat().format("{}", d) == d + + +def test_load_policy_var_retain_type(test): + p = test.load_policy( + { + 'name': 'x', + 'resource': 'aws.sqs', + 'filters': [ + {'type': 'value', 'key': 'why', 'op': 'in', 'value': "{my_list}"}, + {'type': 'value', 'key': 'why_not', 'value': "{my_int}"}, + {'key': "{my_date:%Y-%m-%d}"}, + ], + } + ) + + p.expand_variables( + dict(my_list=[1, 2, 3], my_int=22, my_date=parse_date('2022-02-01 12:00')) + ) + test.assertJmes('filters[0].value', p.data, [1, 2, 3]) + test.assertJmes('filters[1].value', p.data, 22) + test.assertJmes('filters[2].key', p.data, "2022-02-01")
Define and use of integer variables (YAML-files) - c7n-org ### Describe the bug I am not able to use defined variables as integer values in policy files. The solution that was provided here https://github.com/cloud-custodian/cloud-custodian/issues/6734#issuecomment-867604128 is not working: "{min-size}" --> "Parameter validation failed:\nInvalid type for parameter MinSize, value: 0, type: <class 'str'>, valid types: <class 'int'>" {min-size} --> "Parameter validation failed:\nInvalid type for parameter MinSize, value: {'min-size': None}, type: <class 'dict'>, valid types: <class 'int'>" ### What did you expect to happen? That the value pasted as integer. ### Cloud Provider Amazon Web Services (AWS) ### Cloud Custodian version and dependency information ```shell 0.9.17 ``` ### Policy ```shell policies: - name: asg-power-off-working-hours resource: asg mode: type: periodic schedule: "{lambda-schedule}" role: "{asg-lambda-role}" filters: - type: offhour actions: - type: resize min-size: "{asg_min_size}" max-size: "{asg_max_size}" desired-size: "{asg_desired_size}" save-options-tag: OffHoursPrevious ``` ### Relevant log/traceback output ```shell "{asg_min_size}" --> "Parameter validation failed:\nInvalid type for parameter MinSize, value: 0, type: <class 'str'>, valid types: <class 'int'>" {asg_min_size} --> "Parameter validation failed:\nInvalid type for parameter MinSize, value: {'min-size': None}, type: <class 'dict'>, valid types: <class 'int'>" ``` ### Extra information or context I saw that there is the field "value_type" for the filter section, but it looks like it can’t be used in the action section.
0.0
772f5461ac851a1b4ad4b1e8e82068d50c3270bc
[ "tests/test_varfmt.py::test_format_mixed", "tests/test_varfmt.py::test_format_pass_list", "tests/test_varfmt.py::test_format_pass_int", "tests/test_varfmt.py::test_format_pass_empty", "tests/test_varfmt.py::test_format_string_values_empty", "tests/test_varfmt.py::test_format_manual_to_auto", "tests/test_varfmt.py::test_format_auto_to_manual", "tests/test_varfmt.py::test_format_date_fmt", "tests/test_varfmt.py::test_load_policy_var_retain_type" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-04 09:45:51+00:00
apache-2.0
1,601
cloud-custodian__cloud-custodian-7975
diff --git a/c7n/utils.py b/c7n/utils.py index 500795674..0ca7a876f 100644 --- a/c7n/utils.py +++ b/c7n/utils.py @@ -213,6 +213,8 @@ class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() + if isinstance(obj, FormatDate): + return obj.datetime.isoformat() return json.JSONEncoder.default(self, obj)
cloud-custodian/cloud-custodian
63bed288fc0deeb144c9cffc2a10b56977d4539b
diff --git a/tests/test_utils.py b/tests/test_utils.py index 0722f45a6..163eb5ad1 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -224,6 +224,10 @@ class UtilTest(BaseTest): self.assertEqual("{:+5M%M}".format(utils.FormatDate(d)), "05") + self.assertEqual(json.dumps(utils.FormatDate(d), + cls=utils.DateTimeEncoder, indent=2), + '"2018-02-02T12:00:00"') + def test_group_by(self): items = [{}, {"Type": "a"}, {"Type": "a"}, {"Type": "b"}] self.assertEqual(list(utils.group_by(items, "Type").keys()), [None, "a", "b"])
"{now}" Generating Exception When Running With 0.9.19 ### Describe the bug We utilize a policy to track Cloud Custodian evaluation of resources, essentially to give a buffer upstream before an action is taken again. To track this, we use the `{now}` clause as a value for a tracking tag. See attached policy. When running this policy with v0.9.19, a JSON-related exception is generated. This behavior **does not** occur when running with 0.9.18, so it appears to be caused by a change in 0.9.19 specifically. ### What did you expect to happen? C7n runs as expected, without generating an exception. ### Cloud Provider Amazon Web Services (AWS) ### Cloud Custodian version and dependency information ```shell Custodian: 0.9.19 Python: 3.9.13 (main, May 24 2022, 21:28:31) [Clang 13.1.6 (clang-1316.0.21.2)] Platform: posix.uname_result(sysname='Darwin', nodename='jcarlson-pro', release='21.6.0', version='Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64', machine='x86_64') Using venv: True Docker: False Installed: PyYAML==6.0 Pygments==2.13.0 argcomplete==2.0.0 attrs==22.1.0 aws-xray-sdk==2.10.0 bleach==5.0.1 boto3==1.24.87 botocore==1.27.87 certifi==2022.9.24 charset-normalizer==2.1.1 click==8.1.3 colorama==0.4.5 coverage==6.5.0 docutils==0.17.1 execnet==1.9.0 flake8==3.9.2 freezegun==1.2.2 idna==3.4 importlib-metadata==4.13.0 importlib-resources==5.9.0 iniconfig==1.1.1 jaraco-classes==3.2.3 jaraco.classes==3.2.3 jmespath==1.0.1 jsonpatch==1.32 jsonpointer==2.3 jsonschema==4.16.0 keyring==23.9.3 mccabe==0.6.1 mock==4.0.3 more-itertools==8.14.0 multidict==6.0.2 packaging==21.3 pkginfo==1.8.3 pkgutil-resolve-name==1.3.10 placebo==0.9.0 pluggy==1.0.0 portalocker==2.5.1 psutil==5.9.2 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 pygments==2.13.0 pyparsing==3.0.9 pyrsistent==0.18.1 pytest==7.1.3 pytest-cov==3.0.0 pytest-forked==1.4.0 pytest-recording==0.12.1 pytest-sugar==0.9.5 pytest-terraform==0.6.4 pytest-xdist==2.5.0 python-dateutil==2.8.2 pyyaml==6.0 readme-renderer==37.2 requests==2.28.1 requests-toolbelt==0.9.1 rfc3986==2.0.0 s3transfer==0.6.0 six==1.16.0 tabulate==0.8.10 termcolor==2.0.1 tomli==2.0.1 tqdm==4.64.1 twine==3.8.0 typing-extensions==4.3.0 urllib3==1.26.12 vcrpy==4.2.1 webencodings==0.5.1 wrapt==1.14.1 yarl==1.8.1 zipp==3.8.1 ``` ### Policy ```shell - name: update-mfa-for-user-accts-action description: | If needed, update the last evaluation timestamp for the MFA enforcement check. resource: iam-user conditions: - region: us-east-1 - type: value key: account_id value_type: integer value: *target_account filters: - <<: *exception_tag - type: value key: tag:user_acct_mfa op: gt value: 14 value_type: age actions: - type: tag key: "user_acct_mfa" value: "{now}" ``` ### Relevant log/traceback output ```shell Traceback (most recent call last): File "/Users/jcarlson/Code/cloud-custodian/venv/bin/c7n-org", line 8, in <module> sys.exit(cli()) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n_org/cli.py", line 693, in run futures[w.submit( File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/executor.py", line 28, in submit return MainThreadFuture(func(*args, **kw)) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n_org/cli.py", line 613, in run_account resources = p.run() File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/policy.py", line 1294, in __call__ resources = PullMode(self).run() File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/policy.py", line 327, in run return [] File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/ctx.py", line 95, in __exit__ self.output.write_file('metadata.json', dumps(self.get_metadata(), indent=2)) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/utils.py", line 96, in dumps return json.dumps(data, cls=DateTimeEncoder, indent=indent) File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 201, in encode chunks = list(chunks) File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 431, in _iterencode yield from _iterencode_dict(o, _current_indent_level) File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 405, in _iterencode_dict yield from chunks File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 405, in _iterencode_dict yield from chunks File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 325, in _iterencode_list yield from chunks File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 405, in _iterencode_dict yield from chunks File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 438, in _iterencode o = _default(o) File "/Users/jcarlson/Code/cloud-custodian/venv/lib/python3.9/site-packages/c7n/utils.py", line 216, in default return json.JSONEncoder.default(self, obj) File "/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type FormatDate is not JSON serializable ``` ### Extra information or context _No response_
0.0
63bed288fc0deeb144c9cffc2a10b56977d4539b
[ "tests/test_utils.py::UtilTest::test_format_date" ]
[ "tests/test_utils.py::TestTesting::test_assert_regex", "tests/test_utils.py::Backoff::test_delays", "tests/test_utils.py::Backoff::test_delays_jitter", "tests/test_utils.py::Backoff::test_retry_errors", "tests/test_utils.py::Backoff::test_retry_passthrough", "tests/test_utils.py::UrlConfTest::test_parse_url", "tests/test_utils.py::ProxyUrlTest::test_all_proxy_with_full_url", "tests/test_utils.py::ProxyUrlTest::test_http_proxy_with_full_url", "tests/test_utils.py::ProxyUrlTest::test_http_proxy_with_no_proxy_match_explicit_port", "tests/test_utils.py::ProxyUrlTest::test_http_proxy_with_no_proxy_mismatch_explicit_port", "tests/test_utils.py::ProxyUrlTest::test_http_proxy_with_no_proxy_without_port", "tests/test_utils.py::ProxyUrlTest::test_http_proxy_with_relative_url", "tests/test_utils.py::ProxyUrlTest::test_no_proxy", "tests/test_utils.py::UtilTest::test_camel_case", "tests/test_utils.py::UtilTest::test_camel_case_implicit", "tests/test_utils.py::UtilTest::test_camel_nested", "tests/test_utils.py::UtilTest::test_chunks", "tests/test_utils.py::UtilTest::test_date_time_decoder", "tests/test_utils.py::UtilTest::test_format_event", "tests/test_utils.py::UtilTest::test_format_string_values", "tests/test_utils.py::UtilTest::test_generate_arn", "tests/test_utils.py::UtilTest::test_get_support_region", "tests/test_utils.py::UtilTest::test_group_by", "tests/test_utils.py::UtilTest::test_ipv4_list", "tests/test_utils.py::UtilTest::test_ipv4_network", "tests/test_utils.py::UtilTest::test_load_error", "tests/test_utils.py::UtilTest::test_load_file", "tests/test_utils.py::UtilTest::test_local_session_region", "tests/test_utils.py::UtilTest::test_merge_dict", "tests/test_utils.py::UtilTest::test_merge_dict_list", "tests/test_utils.py::UtilTest::test_parse_s3", "tests/test_utils.py::UtilTest::test_reformat_schema", "tests/test_utils.py::UtilTest::test_set_annotation", "tests/test_utils.py::UtilTest::test_snapshot_identifier", "tests/test_utils.py::UtilTest::test_type_schema", "tests/test_utils.py::test_parse_date_floor" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-11-07 18:23:23+00:00
apache-2.0
1,602
cloud-custodian__cloud-custodian-8113
diff --git a/c7n/resources/account.py b/c7n/resources/account.py index 1a422b5c0..6b6cdbb27 100644 --- a/c7n/resources/account.py +++ b/c7n/resources/account.py @@ -100,6 +100,71 @@ class AccountCredentialReport(CredentialReport): return results [email protected]('organization') +class AccountOrganization(ValueFilter): + """Check organization enrollment and configuration + + :example: + + determine if an account is not in an organization + + .. code-block:: yaml + + policies: + - name: no-org + resource: account + filters: + - type: organization + key: Id + value: absent + + + :example: + + determine if an account is setup for organization policies + + .. code-block:: yaml + + policies: + - name: org-policies-not-enabled + resource: account + filters: + - type: organization + key: FeatureSet + value: ALL + op: not-equal + """ + schema = type_schema('organization', rinherit=ValueFilter.schema) + schema_alias = False + + annotation_key = 'c7n:org' + annotate = False + + permissions = ('organizations:DescribeOrganization',) + + def get_org_info(self, account): + client = local_session( + self.manager.session_factory).client('organizations') + try: + org_info = client.describe_organization().get('Organization') + except client.exceptions.AWSOrganizationsNotInUseException: + org_info = {} + except ClientError as e: + self.log.warning('organization filter error accessing org info %s', e) + org_info = None + account[self.annotation_key] = org_info + + def process(self, resources, event=None): + if self.annotation_key not in resources[0]: + self.get_org_info(resources[0]) + # if we can't access org info, we've already logged, and return + if resources[0][self.annotation_key] is None: + return [] + if super().process([resources[0][self.annotation_key]]): + return resources + return [] + + @filters.register('check-macie') class MacieEnabled(ValueFilter): """Check status of macie v2 in the account. diff --git a/c7n/resources/connect.py b/c7n/resources/connect.py index b2fb5ede0..af920d0c2 100644 --- a/c7n/resources/connect.py +++ b/c7n/resources/connect.py @@ -52,6 +52,7 @@ class ConnectInstanceAttributeFilter(ValueFilter): if self.annotation_key not in r: instance_attribute = client.describe_instance_attribute(InstanceId=r['Id'], AttributeType=str.upper(self.data.get('attribute_type'))) + instance_attribute.pop('ResponseMetadata', None) r[self.annotation_key] = instance_attribute if self.match(r[self.annotation_key]): diff --git a/tools/c7n_left/c7n_left/filters.py b/tools/c7n_left/c7n_left/filters.py index 2e80586b7..7dee0e881 100644 --- a/tools/c7n_left/c7n_left/filters.py +++ b/tools/c7n_left/c7n_left/filters.py @@ -24,7 +24,7 @@ class Traverse(Filter): filters: - not: - type: traverse - resource: aws_s3_bucket_server_side_encryption_configuration + resources: aws_s3_bucket_server_side_encryption_configuration attrs: - rule.apply_server_side_encryption_by_default.sse_algorithm: aws:kms @@ -40,7 +40,7 @@ class Traverse(Filter): filters: - network_configuration: present - type: traverse - resource: [aws_apprunner_vpc_connector, aws_subnet, aws_vpc] + resources: [aws_apprunner_vpc_connector, aws_subnet, aws_vpc] attrs: - type: value key: tag:Env diff --git a/tools/c7n_left/c7n_left/output.py b/tools/c7n_left/c7n_left/output.py index c537282e7..80b9d581b 100644 --- a/tools/c7n_left/c7n_left/output.py +++ b/tools/c7n_left/c7n_left/output.py @@ -94,7 +94,7 @@ class RichCli(Output): def on_execution_ended(self): message = "[green]Success[green]" if self.matches: - message = "[red]%d Failures[/red]" % len(self.matches) + message = "[red]%d Failures[/red]" % self.matches self.console.print( "Evaluation complete %0.2f seconds -> %s" % (time.time() - self.started, message)
cloud-custodian/cloud-custodian
2bf18eaeae3c69ab286bc61740561b3ab777d09b
diff --git a/tests/data/placebo/test_account_org_info/iam.ListAccountAliases_1.json b/tests/data/placebo/test_account_org_info/iam.ListAccountAliases_1.json new file mode 100644 index 000000000..97b529abe --- /dev/null +++ b/tests/data/placebo/test_account_org_info/iam.ListAccountAliases_1.json @@ -0,0 +1,10 @@ +{ + "status_code": 200, + "data": { + "AccountAliases": [ + "realms-root" + ], + "IsTruncated": false, + "ResponseMetadata": {} + } +} \ No newline at end of file diff --git a/tests/data/placebo/test_account_org_info/organizations.DescribeOrganization_1.json b/tests/data/placebo/test_account_org_info/organizations.DescribeOrganization_1.json new file mode 100644 index 000000000..a4d13e1e5 --- /dev/null +++ b/tests/data/placebo/test_account_org_info/organizations.DescribeOrganization_1.json @@ -0,0 +1,20 @@ +{ + "status_code": 200, + "data": { + "Organization": { + "Id": "o-vjtynx2e3h", + "Arn": "arn:aws:organizations::644160558196:organization/o-vjtynx4d1h", + "FeatureSet": "ALL", + "MasterAccountArn": "arn:aws:organizations::644160558196:account/o-vjtynx4d1h/644160558196", + "MasterAccountId": "644160558196", + "MasterAccountEmail": "[email protected]", + "AvailablePolicyTypes": [ + { + "Type": "SERVICE_CONTROL_POLICY", + "Status": "ENABLED" + } + ] + }, + "ResponseMetadata": {} + } +} diff --git a/tests/data/placebo/test_account_org_info_denied/iam.ListAccountAliases_1.json b/tests/data/placebo/test_account_org_info_denied/iam.ListAccountAliases_1.json new file mode 100644 index 000000000..97b529abe --- /dev/null +++ b/tests/data/placebo/test_account_org_info_denied/iam.ListAccountAliases_1.json @@ -0,0 +1,10 @@ +{ + "status_code": 200, + "data": { + "AccountAliases": [ + "realms-root" + ], + "IsTruncated": false, + "ResponseMetadata": {} + } +} \ No newline at end of file diff --git a/tests/data/placebo/test_account_org_info_denied/organizations.DescribeOrganization_1.json b/tests/data/placebo/test_account_org_info_denied/organizations.DescribeOrganization_1.json new file mode 100644 index 000000000..1ab801caa --- /dev/null +++ b/tests/data/placebo/test_account_org_info_denied/organizations.DescribeOrganization_1.json @@ -0,0 +1,11 @@ +{ + "status_code": 403, + "data": { + "Error": { + "Message": "not authorized", + "Code": "AccessDeniedException" + }, + "ResponseMetadata": {}, + "message": "not authorized" + } +} diff --git a/tests/data/placebo/test_account_org_no_org/iam.ListAccountAliases_1.json b/tests/data/placebo/test_account_org_no_org/iam.ListAccountAliases_1.json new file mode 100644 index 000000000..97b529abe --- /dev/null +++ b/tests/data/placebo/test_account_org_no_org/iam.ListAccountAliases_1.json @@ -0,0 +1,10 @@ +{ + "status_code": 200, + "data": { + "AccountAliases": [ + "realms-root" + ], + "IsTruncated": false, + "ResponseMetadata": {} + } +} \ No newline at end of file diff --git a/tests/data/placebo/test_account_org_no_org/organizations.DescribeOrganization_1.json b/tests/data/placebo/test_account_org_no_org/organizations.DescribeOrganization_1.json new file mode 100644 index 000000000..a84394039 --- /dev/null +++ b/tests/data/placebo/test_account_org_no_org/organizations.DescribeOrganization_1.json @@ -0,0 +1,14 @@ +{ + "status_code": 404, + "data": { + "ResponseMetadata": { + "HTTPStatusCode": 404, + "HostId": "4tbXPrkIvHzDe7UTWOeiJGxuomJ8SVVvn9cSKQHVTVJdJtVeYDAkwOkd7C0K9k4WtVzvKf1R2iU=", + "RequestId": "29DAAD9315A10452" + }, + "Error": { + "Message": "dunno", + "Code": "AWSOrganizationsNotInUseException" + } + } +} diff --git a/tests/test_account.py b/tests/test_account.py index 821a6841c..aec2e7464 100644 --- a/tests/test_account.py +++ b/tests/test_account.py @@ -69,6 +69,57 @@ class AccountTests(BaseTest): resources = p.run() self.assertEqual(len(resources), 1) + def test_org_no_org(self): + factory = self.replay_flight_data( + 'test_account_org_no_org') + p = self.load_policy({ + 'name': 'org-check', + 'resource': 'aws.account', + 'filters': [{ + 'type': 'organization', + 'key': 'Id', + 'value': 'absent' + }]}, + session_factory=factory + ) + resources = p.run() + self.assertEqual(len(resources), 1) + + def test_org_denied(self): + factory = self.replay_flight_data( + 'test_account_org_info_denied') + p = self.load_policy({ + 'name': 'org-check', + 'resource': 'aws.account', + 'filters': [{ + 'type': 'organization', + 'key': 'Id', + 'value': 'absent' + }]}, + session_factory=factory + ) + resources = p.run() + self.assertEqual(len(resources), 0) + + def test_org_info(self): + factory = self.replay_flight_data( + 'test_account_org_info') + p = self.load_policy({ + 'name': 'org-check', + 'resource': 'aws.account', + 'filters': [{ + 'type': 'organization', + 'key': 'Id', + 'op': 'not-equal', + 'value': 'o-xyz' + }]}, + session_factory=factory + ) + resources = p.run() + + self.assertEqual(len(resources), 1) + self.assertEqual(resources[0]['c7n:org']['FeatureSet'], 'ALL') + def test_missing(self): session_factory = self.replay_flight_data( 'test_account_missing_resource_ec2')
AWS Account - Add organization-member filter ### Describe the feature I need to be able to check if an AWS account is part of an organization for a compliance check. I would like a filter added to the aws.account resource to do this. The API to check if an account is part of an organization is ```response = client.describe_organization()``` and if the account is part of an organization it returns the org info. If the account is not part of an organization it will return: ```An error occurred (AWSOrganizationsNotInUseException) when calling the DescribeOrganization operation: Your account is not a member of an organization.``` ### Extra information or context The policy I want to write will look something like this: ``` - name: aws-account-organization-member resource: aws.account filters: - type: organization-member value: False ```
0.0
2bf18eaeae3c69ab286bc61740561b3ab777d09b
[ "tests/test_account.py::AccountTests::test_org_denied", "tests/test_account.py::AccountTests::test_org_info", "tests/test_account.py::AccountTests::test_org_no_org" ]
[ "tests/test_account.py::AccountTests::test_account_access_analyzer_filter", "tests/test_account.py::AccountTests::test_account_password_policy_update", "tests/test_account.py::AccountTests::test_account_password_policy_update_first_time", "tests/test_account.py::AccountTests::test_account_shield_activate", "tests/test_account.py::AccountTests::test_account_shield_filter", "tests/test_account.py::AccountTests::test_account_virtual_mfa", "tests/test_account.py::AccountTests::test_cloudtrail_current_region_global", "tests/test_account.py::AccountTests::test_cloudtrail_current_region_specific_different", "tests/test_account.py::AccountTests::test_cloudtrail_current_region_specific_same", "tests/test_account.py::AccountTests::test_cloudtrail_enabled", "tests/test_account.py::AccountTests::test_cloudtrail_notifies_disabled", "tests/test_account.py::AccountTests::test_cloudtrail_notifies_enabled", "tests/test_account.py::AccountTests::test_cloudtrail_running", "tests/test_account.py::AccountTests::test_config_enabled", "tests/test_account.py::AccountTests::test_config_enabled_global", "tests/test_account.py::AccountTests::test_create_trail", "tests/test_account.py::AccountTests::test_create_trail_bucket_exists_in_west", "tests/test_account.py::AccountTests::test_credential_report", "tests/test_account.py::AccountTests::test_disable_encryption_by_default", "tests/test_account.py::AccountTests::test_enable_encryption_by_default", "tests/test_account.py::AccountTests::test_enable_trail", "tests/test_account.py::AccountTests::test_get_emr_block_public_access_configuration", "tests/test_account.py::AccountTests::test_glue_catalog_encrypted_filter", "tests/test_account.py::AccountTests::test_glue_connection_password_encryption", "tests/test_account.py::AccountTests::test_glue_password_encryption_setting", "tests/test_account.py::AccountTests::test_guard_duty_filter", "tests/test_account.py::AccountTests::test_macie", "tests/test_account.py::AccountTests::test_macie_disabled", "tests/test_account.py::AccountTests::test_missing", "tests/test_account.py::AccountTests::test_missing_multi_region", "tests/test_account.py::AccountTests::test_missing_password_policy", "tests/test_account.py::AccountTests::test_raise_service_limit", "tests/test_account.py::AccountTests::test_raise_service_limit_amount", "tests/test_account.py::AccountTests::test_raise_service_limit_percent", "tests/test_account.py::AccountTests::test_raise_service_limit_percent_and_amount", "tests/test_account.py::AccountTests::test_root_api_keys", "tests/test_account.py::AccountTests::test_root_mfa_enabled", "tests/test_account.py::AccountTests::test_s3_public_block_filter_missing", "tests/test_account.py::AccountTests::test_s3_set_public_block_action", "tests/test_account.py::AccountTests::test_service_limit_global_service", "tests/test_account.py::AccountTests::test_service_limit_no_threshold", "tests/test_account.py::AccountTests::test_service_limit_poll_status", "tests/test_account.py::AccountTests::test_service_limit_specific_check", "tests/test_account.py::AccountTests::test_service_limit_specific_service", "tests/test_account.py::AccountTests::test_ses_agg_send_stats", "tests/test_account.py::AccountTests::test_ses_consecutive_send_stats", "tests/test_account.py::AccountTests::test_set_emr_block_public_access_configuration", "tests/test_account.py::AccountDataEvents::test_data_events", "tests/test_account.py::AccountDataEvents::test_enable_securityhub", "tests/test_account.py::AccountDataEvents::test_lakeformation_filter", "tests/test_account.py::AccountDataEvents::test_modify_data_events", "tests/test_account.py::AccountDataEvents::test_toggle_config_managed_rule", "tests/test_account.py::AccountDataEvents::test_toggle_config_managed_rule_validation", "tests/test_account.py::test_cloudtrail_success_log_metric_filter", "tests/test_account.py::test_cloudtrail_fail_log_metric_filter_no_alarm", "tests/test_account.py::test_cloudtrail_fail_log_metric_filter_no_sns", "tests/test_account.py::test_cloudtrail_fail_log_metric_filter", "tests/test_account.py::test_success_cloudtrail_include_management_events", "tests/test_account.py::test_fail_cloudtrail_include_management_events" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-04 16:13:36+00:00
apache-2.0
1,603
cloudant__python-cloudant-262
diff --git a/src/cloudant/__init__.py b/src/cloudant/__init__.py index 1ed58b4..caed558 100644 --- a/src/cloudant/__init__.py +++ b/src/cloudant/__init__.py @@ -63,19 +63,21 @@ def cloudant(user, passwd, **kwargs): cloudant_session.disconnect() @contextlib.contextmanager -def cloudant_bluemix(bm_service_name=None, **kwargs): +def cloudant_bluemix(vcap_services, instance_name=None, **kwargs): """ Provides a context manager to create a Cloudant session and provide access to databases, docs etc. - :param str bm_service_name: Optional Bluemix service instance name. Only - required if multiple Cloudant services are available. + :param vcap_services: VCAP_SERVICES environment variable + :type vcap_services: dict or str + :param str instance_name: Optional Bluemix instance name. Only required if + multiple Cloudant instances are available. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. - Loads all configuration from the VCAP_SERVICES Cloud Foundry environment - variable. The VCAP_SERVICES variable contains connection information to - access a service instance. For example: + Loads all configuration from the specified VCAP_SERVICES Cloud Foundry + environment variable. The VCAP_SERVICES variable contains connection + information to access a service instance. For example: .. code-block:: json @@ -102,8 +104,23 @@ def cloudant_bluemix(bm_service_name=None, **kwargs): See `Cloud Foundry Environment Variables <http://docs.cloudfoundry.org/ devguide/deploy-apps/environment-variable.html#VCAP-SERVICES>`_. + + Example usage: + + .. code-block:: python + + import os + + # cloudant_bluemix context manager + from cloudant import cloudant_bluemix + + with cloudant_bluemix(os.getenv('VCAP_SERVICES'), 'Cloudant NoSQL DB') as client: + # Context handles connect() and disconnect() for you. + # Perform library operations within this context. Such as: + print client.all_dbs() + # ... """ - service = CloudFoundryService(bm_service_name) + service = CloudFoundryService(vcap_services, instance_name) cloudant_session = Cloudant( username=service.username, password=service.password, diff --git a/src/cloudant/_common_util.py b/src/cloudant/_common_util.py index ad84b4f..2e8ad78 100644 --- a/src/cloudant/_common_util.py +++ b/src/cloudant/_common_util.py @@ -17,7 +17,6 @@ Module containing miscellaneous classes, functions, and constants used throughout the library. """ -import os import sys import platform from collections import Sequence @@ -340,9 +339,12 @@ class InfiniteSession(Session): class CloudFoundryService(object): """ Manages Cloud Foundry service configuration. """ - def __init__(self, name=None): + def __init__(self, vcap_services, name=None): try: - services = json.loads(os.getenv('VCAP_SERVICES', '{}')) + services = vcap_services + if not isinstance(vcap_services, dict): + services = json.loads(vcap_services) + cloudant_services = services.get('cloudantNoSQLDB', []) # use first service if no name given and only one service present
cloudant/python-cloudant
4c285be19cf4220b9d2dd6970d31a3a9c830d442
diff --git a/tests/unit/cloud_foundry_tests.py b/tests/unit/cloud_foundry_tests.py index f70eb70..043949f 100644 --- a/tests/unit/cloud_foundry_tests.py +++ b/tests/unit/cloud_foundry_tests.py @@ -19,7 +19,6 @@ Unit tests for the CloudFoundryService class. """ import json -import mock import unittest from cloudant._common_util import CloudFoundryService @@ -93,94 +92,101 @@ class CloudFoundryServiceTests(unittest.TestCase): } ]}) - @mock.patch('os.getenv') - def test_get_vcap_service_default_success(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_single - service = CloudFoundryService() + def test_get_vcap_service_default_success(self): + service = CloudFoundryService(self._test_vcap_services_single) self.assertEqual('Cloudant NoSQL DB 1', service.name) - @mock.patch('os.getenv') - def test_get_vcap_service_default_failure_multiple_services(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_get_vcap_service_default_success_as_dict(self): + service = CloudFoundryService( + json.loads(self._test_vcap_services_single) + ) + self.assertEqual('Cloudant NoSQL DB 1', service.name) + + def test_get_vcap_service_default_failure_multiple_services(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService() + CloudFoundryService(self._test_vcap_services_multiple) self.assertEqual('Missing service in VCAP_SERVICES', str(cm.exception)) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_host(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 1') + def test_get_vcap_service_instance_host(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + ) self.assertEqual('example.cloudant.com', service.host) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_password(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 1') + def test_get_vcap_service_instance_password(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + ) self.assertEqual('pa$$w0rd01', service.password) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_port(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 1') + def test_get_vcap_service_instance_port(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + ) self.assertEqual('1234', service.port) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_port_default(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 2') + def test_get_vcap_service_instance_port_default(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 2' + ) self.assertEqual('443', service.port) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_url(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 1') + def test_get_vcap_service_instance_url(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + ) self.assertEqual('https://example.cloudant.com:1234', service.url) - @mock.patch('os.getenv') - def test_get_vcap_service_instance_username(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple - service = CloudFoundryService('Cloudant NoSQL DB 1') + def test_get_vcap_service_instance_username(self): + service = CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + ) self.assertEqual('example', service.username) - @mock.patch('os.getenv') - def test_raise_error_for_missing_host(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_raise_error_for_missing_host(self): with self.assertRaises(CloudantException): - CloudFoundryService('Cloudant NoSQL DB 3') + CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 3' + ) - @mock.patch('os.getenv') - def test_raise_error_for_missing_password(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_raise_error_for_missing_password(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService('Cloudant NoSQL DB 4') + CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 4' + ) self.assertEqual( "Invalid service: 'password' missing", str(cm.exception) ) - @mock.patch('os.getenv') - def test_raise_error_for_missing_username(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_raise_error_for_missing_username(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService('Cloudant NoSQL DB 5') + CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 5' + ) self.assertEqual( "Invalid service: 'username' missing", str(cm.exception) ) - @mock.patch('os.getenv') - def test_raise_error_for_invalid_credentials_type(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_raise_error_for_invalid_credentials_type(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService('Cloudant NoSQL DB 6') + CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 6' + ) self.assertEqual( 'Failed to decode VCAP_SERVICES service credentials', str(cm.exception) ) - @mock.patch('os.getenv') - def test_raise_error_for_missing_service(self, m_getenv): - m_getenv.return_value = self._test_vcap_services_multiple + def test_raise_error_for_missing_service(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService('Cloudant NoSQL DB 7') + CloudFoundryService( + self._test_vcap_services_multiple, 'Cloudant NoSQL DB 7' + ) self.assertEqual('Missing service in VCAP_SERVICES', str(cm.exception)) + + def test_raise_error_for_invalid_vcap(self): + with self.assertRaises(CloudantException) as cm: + CloudFoundryService('{', 'Cloudant NoSQL DB 1') # invalid JSON + self.assertEqual('Failed to decode VCAP_SERVICES JSON', str(cm.exception))
Implement method to create Cloudant client from VCAP services environment variable Add an additional method to parse a `VCAP_SERVICES` environment variable allowing easy binding of a service instance to a Cloud Foundry application. Example `VCAP_SERVICES` variable is JSON: ```json { "cloudantNoSQLDB": [ { "credentials": { "username": "example", "password": "xxxxxxx", "host": "example.cloudant.com", "port": 443, "url": "https://example:[email protected]" }, "syslog_drain_url": null, "label": "cloudantNoSQLDB", "provider": null, "plan": "Lite", "name": "Cloudant NoSQL DB" } ] } ```
0.0
4c285be19cf4220b9d2dd6970d31a3a9c830d442
[ "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_success", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_success_as_dict", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_host", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_password", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_port", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_port_default", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_url", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_username", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_invalid_credentials_type", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_invalid_vcap", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_host", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_password", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_service", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_username" ]
[ "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_failure_multiple_services" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-12-20 11:17:27+00:00
apache-2.0
1,604
cloudant__python-cloudant-332
diff --git a/CHANGES.rst b/CHANGES.rst index eab0557..c683e44 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,7 @@ Unreleased ========== - [NEW] Added ``Result.all()`` convenience method. +- [NEW] Allow ``service_name`` to be specified when instantiating from a Bluemix VCAP_SERVICES environment variable. - [IMPROVED] Updated ``posixpath.join`` references to use ``'/'.join`` when concatenating URL parts. - [IMPROVED] Updated documentation by replacing deprecated Cloudant links with the latest Bluemix links. diff --git a/src/cloudant/__init__.py b/src/cloudant/__init__.py index 04131db..7b1ba55 100644 --- a/src/cloudant/__init__.py +++ b/src/cloudant/__init__.py @@ -92,7 +92,7 @@ def cloudant_iam(account_name, api_key, **kwargs): cloudant_session.disconnect() @contextlib.contextmanager -def cloudant_bluemix(vcap_services, instance_name=None, **kwargs): +def cloudant_bluemix(vcap_services, instance_name=None, service_name=None, **kwargs): """ Provides a context manager to create a Cloudant session and provide access to databases, docs etc. @@ -101,6 +101,7 @@ def cloudant_bluemix(vcap_services, instance_name=None, **kwargs): :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. + :param str service_name: Optional Bluemix service name. :param str encoder: Optional json Encoder object used to encode documents for storage. Defaults to json.JSONEncoder. @@ -149,11 +150,10 @@ def cloudant_bluemix(vcap_services, instance_name=None, **kwargs): print client.all_dbs() # ... """ - service = CloudFoundryService(vcap_services, instance_name) - cloudant_session = Cloudant( - service.username, - service.password, - url=service.url, + cloudant_session = Cloudant.bluemix( + vcap_services, + instance_name=instance_name, + service_name=service_name, **kwargs ) cloudant_session.connect() diff --git a/src/cloudant/_common_util.py b/src/cloudant/_common_util.py index fe2e068..05e3bd3 100644 --- a/src/cloudant/_common_util.py +++ b/src/cloudant/_common_util.py @@ -498,18 +498,18 @@ class IAMSession(ClientSession): class CloudFoundryService(object): """ Manages Cloud Foundry service configuration. """ - def __init__(self, vcap_services, name=None): + def __init__(self, vcap_services, instance_name=None, service_name=None): try: services = vcap_services if not isinstance(vcap_services, dict): services = json.loads(vcap_services) - cloudant_services = services.get('cloudantNoSQLDB', []) + cloudant_services = services.get(service_name, []) # use first service if no name given and only one service present - use_first = name is None and len(cloudant_services) == 1 + use_first = instance_name is None and len(cloudant_services) == 1 for service in cloudant_services: - if use_first or service.get('name') == name: + if use_first or service.get('name') == instance_name: credentials = service['credentials'] self._host = credentials['host'] self._name = service.get('name') diff --git a/src/cloudant/client.py b/src/cloudant/client.py index 3a1360c..ce7d493 100755 --- a/src/cloudant/client.py +++ b/src/cloudant/client.py @@ -754,7 +754,7 @@ class Cloudant(CouchDB): return resp.json() @classmethod - def bluemix(cls, vcap_services, instance_name=None, **kwargs): + def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs): """ Create a Cloudant session using a VCAP_SERVICES environment variable. @@ -762,6 +762,7 @@ class Cloudant(CouchDB): :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. + :param str service_name: Optional Bluemix service name. Example usage: @@ -775,7 +776,10 @@ class Cloudant(CouchDB): print client.all_dbs() """ - service = CloudFoundryService(vcap_services, instance_name) + service_name = service_name or 'cloudantNoSQLDB' # default service + service = CloudFoundryService(vcap_services, + instance_name=instance_name, + service_name=service_name) return Cloudant(service.username, service.password, url=service.url,
cloudant/python-cloudant
e1b5a3291a0759be6d2350e9626a0f6e6e3c657b
diff --git a/tests/unit/client_tests.py b/tests/unit/client_tests.py index 796e5fc..db78861 100644 --- a/tests/unit/client_tests.py +++ b/tests/unit/client_tests.py @@ -552,6 +552,34 @@ class CloudantClientTests(UnitTestDbBase): except Exception as err: self.fail('Exception {0} was raised.'.format(str(err))) + def test_cloudant_bluemix_dedicated_context_helper(self): + """ + Test that the cloudant_bluemix context helper works as expected when + specifying a service name. + """ + instance_name = 'Cloudant NoSQL DB-wq' + service_name = 'cloudantNoSQLDB Dedicated' + vcap_services = {service_name: [{ + 'credentials': { + 'username': self.user, + 'password': self.pwd, + 'host': '{0}.cloudant.com'.format(self.account), + 'port': 443, + 'url': self.url + }, + 'name': instance_name, + }]} + + try: + with cloudant_bluemix(vcap_services, + instance_name=instance_name, + service_name=service_name) as c: + self.assertIsInstance(c, Cloudant) + self.assertIsInstance(c.r_session, requests.Session) + self.assertEquals(c.session()['userCtx']['name'], self.user) + except Exception as err: + self.fail('Exception {0} was raised.'.format(str(err))) + def test_constructor_with_account(self): """ Test instantiating a client object using an account name diff --git a/tests/unit/cloud_foundry_tests.py b/tests/unit/cloud_foundry_tests.py index 043949f..43249b7 100644 --- a/tests/unit/cloud_foundry_tests.py +++ b/tests/unit/cloud_foundry_tests.py @@ -91,68 +91,104 @@ class CloudFoundryServiceTests(unittest.TestCase): ] } ]}) + self._test_vcap_services_dedicated = json.dumps({ + 'cloudantNoSQLDB Dedicated': [ # dedicated service name + { + 'name': 'Cloudant NoSQL DB 1', # valid service + 'credentials': { + 'host': 'example.cloudant.com', + 'password': 'pa$$w0rd01', + 'port': 1234, + 'username': 'example' + } + } + ] + }) def test_get_vcap_service_default_success(self): - service = CloudFoundryService(self._test_vcap_services_single) + service = CloudFoundryService( + self._test_vcap_services_single, + service_name='cloudantNoSQLDB' + ) self.assertEqual('Cloudant NoSQL DB 1', service.name) def test_get_vcap_service_default_success_as_dict(self): service = CloudFoundryService( - json.loads(self._test_vcap_services_single) + json.loads(self._test_vcap_services_single), + service_name='cloudantNoSQLDB' ) self.assertEqual('Cloudant NoSQL DB 1', service.name) def test_get_vcap_service_default_failure_multiple_services(self): with self.assertRaises(CloudantException) as cm: - CloudFoundryService(self._test_vcap_services_multiple) + CloudFoundryService( + self._test_vcap_services_multiple, + service_name='cloudantNoSQLDB' + ) self.assertEqual('Missing service in VCAP_SERVICES', str(cm.exception)) def test_get_vcap_service_instance_host(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 1', + service_name='cloudantNoSQLDB' ) self.assertEqual('example.cloudant.com', service.host) def test_get_vcap_service_instance_password(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 1', + service_name='cloudantNoSQLDB' ) self.assertEqual('pa$$w0rd01', service.password) def test_get_vcap_service_instance_port(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 1', + service_name='cloudantNoSQLDB' ) self.assertEqual('1234', service.port) def test_get_vcap_service_instance_port_default(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 2' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 2', + service_name='cloudantNoSQLDB' ) self.assertEqual('443', service.port) def test_get_vcap_service_instance_url(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 1', + service_name='cloudantNoSQLDB' ) self.assertEqual('https://example.cloudant.com:1234', service.url) def test_get_vcap_service_instance_username(self): service = CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 1' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 1', + service_name='cloudantNoSQLDB' ) self.assertEqual('example', service.username) def test_raise_error_for_missing_host(self): with self.assertRaises(CloudantException): CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 3' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 3', + service_name='cloudantNoSQLDB' ) def test_raise_error_for_missing_password(self): with self.assertRaises(CloudantException) as cm: CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 4' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 4', + service_name='cloudantNoSQLDB' ) self.assertEqual( "Invalid service: 'password' missing", @@ -162,7 +198,9 @@ class CloudFoundryServiceTests(unittest.TestCase): def test_raise_error_for_missing_username(self): with self.assertRaises(CloudantException) as cm: CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 5' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 5', + service_name='cloudantNoSQLDB' ) self.assertEqual( "Invalid service: 'username' missing", @@ -172,7 +210,9 @@ class CloudFoundryServiceTests(unittest.TestCase): def test_raise_error_for_invalid_credentials_type(self): with self.assertRaises(CloudantException) as cm: CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 6' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 6', + service_name='cloudantNoSQLDB' ) self.assertEqual( 'Failed to decode VCAP_SERVICES service credentials', @@ -182,7 +222,9 @@ class CloudFoundryServiceTests(unittest.TestCase): def test_raise_error_for_missing_service(self): with self.assertRaises(CloudantException) as cm: CloudFoundryService( - self._test_vcap_services_multiple, 'Cloudant NoSQL DB 7' + self._test_vcap_services_multiple, + instance_name='Cloudant NoSQL DB 7', + service_name='cloudantNoSQLDB' ) self.assertEqual('Missing service in VCAP_SERVICES', str(cm.exception)) @@ -190,3 +232,10 @@ class CloudFoundryServiceTests(unittest.TestCase): with self.assertRaises(CloudantException) as cm: CloudFoundryService('{', 'Cloudant NoSQL DB 1') # invalid JSON self.assertEqual('Failed to decode VCAP_SERVICES JSON', str(cm.exception)) + + def test_get_vcap_service_with_dedicated_service_name_success(self): + service = CloudFoundryService( + self._test_vcap_services_dedicated, + service_name='cloudantNoSQLDB Dedicated' + ) + self.assertEqual('Cloudant NoSQL DB 1', service.name)
Cloudant.bluemix does not work on IBM Bluemix Dedicated service Please include the following information in your ticket. - Cloudant (python-cloudant) version(s) that are affected by this issue. *2.6.0* - Python version *3.6.2* - A small code sample that demonstrates the issue. *See below* IBM Bluemix Dedicated service uses "cloudantNoSQLDB Dedicated" as the name of the service, rather than "cloudantNoSQLDB" used by Public Bluemix. Unfortunately, the CloudFoundryService class hardcodes the value: `cloudant_services = services.get('cloudantNoSQLDB', [])` Any chance we could make that value a parameter?
0.0
e1b5a3291a0759be6d2350e9626a0f6e6e3c657b
[ "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_failure_multiple_services", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_success", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_default_success_as_dict", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_host", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_password", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_port", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_port_default", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_url", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_instance_username", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_get_vcap_service_with_dedicated_service_name_success", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_invalid_credentials_type", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_host", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_password", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_service", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_missing_username" ]
[ "tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_using_invalid_code", "tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_with_proper_code_and_args", "tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_without_args", "tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_without_code", "tests/unit/cloud_foundry_tests.py::CloudFoundryServiceTests::test_raise_error_for_invalid_vcap" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2017-10-16 14:59:58+00:00
apache-2.0
1,605
cloudevents__sdk-python-172
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e1891b..06c9f29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `.get` accessor for even properties ([#165]) - Added type information for all event member functions ([#173]) +### Fixed +- Fixed event `__eq__` operator raising `AttributeError` on non-CloudEvent values ([#172]) + ### Changed - Code quality and styling tooling is unified and configs compatibility is ensured ([#167]) - CI configurations updated and added macOS and Windows tests ([#169]) @@ -18,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed - `docs` folder and related unused tooling ([#168]) + ## [1.3.0] — 2022-09-07 ### Added - Python 3.9 support ([#144]) @@ -156,4 +160,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#168]: https://github.com/cloudevents/sdk-python/pull/168 [#169]: https://github.com/cloudevents/sdk-python/pull/169 [#170]: https://github.com/cloudevents/sdk-python/pull/170 +[#172]: https://github.com/cloudevents/sdk-python/pull/172 [#173]: https://github.com/cloudevents/sdk-python/pull/173 diff --git a/cloudevents/http/event.py b/cloudevents/http/event.py index b4ef41a..ee78cff 100644 --- a/cloudevents/http/event.py +++ b/cloudevents/http/event.py @@ -68,7 +68,9 @@ class CloudEvent: ) def __eq__(self, other: typing.Any) -> bool: - return self.data == other.data and self._attributes == other._attributes + if isinstance(other, CloudEvent): + return self.data == other.data and self._attributes == other._attributes + return False # Data access is handled via `.data` member # Attribute access is managed via Mapping type
cloudevents/sdk-python
f39b964209babfbcd6a17502b9873cd87df7e6f0
diff --git a/cloudevents/tests/test_http_cloudevent.py b/cloudevents/tests/test_http_cloudevent.py index 3737ea6..fa4bd91 100644 --- a/cloudevents/tests/test_http_cloudevent.py +++ b/cloudevents/tests/test_http_cloudevent.py @@ -47,6 +47,18 @@ def your_dummy_data(): return '{"name":"paul"}' [email protected]() +def dummy_event(dummy_attributes, my_dummy_data): + return CloudEvent(attributes=dummy_attributes, data=my_dummy_data) + + [email protected]() +def non_exiting_attribute_name(dummy_event): + result = "nonexisting" + assert result not in dummy_event + return result + + def test_http_cloudevent_equality(dummy_attributes, my_dummy_data, your_dummy_data): data = my_dummy_data event1 = CloudEvent(dummy_attributes, data) @@ -71,6 +83,21 @@ def test_http_cloudevent_equality(dummy_attributes, my_dummy_data, your_dummy_da assert event1 != event2 and event3 != event1 [email protected]( + "non_cloudevent_value", + ( + 1, + None, + object(), + "Hello World", + ), +) +def test_http_cloudevent_must_not_equal_to_non_cloudevent_value( + dummy_event, non_cloudevent_value +): + assert not dummy_event == non_cloudevent_value + + def test_http_cloudevent_mutates_equality( dummy_attributes, my_dummy_data, your_dummy_data ): @@ -145,18 +172,6 @@ def test_none_json_or_string(): assert _json_or_string(None) is None [email protected]() -def dummy_event(dummy_attributes, my_dummy_data): - return CloudEvent(attributes=dummy_attributes, data=my_dummy_data) - - [email protected]() -def non_exiting_attribute_name(dummy_event): - result = "nonexisting" - assert result not in dummy_event - return result - - def test_get_operation_on_non_existing_attribute_must_not_raise_exception( dummy_event, non_exiting_attribute_name ):
__eq__ operator raises attribute error on non-cloudevent values ## Expected Behavior Given a non-cloudevent value will return false ## Actual Behavior raises an `AttributeError` ## Steps to Reproduce the Problem 1. create an event 2. compare it to an integer ```python from cloudevents.http import CloudEvent attributes = { "source": "test", "type": "google.cloud.audit.log.v1.written", } event = CloudEvent(attributes) event == 1 ``` ## Specifications - Platform: Windows - Python Version: Python 3.9
0.0
f39b964209babfbcd6a17502b9873cd87df7e6f0
[ "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[0.3-1]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[0.3-None]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[0.3-non_cloudevent_value2]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[0.3-Hello", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[1.0-1]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[1.0-None]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[1.0-non_cloudevent_value2]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_must_not_equal_to_non_cloudevent_value[1.0-Hello" ]
[ "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_equality[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_equality[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_mutates_equality[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_http_cloudevent_mutates_equality[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_cloudevent_missing_specversion", "cloudevents/tests/test_http_cloudevent.py::test_cloudevent_missing_minimal_required_fields", "cloudevents/tests/test_http_cloudevent.py::test_cloudevent_general_overrides", "cloudevents/tests/test_http_cloudevent.py::test_none_json_or_string", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_not_raise_exception[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_not_raise_exception[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_get_must_return_attribute_value_if_exists[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_get_must_return_attribute_value_if_exists[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_return_none_by_default[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_return_none_by_default[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_return_default_value_if_given[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_must_return_default_value_if_given[1.0]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_should_not_copy_default_value[0.3]", "cloudevents/tests/test_http_cloudevent.py::test_get_operation_on_non_existing_attribute_should_not_copy_default_value[1.0]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-07-11 11:15:46+00:00
apache-2.0
1,606
cloudevents__sdk-python-71
diff --git a/cloudevents/sdk/event/base.py b/cloudevents/sdk/event/base.py index 791eb67..2004dbb 100644 --- a/cloudevents/sdk/event/base.py +++ b/cloudevents/sdk/event/base.py @@ -201,6 +201,9 @@ class BaseEvent(EventGetterSetter): props["data_base64"] = base64.b64encode(data).decode("ascii") else: props["data"] = data + if "extensions" in props: + extensions = props.pop("extensions") + props.update(extensions) return json.dumps(props) def UnmarshalJSON(
cloudevents/sdk-python
0aa01ba5c6eb9c2bc6a583104068a87ca9d66708
diff --git a/cloudevents/tests/test_event_extensions.py b/cloudevents/tests/test_event_extensions.py new file mode 100644 index 0000000..57afff4 --- /dev/null +++ b/cloudevents/tests/test_event_extensions.py @@ -0,0 +1,92 @@ +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +import json + +import pytest + +from cloudevents.sdk.http import ( + CloudEvent, + from_http, + to_binary_http, + to_structured_http, +) + +test_data = json.dumps({"data-key": "val"}) +test_attributes = { + "type": "com.example.string", + "source": "https://example.com/event-producer", + "ext1": "testval", +} + + [email protected]("specversion", ["0.3", "1.0"]) +def test_cloudevent_access_extensions(specversion): + event = CloudEvent(test_attributes, test_data) + assert event["ext1"] == "testval" + + [email protected]("specversion", ["0.3", "1.0"]) +def test_to_binary_extensions(specversion): + event = CloudEvent(test_attributes, test_data) + headers, body = to_binary_http(event) + + assert "ce-ext1" in headers + assert headers.get("ce-ext1") == test_attributes["ext1"] + + [email protected]("specversion", ["0.3", "1.0"]) +def test_from_binary_extensions(specversion): + headers = { + "ce-id": "1234", + "ce-source": "<my url>", + "ce-type": "sample", + "ce-specversion": specversion, + "ce-ext1": "test1", + "ce-ext2": "test2", + } + body = json.dumps({"data-key": "val"}) + event = from_http(body, headers) + + assert headers["ce-ext1"] == event["ext1"] + assert headers["ce-ext2"] == event["ext2"] + + [email protected]("specversion", ["0.3", "1.0"]) +def test_to_structured_extensions(specversion): + event = CloudEvent(test_attributes, test_data) + headers, body = to_structured_http(event) + + body = json.loads(body) + + assert "ext1" in body + assert "extensions" not in body + + [email protected]("specversion", ["0.3", "1.0"]) +def test_from_structured_extensions(specversion): + headers = {"Content-Type": "application/cloudevents+json"} + body = { + "id": "1234", + "source": "<my url>", + "type": "sample", + "specversion": specversion, + "ext1": "test1", + "ext2": "test2", + } + + data = json.dumps(body) + event = from_http(data, headers) + + assert body["ext1"] == event["ext1"] + assert body["ext2"] == event["ext2"] diff --git a/requirements/test.txt b/requirements/test.txt index 4c9fb75..1d5f308 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -9,3 +9,5 @@ pytest-cov==2.4.0 sanic aiohttp Pillow +requests +
Structured extensions aren't serialized top level in to_http result ## Actual Behavior ```python from cloudevents.sdk.http_events import CloudEvent attributes = {"source": "<source-url>", "type": "com.issue.extensions", "example-extension": "ext1"} data = 'Hello' event = CloudEvent(attributes, data) headers, body = event.to_http() print(body) ``` The above code will produce the following: ``` b'{"specversion": "1.0", "id": "fc713795-93f6-44a8-b67e-7b8bd7071e2a", "source": "<source-url>", "type": "com.issue.extensions", "time": "2020-07-16T22:41:48.222788+00:00", "extensions": {"example-extension": "ext1"}, "data": "Hello"}' ``` When in fact we expectthis to be outputted: ``` b'{"specversion": "1.0", "id": "fc713795-93f6-44a8-b67e-7b8bd7071e2a", "source": "<source-url>", "type": "com.issue.extensions", "time": "2020-07-16T22:41:48.222788+00:00", "example-extension": "ext1", "data": "Hello"}' ``` Current output is readable by python CloudEvents, but possibly not by other cloudevent systems unless I'm misunderstanding extensions.
0.0
0aa01ba5c6eb9c2bc6a583104068a87ca9d66708
[ "cloudevents/tests/test_event_extensions.py::test_to_structured_extensions[0.3]", "cloudevents/tests/test_event_extensions.py::test_to_structured_extensions[1.0]" ]
[ "cloudevents/tests/test_event_extensions.py::test_cloudevent_access_extensions[0.3]", "cloudevents/tests/test_event_extensions.py::test_cloudevent_access_extensions[1.0]", "cloudevents/tests/test_event_extensions.py::test_to_binary_extensions[0.3]", "cloudevents/tests/test_event_extensions.py::test_to_binary_extensions[1.0]", "cloudevents/tests/test_event_extensions.py::test_from_binary_extensions[0.3]", "cloudevents/tests/test_event_extensions.py::test_from_binary_extensions[1.0]", "cloudevents/tests/test_event_extensions.py::test_from_structured_extensions[0.3]", "cloudevents/tests/test_event_extensions.py::test_from_structured_extensions[1.0]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-07-22 10:21:10+00:00
apache-2.0
1,607
cloudevents__sdk-python-72
diff --git a/cloudevents/sdk/http/__init__.py b/cloudevents/sdk/http/__init__.py index 4010148..d08e1a5 100644 --- a/cloudevents/sdk/http/__init__.py +++ b/cloudevents/sdk/http/__init__.py @@ -43,7 +43,8 @@ def from_http( headers: typing.Dict[str, str], data_unmarshaller: types.UnmarshallerType = None, ): - """Unwrap a CloudEvent (binary or structured) from an HTTP request. + """ + Unwrap a CloudEvent (binary or structured) from an HTTP request. :param data: the HTTP request body :type data: typing.IO :param headers: the HTTP headers @@ -82,5 +83,32 @@ def from_http( return CloudEvent(attrs, event.data) -def from_json(): - raise NotImplementedError +def to_json( + event: EventClass, data_marshaller: types.MarshallerType = None +) -> typing.Union[str, bytes]: + """ + Cast an EventClass into a json object + :param event: EventClass which will be converted into a json object + :type event: EventClass + :param data_marshaller: Callable function which will cast event.data + into a json object + :type data_marshaller: typing.Callable + :returns: json object representing the given event + """ + return to_structured_http(event, data_marshaller=data_marshaller)[1] + + +def from_json( + data: typing.Union[str, bytes], + data_unmarshaller: types.UnmarshallerType = None, +) -> EventClass: + """ + Cast json encoded data into an EventClass + :param data: json encoded cloudevent data + :type event: typing.Union[str, bytes] + :param data_unmarshaller: Callable function which will cast json encoded + data into a python object retrievable from returned EventClass.data + :type data_marshaller: typing.Callable + :returns: EventClass representing given cloudevent json object + """ + return from_http(data=data, headers={}, data_unmarshaller=data_unmarshaller) diff --git a/cloudevents/sdk/http/event.py b/cloudevents/sdk/http/event.py index a991918..3f5cfa5 100644 --- a/cloudevents/sdk/http/event.py +++ b/cloudevents/sdk/http/event.py @@ -176,11 +176,3 @@ def to_binary_http( format=converters.TypeBinary, data_marshaller=data_marshaller, ) - - -def to_json(): - raise NotImplementedError - - -def from_json(): - raise NotImplementedError
cloudevents/sdk-python
b2a87a8af6ce900d99f80bcea91094933dfa6e07
diff --git a/cloudevents/tests/test_http_json_methods.py b/cloudevents/tests/test_http_json_methods.py new file mode 100644 index 0000000..293a9ef --- /dev/null +++ b/cloudevents/tests/test_http_json_methods.py @@ -0,0 +1,128 @@ +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +import base64 +import json + +import pytest + +from cloudevents.sdk.http import CloudEvent, from_json, to_json + +test_data = json.dumps({"data-key": "val"}) +test_attributes = { + "type": "com.example.string", + "source": "https://example.com/event-producer", +} + + [email protected]("specversion", ["0.3", "1.0"]) +def test_to_json(specversion): + event = CloudEvent(test_attributes, test_data) + event_json = to_json(event) + event_dict = json.loads(event_json) + + for key, val in test_attributes.items(): + assert event_dict[key] == val + + assert event_dict["data"] == test_data + + [email protected]("specversion", ["0.3", "1.0"]) +def test_to_json_base64(specversion): + data = b"test123" + + event = CloudEvent(test_attributes, data) + event_json = to_json(event) + event_dict = json.loads(event_json) + + for key, val in test_attributes.items(): + assert event_dict[key] == val + + # test data was properly marshalled into data_base64 + data_base64 = event_dict["data_base64"].encode() + test_data_base64 = base64.b64encode(data) + + assert data_base64 == test_data_base64 + + [email protected]("specversion", ["0.3", "1.0"]) +def test_from_json(specversion): + payload = { + "type": "com.example.string", + "source": "https://example.com/event-producer", + "id": "1234", + "specversion": specversion, + "data": {"data-key": "val"}, + } + event = from_json(json.dumps(payload)) + + for key, val in payload.items(): + if key == "data": + assert event.data == payload["data"] + else: + assert event[key] == val + + [email protected]("specversion", ["0.3", "1.0"]) +def test_from_json_base64(specversion): + # Create base64 encoded data + raw_data = {"data-key": "val"} + data = json.dumps(raw_data).encode() + data_base64_str = base64.b64encode(data).decode() + + # Create json payload + payload = { + "type": "com.example.string", + "source": "https://example.com/event-producer", + "id": "1234", + "specversion": specversion, + "data_base64": data_base64_str, + } + payload_json = json.dumps(payload) + + # Create event + event = from_json(payload_json) + + # Test fields were marshalled properly + for key, val in payload.items(): + if key == "data_base64": + # Check data_base64 was unmarshalled properly + assert event.data == raw_data + else: + assert event[key] == val + + [email protected]("specversion", ["0.3", "1.0"]) +def test_json_can_talk_to_itself(specversion): + event = CloudEvent(test_attributes, test_data) + event_json = to_json(event) + + event = from_json(event_json) + + for key, val in test_attributes.items(): + assert event[key] == val + assert event.data == test_data + + [email protected]("specversion", ["0.3", "1.0"]) +def test_json_can_talk_to_itself_base64(specversion): + data = b"test123" + + event = CloudEvent(test_attributes, data) + event_json = to_json(event) + + event = from_json(event_json) + + for key, val in test_attributes.items(): + assert event[key] == val + assert event.data == data
Implement to_json and from_json to_json and from_json in cloudevents.sdk.http.event.py raises notimplemented error
0.0
b2a87a8af6ce900d99f80bcea91094933dfa6e07
[ "cloudevents/tests/test_http_json_methods.py::test_to_json[0.3]", "cloudevents/tests/test_http_json_methods.py::test_to_json[1.0]", "cloudevents/tests/test_http_json_methods.py::test_to_json_base64[0.3]", "cloudevents/tests/test_http_json_methods.py::test_to_json_base64[1.0]", "cloudevents/tests/test_http_json_methods.py::test_from_json[0.3]", "cloudevents/tests/test_http_json_methods.py::test_from_json[1.0]", "cloudevents/tests/test_http_json_methods.py::test_from_json_base64[0.3]", "cloudevents/tests/test_http_json_methods.py::test_from_json_base64[1.0]", "cloudevents/tests/test_http_json_methods.py::test_json_can_talk_to_itself[0.3]", "cloudevents/tests/test_http_json_methods.py::test_json_can_talk_to_itself[1.0]", "cloudevents/tests/test_http_json_methods.py::test_json_can_talk_to_itself_base64[0.3]", "cloudevents/tests/test_http_json_methods.py::test_json_can_talk_to_itself_base64[1.0]" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-07-22 21:52:31+00:00
apache-2.0
1,608
cloudfoundry-community__cf-python-client-181
diff --git a/main/cloudfoundry_client/operations/push/validation/manifest.py b/main/cloudfoundry_client/operations/push/validation/manifest.py index 94c93dc..326bfcf 100644 --- a/main/cloudfoundry_client/operations/push/validation/manifest.py +++ b/main/cloudfoundry_client/operations/push/validation/manifest.py @@ -6,7 +6,7 @@ import yaml class ManifestReader(object): - MEMORY_PATTERN = re.compile(r"^(\d+)([KMGT])B?$") + SIZE_FIELD_PATTERNS = re.compile(r"^(\d+)([MG])B?$") POSITIVE_FIELDS = ["instances", "timeout"] @@ -40,7 +40,7 @@ class ManifestReader(object): raise AssertionError("One of path or docker must be set") else: ManifestReader._absolute_path(manifest_directory, app_manifest) - ManifestReader._convert_memory(app_manifest) + ManifestReader._convert_size_fields(app_manifest) for field in ManifestReader.POSITIVE_FIELDS: ManifestReader._convert_positive(app_manifest, field) for field in ManifestReader.BOOLEAN_FIELDS: @@ -61,25 +61,22 @@ class ManifestReader(object): raise AssertionError("hosts, host, domains, domain and no-hostname are all deprecated. Use the routes attribute") @staticmethod - def _convert_memory(manifest: dict): - if "memory" in manifest: - memory = manifest["memory"].upper() - match = ManifestReader.MEMORY_PATTERN.match(memory) - if match is None: - raise AssertionError("Invalid memory format: %s" % memory) - - memory_number = int(match.group(1)) - if match.group(2) == "K": - memory_number *= 1024 - elif match.group(2) == "M": - memory_number *= 1024 * 1024 - elif match.group(2) == "G": - memory_number *= 1024 * 1024 * 1024 - elif match.group(2) == "T": - memory_number *= 1024 * 1024 * 1024 * 1024 - else: - raise AssertionError("Invalid memory unit: %s" % memory) - manifest["memory"] = int(memory_number / (1024 * 1024)) + def _convert_size_fields(manifest: dict): + for field_name in ["memory", "disk_quota"]: + if field_name in manifest: + field_value = manifest[field_name].upper() + match = ManifestReader.SIZE_FIELD_PATTERNS.match(field_value) + if match is None: + raise AssertionError("Invalid %s format: %s" % (field_name, field_value)) + + size_converted = int(match.group(1)) + if match.group(2) == "M": + size_converted *= 1024 * 1024 + elif match.group(2) == "G": + size_converted *= 1024 * 1024 * 1024 + else: + raise AssertionError("Invalid %s unit: %s" % (field_name, field_value)) + manifest[field_name] = int(size_converted / (1024 * 1024)) @staticmethod def _convert_positive(manifest: dict, field: str):
cloudfoundry-community/cf-python-client
3334af9bdeec36a542eaeff81adcb71a98567cd5
diff --git a/test/operations/push/validation/test_manifest_reader.py b/test/operations/push/validation/test_manifest_reader.py index 25995c3..0182cf2 100644 --- a/test/operations/push/validation/test_manifest_reader.py +++ b/test/operations/push/validation/test_manifest_reader.py @@ -104,17 +104,22 @@ class TestManifestReader(unittest.TestCase): ManifestReader._validate_application_manifest(".", manifest) self.assertEqual(os.path.abspath("test"), manifest["path"]) - def test_memory_in_kb(self): - manifest = dict(memory="2048KB") - ManifestReader._convert_memory(manifest) - self.assertEqual(2, manifest["memory"]) - def test_memory_in_mb(self): manifest = dict(memory="2048MB") - ManifestReader._convert_memory(manifest) + ManifestReader._convert_size_fields(manifest) self.assertEqual(2048, manifest["memory"]) def test_memory_in_gb(self): manifest = dict(memory="1G") - ManifestReader._convert_memory(manifest) + ManifestReader._convert_size_fields(manifest) self.assertEqual(1024, manifest["memory"]) + + def test_disk_quota_in_mb(self): + manifest = dict(disk_quota="2048MB") + ManifestReader._convert_size_fields(manifest) + self.assertEqual(2048, manifest["disk_quota"]) + + def test_disk_quota_in_gb(self): + manifest = dict(disk_quota="1G") + ManifestReader._convert_size_fields(manifest) + self.assertEqual(1024, manifest["disk_quota"])
Push only converts memory but not disk_quota Hi, I get the error "disk_quota, Error: Expected instance of Integer, given an instance of String" because the code only converts memory values: https://github.com/cloudfoundry-community/cf-python-client/blob/3334af9bdeec36a542eaeff81adcb71a98567cd5/main/cloudfoundry_client/operations/push/validation/manifest.py#L64-L65 Best regards, Alex
0.0
3334af9bdeec36a542eaeff81adcb71a98567cd5
[ "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_disk_quota_in_gb", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_disk_quota_in_mb", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_memory_in_gb", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_memory_in_mb" ]
[ "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_application_should_declare_at_least_path_or_docker", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_application_should_declare_either_path_or_docker", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_complex_manifest_should_be_read", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_deprecated_entries_should_not_be_set", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_docker_manifest_should_declare_buildpack_or_image", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_empty_manifest_should_raise_exception", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_manifest_should_be_read", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_name_should_be_set", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_password_should_be_set_if_username_is", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_routes_should_be_an_object_with_attribute", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_username_and_password_are_set_when_image_is", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_username_should_be_set_if_password_is", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_valid_application_with_docker_and_routes", "test/operations/push/validation/test_manifest_reader.py::TestManifestReader::test_valid_application_with_path_and_routes" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-12-03 17:19:12+00:00
apache-2.0
1,609
cloudinary__pycloudinary-158
diff --git a/cloudinary/utils.py b/cloudinary/utils.py index bf4cac4..a112aa6 100644 --- a/cloudinary/utils.py +++ b/cloudinary/utils.py @@ -8,6 +8,7 @@ import re import string import struct import time +import urllib import zlib from collections import OrderedDict from datetime import datetime, date @@ -557,7 +558,8 @@ def cloudinary_api_url(action='upload', **options): if not cloud_name: raise ValueError("Must supply cloud_name") resource_type = options.get("resource_type", "image") - return "/".join([cloudinary_prefix, "v1_1", cloud_name, resource_type, action]) + + return encode_unicode_url("/".join([cloudinary_prefix, "v1_1", cloud_name, resource_type, action])) def smart_escape(source, unsafe=r"([^a-zA-Z0-9_.\-\/:]+)"): @@ -962,6 +964,20 @@ def base64_encode_url(url): return b64.decode('ascii') +def encode_unicode_url(url_str): + """ + Quote and encode possible unicode url string (applicable for python2) + + :param url_str: Url string to encode + + :return: Encoded string + """ + if six.PY2: + url_str = urllib.quote(url_str.encode('utf-8'), ":/?#[]@!$&'()*+,;=") + + return url_str + + def __json_serializer(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)):
cloudinary/pycloudinary
374cb5773d29fc01b6af5283428dc8651aa6c50d
diff --git a/test/test_utils.py b/test/test_utils.py index 591cbab..ccb82fc 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -10,7 +10,7 @@ import six from mock import patch import cloudinary.utils -from cloudinary.utils import build_list_of_dicts, json_encode +from cloudinary.utils import build_list_of_dicts, json_encode, encode_unicode_url from test.helper_test import TEST_IMAGE, REMOTE_TEST_IMAGE @@ -816,6 +816,10 @@ class TestUtils(unittest.TestCase): json_encode({"t": self}) self.assertIn("is not JSON serializable", str(te.exception)) + def test_encode_unicode_url(self): + self.assertEqual("string", encode_unicode_url("string")) + self.assertEqual("encoded", encode_unicode_url(u"encoded")) + def test_is_remote_url(self): self.assertFalse(cloudinary.utils.is_remote_url(TEST_IMAGE)) self.assertTrue(cloudinary.utils.is_remote_url(REMOTE_TEST_IMAGE))
Using unicode literals in config causes UnicodeDecodeError on upload If the `CLOUDINARY` settings are defined in a python file which uses unicode literals (or if the `cloud_name` is defined as a unicode literal manually) there is an error thrown deep down inside `httplib.py`. The reason for this is that `cloudinary_api_url` joins together all of the url parts which, if one of these elements is unicode, generates a URL which is a unicode string. ``` In [1]: "/".join(('non-unicode', u'unicode')) Out[1]: u'non-unicode/unicode' ``` There was a python bug raised for this here https://bugs.python.org/issue11898 but it looks like it was treated as an invalid input. I guess you could say the same thing here and that passing a unicode string is undefined behaviour but at least this bug might help someone else with this problem.
0.0
374cb5773d29fc01b6af5283428dc8651aa6c50d
[ "test/test_utils.py::TestUtils::test_angle", "test/test_utils.py::TestUtils::test_array_should_define_a_set_of_variables", "test/test_utils.py::TestUtils::test_aspect_ratio", "test/test_utils.py::TestUtils::test_audio_codec", "test/test_utils.py::TestUtils::test_audio_frequency", "test/test_utils.py::TestUtils::test_background", "test/test_utils.py::TestUtils::test_base_transformation_array", "test/test_utils.py::TestUtils::test_base_transformations", "test/test_utils.py::TestUtils::test_bit_rate", "test/test_utils.py::TestUtils::test_border", "test/test_utils.py::TestUtils::test_build_list_of_dicts", "test/test_utils.py::TestUtils::test_cloud_name", "test/test_utils.py::TestUtils::test_cloud_name_options", "test/test_utils.py::TestUtils::test_cname", "test/test_utils.py::TestUtils::test_cname_subdomain", "test/test_utils.py::TestUtils::test_crop", "test/test_utils.py::TestUtils::test_default_image", "test/test_utils.py::TestUtils::test_density", "test/test_utils.py::TestUtils::test_disallow_url_suffix_in_non_upload_types", "test/test_utils.py::TestUtils::test_disallow_url_suffix_with_slash_or_dot", "test/test_utils.py::TestUtils::test_disallow_use_root_path_if_not_image_upload", "test/test_utils.py::TestUtils::test_dollar_key_should_define_a_variable", "test/test_utils.py::TestUtils::test_dpr", "test/test_utils.py::TestUtils::test_duration", "test/test_utils.py::TestUtils::test_effect", "test/test_utils.py::TestUtils::test_effect_with_array", "test/test_utils.py::TestUtils::test_effect_with_dict", "test/test_utils.py::TestUtils::test_encode_context", "test/test_utils.py::TestUtils::test_encode_unicode_url", "test/test_utils.py::TestUtils::test_end_offset", "test/test_utils.py::TestUtils::test_escape_public_id", "test/test_utils.py::TestUtils::test_escape_public_id_with_non_ascii_characters", "test/test_utils.py::TestUtils::test_fetch", "test/test_utils.py::TestUtils::test_fetch_format", "test/test_utils.py::TestUtils::test_fetch_overlay", "test/test_utils.py::TestUtils::test_flags", "test/test_utils.py::TestUtils::test_folder_version", "test/test_utils.py::TestUtils::test_format", "test/test_utils.py::TestUtils::test_html_width_height_on_angle", "test/test_utils.py::TestUtils::test_html_width_height_on_crop_fit_limit", "test/test_utils.py::TestUtils::test_http_escape", "test/test_utils.py::TestUtils::test_http_private_cdn", "test/test_utils.py::TestUtils::test_ignore_http", "test/test_utils.py::TestUtils::test_is_remote_url", "test/test_utils.py::TestUtils::test_json_encode", "test/test_utils.py::TestUtils::test_keyframe_interval", "test/test_utils.py::TestUtils::test_merge", "test/test_utils.py::TestUtils::test_no_empty_transformation", "test/test_utils.py::TestUtils::test_norm_auto_range_value", "test/test_utils.py::TestUtils::test_norm_range_value", "test/test_utils.py::TestUtils::test_not_sign_the_url_suffix", "test/test_utils.py::TestUtils::test_offset", "test/test_utils.py::TestUtils::test_original_width_and_height", "test/test_utils.py::TestUtils::test_overlay", "test/test_utils.py::TestUtils::test_overlay_error_1", "test/test_utils.py::TestUtils::test_overlay_error_2", "test/test_utils.py::TestUtils::test_overlay_options", "test/test_utils.py::TestUtils::test_page", "test/test_utils.py::TestUtils::test_put_format_after_url_suffix", "test/test_utils.py::TestUtils::test_raw_transformation", "test/test_utils.py::TestUtils::test_resource_type", "test/test_utils.py::TestUtils::test_responsive_width", "test/test_utils.py::TestUtils::test_secure_akamai", "test/test_utils.py::TestUtils::test_secure_distibution", "test/test_utils.py::TestUtils::test_secure_distribution", "test/test_utils.py::TestUtils::test_secure_distribution_overwrite", "test/test_utils.py::TestUtils::test_secure_non_akamai", "test/test_utils.py::TestUtils::test_shorten", "test/test_utils.py::TestUtils::test_should_place_defined_variables_before_ordered", "test/test_utils.py::TestUtils::test_should_sort_defined_variable", "test/test_utils.py::TestUtils::test_should_support_auto_value", "test/test_utils.py::TestUtils::test_should_support_auto_width", "test/test_utils.py::TestUtils::test_should_support_string_interpolation", "test/test_utils.py::TestUtils::test_should_support_text_values", "test/test_utils.py::TestUtils::test_signed_url", "test/test_utils.py::TestUtils::test_size", "test/test_utils.py::TestUtils::test_start_offset", "test/test_utils.py::TestUtils::test_streaming_profile", "test/test_utils.py::TestUtils::test_support_a_percent_value", "test/test_utils.py::TestUtils::test_support_cdn_subdomain_with_secure_on_if_using_shared_domain", "test/test_utils.py::TestUtils::test_support_secure_cdn_subdomain_true_override_with_secure", "test/test_utils.py::TestUtils::test_support_url_suffix_for_private_cdn", "test/test_utils.py::TestUtils::test_support_url_suffix_for_raw_uploads", "test/test_utils.py::TestUtils::test_support_use_root_path_for_private_cdn", "test/test_utils.py::TestUtils::test_support_use_root_path_for_shared_cdn", "test/test_utils.py::TestUtils::test_support_use_root_path_together_with_url_suffix_for_private_cdn", "test/test_utils.py::TestUtils::test_transformation_array", "test/test_utils.py::TestUtils::test_transformation_simple", "test/test_utils.py::TestUtils::test_translate_if", "test/test_utils.py::TestUtils::test_type", "test/test_utils.py::TestUtils::test_underlay", "test/test_utils.py::TestUtils::test_user_agent", "test/test_utils.py::TestUtils::test_various_options", "test/test_utils.py::TestUtils::test_video_codec", "test/test_utils.py::TestUtils::test_video_sampling" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-07-23 13:41:44+00:00
mit
1,610
cloudpassage__cloudpassage-halo-python-sdk-195
diff --git a/cloudpassage/sanity.py b/cloudpassage/sanity.py index bb4bd7c..ec5b497 100644 --- a/cloudpassage/sanity.py +++ b/cloudpassage/sanity.py @@ -20,7 +20,7 @@ def validate_object_id(object_id): """ - rex = re.compile('^[A-Za-z0-9]+$') + rex = re.compile('^[A-Za-z0-9-]+$') if is_it_a_string(object_id): if not rex.match(object_id): msg = "Object ID failed validation: {}".format(object_id)
cloudpassage/cloudpassage-halo-python-sdk
1f904b7602bfbc94bb5dae5b91299c9752f3b88c
diff --git a/tests/unit/test_unit_sanity.py b/tests/unit/test_unit_sanity.py index 60eca25..763a1f3 100644 --- a/tests/unit/test_unit_sanity.py +++ b/tests/unit/test_unit_sanity.py @@ -8,11 +8,21 @@ class TestUnitSanity: sample_object_id = "951ffd865e4f11e59ba055477bd3e868" assert sanity.validate_object_id(sample_object_id) + def test_valid_object_id_hyphenated(self): + sample_object_id = "be35b286-a36c-11e9-bb19-71dc777df26f" + assert sanity.validate_object_id(sample_object_id) + def test_valid_object_id_list(self): sample_object_id = ["951ffd865e4f11e59ba055477bd3e868", "951ffd865e4f11e59ba055477bd3e999"] assert sanity.validate_object_id(sample_object_id) + def test_valid_object_id_list_mixed_format(self): + sample_object_id = ["951ffd865e4f11e59ba055477bd3e868", + "951ffd865e4f11e59ba055477bd3e999", + "be35b286-a36c-11e9-bb19-71dc777df26f"] + assert sanity.validate_object_id(sample_object_id) + def test_invalid_object_id_list(self): rejected = False sample_object_id = ["951ffd865e4f11e59ba055477bd3e868",
New ID format fails validation Issue IDs for `/v3/issues` have a format like this:`be35b286-a36c-11e9-bb19-71dc777df26f` This doesn't pass object ID validation.
0.0
1f904b7602bfbc94bb5dae5b91299c9752f3b88c
[ "tests/unit/test_unit_sanity.py::TestUnitSanity::test_valid_object_id_hyphenated", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_valid_object_id_list_mixed_format" ]
[ "tests/unit/test_unit_sanity.py::TestUnitSanity::test_valid_object_id", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_valid_object_id_list", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_invalid_object_id_list", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_invalid_object_id", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_invalid_object_type", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_validate_hostname_mtg", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_validate_hostname_nonexist_vpg", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_validate_hostname_not_cp", "tests/unit/test_unit_sanity.py::TestUnitSanity::test_validate_borky" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-07-16 21:59:40+00:00
bsd-3-clause
1,611
cloudtools__stacker-646
diff --git a/stacker/lookups/handlers/file.py b/stacker/lookups/handlers/file.py index 2ea8893..a57af66 100644 --- a/stacker/lookups/handlers/file.py +++ b/stacker/lookups/handlers/file.py @@ -136,7 +136,7 @@ def _parameterize_string(raw): s_index = match.end() if not parts: - return raw + return GenericHelperFn(raw) parts.append(raw[s_index:]) return GenericHelperFn({u"Fn::Join": [u"", parts]}) @@ -152,7 +152,7 @@ def parameterized_codec(raw, b64): call Returns: - :class:`troposphere.GenericHelperFn`: output to be included in a + :class:`troposphere.AWSHelperFn`: output to be included in a CloudFormation template. """ diff --git a/stacker/providers/aws/default.py b/stacker/providers/aws/default.py index 1c47ecd..369d0b9 100644 --- a/stacker/providers/aws/default.py +++ b/stacker/providers/aws/default.py @@ -825,9 +825,17 @@ class Provider(BaseProvider): self.cloudformation, fqn, template, parameters, tags, 'UPDATE', service_role=self.service_role, **kwargs ) + old_parameters_as_dict = self.params_as_dict(old_parameters) + new_parameters_as_dict = self.params_as_dict( + [x + if x.get('ParameterValue') + else {'ParameterKey': x['ParameterKey'], + 'ParameterValue': old_parameters_as_dict[x['ParameterKey']]} + for x in parameters] + ) params_diff = diff_parameters( - self.params_as_dict(old_parameters), - self.params_as_dict(parameters)) + old_parameters_as_dict, + new_parameters_as_dict) action = "replacements" if self.replacements_only else "changes" full_changeset = changes
cloudtools/stacker
0a5652a7580232a701b6abb984537b941a446ee0
diff --git a/stacker/tests/lookups/handlers/test_file.py b/stacker/tests/lookups/handlers/test_file.py index c2eb93f..312f71a 100644 --- a/stacker/tests/lookups/handlers/test_file.py +++ b/stacker/tests/lookups/handlers/test_file.py @@ -9,7 +9,7 @@ import mock import base64 import yaml import json -from troposphere import Base64, Join +from troposphere import Base64, GenericHelperFn, Join from stacker.lookups.handlers.file import (json_codec, handler, parameterized_codec, yaml_codec) @@ -46,12 +46,21 @@ class TestFileTranslator(unittest.TestCase): ) out = parameterized_codec(u'Test {{Interpolation}} Here', True) + self.assertEqual(Base64, out.__class__) self.assertTemplateEqual(expected, out) def test_parameterized_codec_plain(self): expected = Join(u'', [u'Test ', {u'Ref': u'Interpolation'}, u' Here']) out = parameterized_codec(u'Test {{Interpolation}} Here', False) + self.assertEqual(GenericHelperFn, out.__class__) + self.assertTemplateEqual(expected, out) + + def test_parameterized_codec_plain_no_interpolation(self): + expected = u'Test Without Interpolation Here' + + out = parameterized_codec(u'Test Without Interpolation Here', False) + self.assertEqual(GenericHelperFn, out.__class__) self.assertTemplateEqual(expected, out) def test_yaml_codec_raw(self):
file lookup returning <type 'unicode'> where it previously returned <class 'troposphere.AWSHelperFn'> As of 1.4.0, the use of the `${file parameterized }` lookup no longer works with blueprints using variable type of `troposphere.AWSHelperFn`. This was working in previous versions - most recently 1.3.0. ### Error ``` File "/usr/local/lib/python2.7/site-packages/stacker/plan.py", line 93, in _run_once status = self.fn(self.stack, status=self.status) File "/usr/local/lib/python2.7/site-packages/stacker/actions/build.py", line 321, in _launch_stack stack.resolve(self.context, self.provider) File "/usr/local/lib/python2.7/site-packages/stacker/stack.py", line 196, in resolve self.blueprint.resolve_variables(self.variables) File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 452, in resolve_variables self.name File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 226, in resolve_variable value = validate_variable_type(var_name, var_type, value) File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 147, in validate_variable_type "type: %s." % (var_name, var_type, type(value)) ValueError: Value for variable ExampleParameter must be of type <class 'troposphere.AWSHelperFn'>. Actual type: <type 'unicode'>. ``` ### System Information **Operating System:** Mac OS X 10.13.6 build 17G65 **Python Version:** 2.7.14 **Stacker Version:** 1.4.0 ### Files ``` ├── top-level-folder │ ├── blueprints │ │ ├── __init__.py │ │ └── example_blueprint.py │ ├── file-to-reference.json │ ├── example.env │ └── stacker-config.yaml ``` #### stacker-config.yaml ``` namespace: example stacker_bucket: "" sys_path: ./ stacks: example-stack: class_path: blueprints.example_blueprint.BlueprintClass enabled: true variables: ExampleParameter: ${file parameterized:file://file-to-reference.json} ``` #### blueprints/example_blueprint.py ```python from troposphere import AWSHelperFn from stacker.blueprints.base import Blueprint class BlueprintClass(Blueprint): VARIABLES = { 'ExampleParameter': { 'type': AWSHelperFn } } ```
0.0
0a5652a7580232a701b6abb984537b941a446ee0
[ "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_plain_no_interpolation" ]
[ "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_plain", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_parameterized_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_json_codec_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_json", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_unknown_codec", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_yaml_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_yaml", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_file_loaded", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_json_codec_raw", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_plain", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_json_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_yaml_codec_raw", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_yaml_codec_parameterized" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-08-08 18:16:01+00:00
bsd-2-clause
1,612
cltk__cltk-629
diff --git a/cltk/lemmatize/latin/backoff.py b/cltk/lemmatize/latin/backoff.py index ab5a3be2..46497c47 100755 --- a/cltk/lemmatize/latin/backoff.py +++ b/cltk/lemmatize/latin/backoff.py @@ -518,13 +518,14 @@ class BackoffLatinLemmatizer(object): self.pos_train_sents, self.train_sents, self.test_sents = _randomize_data(self.train, self.seed) def _define_lemmatizer(self): + # Suggested backoff chain--should be tested for optimal order backoff0 = None backoff1 = IdentityLemmatizer() backoff2 = TrainLemmatizer(model=self.LATIN_OLD_MODEL, backoff=backoff1) backoff3 = PPLemmatizer(regexps=self.latin_verb_patterns, pps=self.latin_pps, backoff=backoff2) - backoff4 = UnigramLemmatizer(self.train_sents, backoff=backoff3) - backoff5 = RegexpLemmatizer(self.latin_sub_patterns, backoff=backoff4) - backoff6 = TrainLemmatizer(model=self.LATIN_MODEL, backoff=backoff5) + backoff4 = RegexpLemmatizer(self.latin_sub_patterns, backoff=backoff3) + backoff5 = UnigramLemmatizer(self.train_sents, backoff=backoff4) + backoff6 = TrainLemmatizer(model=self.LATIN_MODEL, backoff=backoff5) #backoff7 = BigramPOSLemmatizer(self.pos_train_sents, include=['cum'], backoff=backoff6) #lemmatizer = backoff7 lemmatizer = backoff6 diff --git a/cltk/tokenize/word.py b/cltk/tokenize/word.py index b1329109..34b2f160 100644 --- a/cltk/tokenize/word.py +++ b/cltk/tokenize/word.py @@ -8,6 +8,7 @@ from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters import re +# Cleanup these imports—most are not used! from nltk.data import load from nltk.tokenize.casual import (TweetTokenizer, casual_tokenize) from nltk.tokenize.mwe import MWETokenizer @@ -41,20 +42,28 @@ class WordTokenizer: # pylint: disable=too-few-public-methods """Take language as argument to the class. Check availability and setup class variables.""" self.language = language - self.available_languages = ['arabic', 'latin', 'french', 'old_norse'] + self.available_languages = ['arabic', + 'french', + 'greek', + 'latin', + 'old_norse'] assert self.language in self.available_languages, \ "Specific tokenizer not available for '{0}'. Only available for: '{1}'.".format(self.language, # pylint: disable=line-too-long - self.available_languages) # pylint: disable=line-too-long + self.available_languages) # pylint: disable=line-too-long + # ^^^ Necessary? since we have an 'else' in `tokenize` + def tokenize(self, string): """Tokenize incoming string.""" - - if self.language == 'latin': - tokens = tokenize_latin_words(string) + + if self.language == 'arabic': + tokens = tokenize_arabic_words(string) elif self.language == 'french': tokens = tokenize_french_words(string) - elif self.language == 'arabic': - tokens = tokenize_arabic_words(string) + elif self.language == 'greek': + tokens = tokenize_greek_words(string) + elif self.language == 'latin': + tokens = tokenize_latin_words(string) elif self.language == 'old_norse': tokens = tokenize_old_norse_words(string) else: @@ -101,6 +110,56 @@ def nltk_tokenize_words(string, attached_period=False, language=None): return new_tokens +def tokenize_arabic_words(text): + + """ + Tokenize text into words + @param text: the input text. + @type text: unicode. + @return: list of words. + @rtype: list. + """ + specific_tokens = [] + if not text: + return specific_tokens + else: + specific_tokens = araby.tokenize(text) + return specific_tokens + + +def tokenize_french_words(string): + assert isinstance(string, str), "Incoming string must be type str." + + # normalize apostrophes + + text = re.sub(r"’", r"'", string) + + # Dealing with punctuation + text = re.sub(r"\'", r"' ", text) + text = re.sub("(?<=.)(?=[.!?)(\";:,«»\-])", " ", text) + + results = str.split(text) + return (results) + + +def tokenize_greek_words(text): + """ + Tokenizer divides the string into a list of substrings. This is a placeholder + function that returns the default NLTK word tokenizer until + Greek-specific options are added. + + Example: + >>> text = 'Θουκυδίδης Ἀθηναῖος ξυνέγραψε τὸν πόλεμον τῶν Πελοποννησίων καὶ Ἀθηναίων,' + >>> tokenize_greek_words(text) + ['Θουκυδίδης', 'Ἀθηναῖος', 'ξυνέγραψε', 'τὸν', 'πόλεμον', 'τῶν', 'Πελοποννησίων', 'καὶ', 'Ἀθηναίων', ','] + + :param string: This accepts the string value that needs to be tokenized + :returns: A list of substrings extracted from the string + """ + + return nltk_tokenize_words(text) # Simplest implementation to start + + def tokenize_latin_words(string): """ Tokenizer divides the string into a list of substrings @@ -211,38 +270,6 @@ def tokenize_latin_words(string): return specific_tokens -def tokenize_french_words(string): - assert isinstance(string, str), "Incoming string must be type str." - - # normalize apostrophes - - text = re.sub(r"’", r"'", string) - - # Dealing with punctuation - text = re.sub(r"\'", r"' ", text) - text = re.sub("(?<=.)(?=[.!?)(\";:,«»\-])", " ", text) - - results = str.split(text) - return (results) - - -def tokenize_arabic_words(text): - - """ - Tokenize text into words - @param text: the input text. - @type text: unicode. - @return: list of words. - @rtype: list. - """ - specific_tokens = [] - if not text: - return specific_tokens - else: - specific_tokens = araby.tokenize(text) - return specific_tokens - - def tokenize_old_norse_words(text): """ diff --git a/docs/greek.rst b/docs/greek.rst index 4ddcca68..9937650f 100644 --- a/docs/greek.rst +++ b/docs/greek.rst @@ -856,6 +856,20 @@ the Greek language. Currently, the only available dialect is Attic as reconstruc Out[3]: '[di.ó.tʰen kɑj dis.kɛ́ːp.trọː ti.mɛ̂ːs o.kʰy.ron zdêw.gos ɑ.trẹː.dɑ̂n stó.lon ɑr.gẹ́ː.ɔːn]' +Word Tokenization +================= + +.. code-block:: python + + In [1]: from cltk.tokenize.word import WordTokenizer + + In [2]: word_tokenizer = WordTokenizer('greek') + + In [3]: text = 'Θουκυδίδης Ἀθηναῖος ξυνέγραψε τὸν πόλεμον τῶν Πελοποννησίων καὶ Ἀθηναίων,' + + In [4]: word_tokenizer.tokenize(text) + Out[4]: ['Θουκυδίδης', 'Ἀθηναῖος', 'ξυνέγραψε', 'τὸν', 'πόλεμον', 'τῶν', 'Πελοποννησίων', 'καὶ', 'Ἀθηναίων', ','] + Word2Vec ========
cltk/cltk
43396058c512c1732db43494a67795d765cf9335
diff --git a/cltk/tests/test_tokenize.py b/cltk/tests/test_tokenize.py index 668292ee..c5856900 100644 --- a/cltk/tests/test_tokenize.py +++ b/cltk/tests/test_tokenize.py @@ -61,6 +61,23 @@ class TestSequenceFunctions(unittest.TestCase): # pylint: disable=R0904 self.assertEqual(len(tokenized_sentences), len(good_tokenized_sentences)) ''' + + def test_greek_word_tokenizer(self): + """Test Latin-specific word tokenizer.""" + word_tokenizer = WordTokenizer('greek') + + # Test sources: + # - Thuc. 1.1.1 + + test = "Θουκυδίδης Ἀθηναῖος ξυνέγραψε τὸν πόλεμον τῶν Πελοποννησίων καὶ Ἀθηναίων, ὡς ἐπολέμησαν πρὸς ἀλλήλους, ἀρξάμενος εὐθὺς καθισταμένου καὶ ἐλπίσας μέγαν τε ἔσεσθαι καὶ ἀξιολογώτατον τῶν προγεγενημένων, τεκμαιρόμενος ὅτι ἀκμάζοντές τε ᾖσαν ἐς αὐτὸν ἀμφότεροι παρασκευῇ τῇ πάσῃ καὶ τὸ ἄλλο Ἑλληνικὸν ὁρῶν ξυνιστάμενον πρὸς ἑκατέρους, τὸ μὲν εὐθύς, τὸ δὲ καὶ διανοούμενον." + + target = ['Θουκυδίδης', 'Ἀθηναῖος', 'ξυνέγραψε', 'τὸν', 'πόλεμον', 'τῶν', 'Πελοποννησίων', 'καὶ', 'Ἀθηναίων', ',', 'ὡς', 'ἐπολέμησαν', 'πρὸς', 'ἀλλήλους', ',', 'ἀρξάμενος', 'εὐθὺς', 'καθισταμένου', 'καὶ', 'ἐλπίσας', 'μέγαν', 'τε', 'ἔσεσθαι', 'καὶ', 'ἀξιολογώτατον', 'τῶν', 'προγεγενημένων', ',', 'τεκμαιρόμενος', 'ὅτι', 'ἀκμάζοντές', 'τε', 'ᾖσαν', 'ἐς', 'αὐτὸν', 'ἀμφότεροι', 'παρασκευῇ', 'τῇ', 'πάσῃ', 'καὶ', 'τὸ', 'ἄλλο', 'Ἑλληνικὸν', 'ὁρῶν', 'ξυνιστάμενον', 'πρὸς', 'ἑκατέρους', ',', 'τὸ', 'μὲν', 'εὐθύς', ',', 'τὸ', 'δὲ', 'καὶ', 'διανοούμενον', '.'] + + result = word_tokenizer.tokenize(test) + + self.assertEqual(result, target) + + def test_latin_word_tokenizer(self): """Test Latin-specific word tokenizer.""" word_tokenizer = WordTokenizer('latin') @@ -213,7 +230,7 @@ class TestSequenceFunctions(unittest.TestCase): # pylint: disable=R0904 'vilja', 'þeira', '.'] word_tokenizer = WordTokenizer('old_norse') result = word_tokenizer.tokenize(text) - print(result) + #print(result) self.assertTrue(result == target) if __name__ == '__main__':
Greek not among word tokenizers Hi! I attempted to use the Greek word tokenizer for a really quick search of a plain text file, as follows: <pre> from cltk.tokenize.word import WordTokenizer word_tokenizer = WordTokenizer('greek') for word in word_tokenizer.tokenize('files/plain_text/1-23_1.1-42.txt'): if word.endswith('εαι'): print(word) </pre> When I tried to call the script, I got the following error: `AssertionError: Specific tokenizer not available for 'greek'. Only available for: '['arabic', 'latin', 'french', 'old_norse']'.` Thanks!
0.0
43396058c512c1732db43494a67795d765cf9335
[ "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_french_line_tokenizer", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_greek_word_tokenizer" ]
[ "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_french_line_tokenizer_include_blanks", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_latin_word_tokenizer", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_line_tokenizer", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_line_tokenizer_include_blanks", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_nltk_tokenize_words", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_nltk_tokenize_words_assert", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_nltk_tokenize_words_attached", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_old_norse_word_tokenizer", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_sanskrit_nltk_tokenize_words", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_sanskrit_nltk_tokenize_words_attached", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_sentence_tokenizer_latin", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_tokenize_arabic_words", "cltk/tests/test_tokenize.py::TestSequenceFunctions::test_word_tokenizer_french" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-01-28 03:57:26+00:00
mit
1,613
cltk__cltk-661
diff --git a/cltk/corpus/swadesh.py b/cltk/corpus/swadesh.py index 9d1b3759..0c1a960d 100644 --- a/cltk/corpus/swadesh.py +++ b/cltk/corpus/swadesh.py @@ -7,6 +7,8 @@ swadesh_la = ['ego', 'tū', 'is, ea, id', 'nōs', 'vōs', 'eī, iī, eae, ea', ' swadesh_gr = ['ἐγώ', 'σύ', 'αὐτός, οὗ, ὅς, ὁ, οὗτος', 'ἡμεῖς', 'ὑμεῖς', 'αὐτοί', 'ὅδε', 'ἐκεῖνος', 'ἔνθα, ἐνθάδε, ἐνταῦθα', 'ἐκεῖ', 'τίς', 'τί', 'ποῦ, πόθι', 'πότε, πῆμος', 'πῶς', 'οὐ, μή', 'πᾶς, ἅπᾱς', 'πολύς', 'τις', 'ὀλίγος, βαιός, παῦρος', 'ἄλλος, ἕτερος', 'εἷς', 'δύο', 'τρεῖς', 'τέσσαρες', 'πέντε', 'μέγας', 'μακρός', 'εὐρύς', 'πυκνός', 'βαρύς', 'μῑκρός', 'βραχύς', 'στενός', 'μανός', 'γυνή', 'ἀνήρ', 'ἄνθρωπος', 'τέκνον, παῖς, παιδίον', 'γυνή', 'ἀνήρ', 'μήτηρ', 'πατήρ', 'ζῷον', 'ἰχθύς', 'ὄρνις, πετεινόν', 'κύων', 'φθείρ', 'ὄφις', 'ἑρπετόν, σκώληξ, ἕλμινς', 'δένδρον', 'ὕλη', 'βακτηρία, ῥάβδος', 'καρπός', 'σπέρμα', 'φύλλον', 'ῥίζα', 'φλοιός', 'ἄνθος', 'χλόη', 'δεσμός, σχοινίον', 'δέρμα', 'κρέας', 'αἷμα', 'ὀστοῦν', 'δημός', 'ᾠόν', 'κέρας', 'οὐρά, κέρκος', 'πτερόν', 'θρίξ, κόμη', 'κεφαλή', 'οὖς', 'ὀφθαλμός', 'ῥίς', 'στόμα', 'ὀδούς', 'γλῶσσα', 'ὄνυξ', 'πούς', 'κῶλον, σκέλος', 'γόνυ', 'χείρ', 'πτέρυξ', 'γαστήρ, κοιλία', 'ἔντερα, σπλάγχνα', 'αὐχήν, τράχηλος', 'νῶτον', 'μαστός, στῆθος', 'καρδία', 'ἧπαρ', 'πίνω', 'ἐσθίω, ἔφαγον', 'δάκνω', 'σπάω', 'πτύω', 'ἐμέω', 'φυσάω', 'πνέω', 'γελάω', 'βλέπω, ὁράω, εἶδον', 'ἀκούω, ἀΐω', 'οἶδα, γιγνώσκω', 'νομίζω, δοκέω, νοέω, οἴομαι', 'ὀσφραίνομαι', 'φοβέομαι', 'καθεύδω, εὕδω, εὐνάζομαι, κοιμάομαι, ἰαύω', 'ζάω, βιόω, οἰκέω', 'ἀποθνῄσκω, θνῄσκω, τελευτάω, ὄλομαι', 'ἀποκτείνω, ἔπεφνον', 'μάχομαι', 'θηρεύω, θηράω, ἰχνεύω, κυνηγετέω, κυνηγέω, σεύω', 'τύπτω', 'τέμνω', 'σχίζω', 'κεντέω', 'κνάω', 'ὀρύσσω, σκᾰ́πτω', 'νέω, κολυμβάω', 'πέτομαι', 'περιπατέω, πατέω, στείχω, βαίνω, βαδίζω, πεζεύω, πορεύω', 'ἱκνέομαι, ἵκω, ἔρχομαι, εἶμι', 'κεῖμαι', 'καθίζω', 'ἵστημι', 'τρέπω', 'πίπτω', 'παρέχω, δίδωμι', 'ἔχω', 'πιέζω', 'τρίβω', 'λούω, πλύνω, νίπτω', 'ἀπομάσσω', 'ἕλκω', 'ὠθέω', 'ῥίπτω, βάλλω', 'δέω', 'ῥάπτω', 'ἀριθμέω', 'φημί, λέγω, ἐνέπω', 'ἀείδω', 'παίζω', 'νέω', 'ῥέω', 'πήγνυμαι', 'αὐξάνω', 'ἥλιος', 'σελήνη', 'ἀστήρ', 'ὕδωρ', 'ὑετός, βροχή', 'ποταμός', 'λίμνη', 'θάλασσα, πέλαγος, πόντος', 'ἅλς', 'λίθος', 'ἄμμος', 'κόνις', 'γῆ, χθών', 'νέφος', 'ὀμίχλη', 'οὐρανός', 'ἄνεμος', 'χιών', 'κρύσταλλος', 'καπνός', 'πῦρ', 'τέφρα', 'καίω', 'ὁδός', 'ἄκρα, ὄρος, βουνός', 'ἐρυθρός, πυρρός', 'χλωρός', 'ξανθός', 'λευκός', 'μέλας', 'νύξ', 'ἡμέρα, ἦμαρ', 'ἔτος', 'θερμός', 'ψυχρός', 'μεστός, πλήρης', 'νέος', 'παλαιός', 'ἀγαθός', 'κακός', 'σαπρός', 'θολερός', 'εὐθύς, ὀρθός', 'κυκλοτερής', 'τομός, ὀξύς', 'ἀμβλύς, βαρύς', 'λεῖος', 'ὑγρός', 'ξηρός', 'δίκαιος', 'ἐγγύς', 'μακράν', 'δεξιός', 'ἀριστερός, εὐώνυμος', 'ἐν', 'ἐν', 'μετά, σύν', 'καί, τε', 'εἰ', 'ὅτι', 'ὄνομα'] +swadesh_txb = ['ñäś', 'tuwe', 'su', 'wes', 'yes', 'cey', 'se', 'su, samp', 'tane', 'tane, omp', 'kᵤse', 'kᵤse', 'ente', 'ente', 'mäkte', 'mā', 'poñc', 'māka', 'ṣemi', 'totka', 'allek', 'ṣe', 'wi', 'trey', 'śtwer', 'piś', 'orotstse', 'pärkare', 'aurtstse', '', 'kramartse', 'lykaśke, totka', '', '', '', 'klyiye, śana', 'eṅkwe', 'śaumo', 'śamaśke', 'śana', 'petso', 'mācer', 'pācer', 'luwo', 'laks', 'salamo luwo', 'ku', 'pärśeriñ', 'arṣāklo, auk', 'yel', 'stām', 'wartto, karāś', 'śakātai', 'oko', 'sārm, śäktālye', 'pilta', 'witsako', 'enmetre', 'pyāpyo', 'atiyai', '', 'ewe, yetse', 'misa', 'yasar', 'āy, āsta pl', 'ṣalype', '', 'krorīyai', 'pako', 'paruwa', 'matsi', 'āśce', 'klautso', 'ek', 'meli', 'koyṃ', 'keme', 'kantwo', '', 'paiyye', 'ckāckai', 'keni', 'ṣar', '', 'kātso', 'kātso', 'kor', 'sark', 'päścane', 'arañce', 'wästarye', 'yokäṃ', 'śuwaṃ', '', '', 'pitke', 'aṅkaiṃ', 'pinaṣṣnäṃ', 'anāṣṣäṃ, satāṣṣäṃ', 'ker-', 'lkāṣṣäṃ', 'klyauṣäṃ', 'aiśtär, kärsanaṃ', 'pälskanaṃ', 'warṣṣäṃ', 'prāskaṃ', 'kläntsaṃ', 'śaiṃ', 'sruketär', 'kauṣäṃ', 'witāre', 'śerītsi', 'karnäṣṣäṃ', 'karsnaṃ, latkanaṃ', 'kautanaṃ', 'tsopäṃ', '', 'rapanaṃ', 'nāṣṣäṃ', 'pluṣäṃ', 'yaṃ', 'känmaṣṣäṃ', 'lyaśäṃ', 'ṣamäṃ, āṣṣäṃ', 'kaltär', 'kluttaṅktär, sporttotär', 'kloyotär', 'aiṣṣäṃ', '', 'klupnātär, nuskaṣṣäṃ', 'lyuwetär, kantanatär', 'laikanatär', 'lyyāstär', 'slaṅktär', 'nätkanaṃ', 'karṣṣäṃ, saläṣṣäṃ', 'śanmästär, kärkaṣṣäṃ', '', 'ṣäṃṣtär', 'weṣṣäṃ', 'piyaṃ', 'kāñmäṃ', 'pluṣäṃ', 'reṣṣäṃ', '', 'staukkanatär', 'kauṃ', 'meñe', 'ścirye', 'war', 'swese', 'cake', 'lyam', 'samudtär', 'salyiye', 'kärweñe', 'warañc', 'tweye, taur', 'keṃ', 'tarkär', '', 'iprer', 'yente', 'śiñcatstse', '', '', 'puwar', 'taur, tweye', 'tsakṣtär,pälketär', 'ytārye', 'ṣale', 'ratre', 'motartstse', 'tute', 'ārkwi', 'erkent-', 'yṣiye', 'kauṃ', 'pikul', 'emalle', 'krośce', 'ite', 'ñuwe', 'ktsaitstse', 'kartse', 'yolo, pakwāre', 'āmpau', 'sal, kraketstse', '', '', 'mātre, akwatse', 'mālle', 'ṣmare', 'karītstse', 'asāre', '', 'akartte, ysape, etsuwai', 'lau, lauke', 'saiwai', 'śwālyai', '-ne', '-ne', 'śle', 'ṣp', 'krui, ente', 'kuce, mäkte', 'ñem'] + swadesh_pt_old = ['eu', 'tu', 'ele', 'nos', 'vos', 'eles', 'esto, aquesto', 'aquelo', 'aqui', 'ali', 'quen', 'que', 'u', 'quando', 'como', 'non', 'todo', 'muito', 'algũus', 'pouco', 'outro', 'un, ũu', 'dous', 'tres', 'quatro', 'cinco', 'grande, gran', 'longo', 'ancho', 'grosso', 'pesado', 'pequeno', 'curto', 'estreito', 'magro', 'moller, dona', 'ome', 'ome, pessõa', 'infante, meninno, creatura', 'moller', 'marido', 'madre, mãi', 'padre, pai', 'besta, bestia, bescha', 'peixe', 'ave', 'can', 'peollo', 'coobra', 'vermen', 'arvor', 'furesta, mata, monte', 'baston, pao', 'fruita, fruito', 'semente', 'folla', 'raiz', 'cortiça', 'fror, flor', 'erva', 'corda', 'pele', 'carne', 'sangui, sangue', 'osso', 'gordura', 'ovo', 'corno', 'rabo', 'pena', 'cabelo', 'cabeça', 'orella', 'ollo', 'nariz', 'boca', 'dente', 'lingua', 'unna, unlla', 'pee, pe', 'perna', 'gẽollo', 'mão', 'aa', 'ventre', 'tripas', 'colo', 'costas', 'peito, sẽo', 'coraçon', 'figado', 'bever', 'comer', 'morder', 'mamar', 'cospir', '', 'soprar', '', 'riir', 'veer', 'ouvir, oir, ascuitar', 'saber', 'pensar', 'cheirar', 'temer', 'dormir', 'viver', 'morrer', 'matar', 'pelejar', 'caçar', 'bater', 'cortar, partir', '', 'acuitelar', 'rascar', 'cavar', 'nadar', 'voar', 'andar', 'vĩir', 'jazer, deitar', 'sentar', 'levantar', '', 'caer', 'dar', 'tẽer', 'apertar', '', 'lavar', 'terger, enxugar', 'puxar', 'empuxar', 'lançar', 'atar', 'coser', 'contar', 'contar, dizer, falar', 'cantar', 'jogar', 'boiar', 'correr', 'gelar, *gear', 'inchar', 'sol', 'lũa', 'estrela', 'agua', 'chuvia', 'rio', 'lago', 'mar', 'sal', 'pedra', 'arẽa', 'poo', 'terra', 'nuve', 'nevoeiro', 'ceo', 'vento', 'neve', 'geo', 'fumo, fumaz', 'fogo', 'cĩisa', 'queimar, arder', 'caminno, via', 'montanna, monte', 'vermello', 'verde', 'amarelo', 'branco', 'negro', 'noite', 'dia', 'ano', 'caente', 'frio', 'chẽo', 'novo', 'vello, antigo', 'bon, bõo', 'mal, mao', 'podre', 'lixoso', 'estreito', 'redondo', 'amoado', 'romo', 'chão', 'mollado', 'seco', 'reito, dereito', 'preto', 'longe', 'dereita', 'sẽestra', 'a', 'en', 'con', 'e', 'se', 'porque', 'nome'] class Swadesh(): @@ -18,6 +20,7 @@ class Swadesh(): return swadesh_la elif self.language == 'gr': return swadesh_gr + elif self.language == 'txb': + return swadesh_txb elif self.language == 'pt_old': return swadesh_pt_old -
cltk/cltk
88b88dfc964e3753f556290cadd10ef37c9390dc
diff --git a/cltk/tests/test_corpus.py b/cltk/tests/test_corpus.py index 5be48f0a..a09c4a81 100644 --- a/cltk/tests/test_corpus.py +++ b/cltk/tests/test_corpus.py @@ -743,6 +743,12 @@ class TestScriptInformation(unittest.TestCase): match = swadesh.words()[0] self.assertEqual(first_word, match) + def test_swadesh_tocharianB(self): + swadesh = Swadesh('txb') + first_word = 'ñäś' + match = swadesh.words()[0] + self.assertEqual(first_word, match) + def test_swadesh_old_portuguese(self): swadesh = Swadesh('pt_old')
Add Swadesh list for Tocharian B Data here: https://en.wiktionary.org/wiki/Appendix:Tocharian_B_Swadesh_list Follow the pattern here: https://github.com/cltk/cltk/blob/4bf42fc9a19cf711f7eb1e908850fb64c65b0582/cltk/corpus/swadesh.py#L6 Call the list `swadesh_txb`.
0.0
88b88dfc964e3753f556290cadd10ef37c9390dc
[ "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_tocharianB" ]
[ "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_phi5_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_phi5_works", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_tlg_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_tlg_works", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_check_id", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_check_number", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_cltk_normalize_compatible", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_cltk_normalize_noncompatible", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpora_import_list_greek", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpora_import_list_latin", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_but_in_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_but_yes_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_no_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_user_but_not_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_egyptian_transliterate_mdc_to_unicode_q_kopf_False", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_egyptian_transliterate_mdc_to_unicode_q_kopf_True", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_englishToPun_number", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_english_to_punjabi_number_conversion", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_expand_iota_subscript", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_expand_iota_subscript_lower", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_filter_non_greek", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithet_index", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithet_of_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithets", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epoch", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_female_authors", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geo_index", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geo_of_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geographies", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_id_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_lists", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_works_by_id", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_greek_betacode_to_unicode", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_handle_splits", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_greek_models_cltk", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_greek_software_tlgu", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_lat_text_lat_lib", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_latin_models_cltk", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_latin_text_antique_digiliblt", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_nonexistant_corpus", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_normalize", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup_rm_periods", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup_rm_periods_bytes", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_punjabi_to_english_number_conversion", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_ascii", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_latin", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_latin_opt", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_authors_by_epithet", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_authors_by_geo", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_id_by_name", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_show_corpora_bad_lang", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlg_plaintext_cleanup", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlg_plaintext_cleanup_rm_periods", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert_corpus_fail", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert_fail", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_init", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tonos_oxia_converter", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tonos_oxia_converter_reverse", "cltk/tests/test_corpus.py::TestUnicode::test_py23char", "cltk/tests/test_corpus.py::TestTransliteration::test_Indicization", "cltk/tests/test_corpus.py::TestTransliteration::test_Romanization", "cltk/tests/test_corpus.py::TestTransliteration::test_ScriptConversion", "cltk/tests/test_corpus.py::TestTransliteration::test_SinhalaDevanagariTransliterator", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsApproximant", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsAspirated", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsAum", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsConsonant", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsDental", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsFricative", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsHalanta", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsLabial", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNasal", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNukta", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNumber", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsPalatal", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsRetroflex", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsUnAspirated", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsUnvoiced", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVelar", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVoiced", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVowel", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVowelSign", "cltk/tests/test_corpus.py::TestScriptInformation::test_in_coordinated_range", "cltk/tests/test_corpus.py::TestScriptInformation::test_is_indiclang_char", "cltk/tests/test_corpus.py::TestScriptInformation::test_offset_to_char", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_greek", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_latin", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_old_portuguese" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-02-04 22:21:03+00:00
mit
1,614
cltk__cltk-666
diff --git a/cltk/corpus/swadesh.py b/cltk/corpus/swadesh.py index 33203282..bbeea2b8 100644 --- a/cltk/corpus/swadesh.py +++ b/cltk/corpus/swadesh.py @@ -7,6 +7,8 @@ swadesh_la = ['ego', 'tū', 'is, ea, id', 'nōs', 'vōs', 'eī, iī, eae, ea', ' swadesh_gr = ['ἐγώ', 'σύ', 'αὐτός, οὗ, ὅς, ὁ, οὗτος', 'ἡμεῖς', 'ὑμεῖς', 'αὐτοί', 'ὅδε', 'ἐκεῖνος', 'ἔνθα, ἐνθάδε, ἐνταῦθα', 'ἐκεῖ', 'τίς', 'τί', 'ποῦ, πόθι', 'πότε, πῆμος', 'πῶς', 'οὐ, μή', 'πᾶς, ἅπᾱς', 'πολύς', 'τις', 'ὀλίγος, βαιός, παῦρος', 'ἄλλος, ἕτερος', 'εἷς', 'δύο', 'τρεῖς', 'τέσσαρες', 'πέντε', 'μέγας', 'μακρός', 'εὐρύς', 'πυκνός', 'βαρύς', 'μῑκρός', 'βραχύς', 'στενός', 'μανός', 'γυνή', 'ἀνήρ', 'ἄνθρωπος', 'τέκνον, παῖς, παιδίον', 'γυνή', 'ἀνήρ', 'μήτηρ', 'πατήρ', 'ζῷον', 'ἰχθύς', 'ὄρνις, πετεινόν', 'κύων', 'φθείρ', 'ὄφις', 'ἑρπετόν, σκώληξ, ἕλμινς', 'δένδρον', 'ὕλη', 'βακτηρία, ῥάβδος', 'καρπός', 'σπέρμα', 'φύλλον', 'ῥίζα', 'φλοιός', 'ἄνθος', 'χλόη', 'δεσμός, σχοινίον', 'δέρμα', 'κρέας', 'αἷμα', 'ὀστοῦν', 'δημός', 'ᾠόν', 'κέρας', 'οὐρά, κέρκος', 'πτερόν', 'θρίξ, κόμη', 'κεφαλή', 'οὖς', 'ὀφθαλμός', 'ῥίς', 'στόμα', 'ὀδούς', 'γλῶσσα', 'ὄνυξ', 'πούς', 'κῶλον, σκέλος', 'γόνυ', 'χείρ', 'πτέρυξ', 'γαστήρ, κοιλία', 'ἔντερα, σπλάγχνα', 'αὐχήν, τράχηλος', 'νῶτον', 'μαστός, στῆθος', 'καρδία', 'ἧπαρ', 'πίνω', 'ἐσθίω, ἔφαγον', 'δάκνω', 'σπάω', 'πτύω', 'ἐμέω', 'φυσάω', 'πνέω', 'γελάω', 'βλέπω, ὁράω, εἶδον', 'ἀκούω, ἀΐω', 'οἶδα, γιγνώσκω', 'νομίζω, δοκέω, νοέω, οἴομαι', 'ὀσφραίνομαι', 'φοβέομαι', 'καθεύδω, εὕδω, εὐνάζομαι, κοιμάομαι, ἰαύω', 'ζάω, βιόω, οἰκέω', 'ἀποθνῄσκω, θνῄσκω, τελευτάω, ὄλομαι', 'ἀποκτείνω, ἔπεφνον', 'μάχομαι', 'θηρεύω, θηράω, ἰχνεύω, κυνηγετέω, κυνηγέω, σεύω', 'τύπτω', 'τέμνω', 'σχίζω', 'κεντέω', 'κνάω', 'ὀρύσσω, σκᾰ́πτω', 'νέω, κολυμβάω', 'πέτομαι', 'περιπατέω, πατέω, στείχω, βαίνω, βαδίζω, πεζεύω, πορεύω', 'ἱκνέομαι, ἵκω, ἔρχομαι, εἶμι', 'κεῖμαι', 'καθίζω', 'ἵστημι', 'τρέπω', 'πίπτω', 'παρέχω, δίδωμι', 'ἔχω', 'πιέζω', 'τρίβω', 'λούω, πλύνω, νίπτω', 'ἀπομάσσω', 'ἕλκω', 'ὠθέω', 'ῥίπτω, βάλλω', 'δέω', 'ῥάπτω', 'ἀριθμέω', 'φημί, λέγω, ἐνέπω', 'ἀείδω', 'παίζω', 'νέω', 'ῥέω', 'πήγνυμαι', 'αὐξάνω', 'ἥλιος', 'σελήνη', 'ἀστήρ', 'ὕδωρ', 'ὑετός, βροχή', 'ποταμός', 'λίμνη', 'θάλασσα, πέλαγος, πόντος', 'ἅλς', 'λίθος', 'ἄμμος', 'κόνις', 'γῆ, χθών', 'νέφος', 'ὀμίχλη', 'οὐρανός', 'ἄνεμος', 'χιών', 'κρύσταλλος', 'καπνός', 'πῦρ', 'τέφρα', 'καίω', 'ὁδός', 'ἄκρα, ὄρος, βουνός', 'ἐρυθρός, πυρρός', 'χλωρός', 'ξανθός', 'λευκός', 'μέλας', 'νύξ', 'ἡμέρα, ἦμαρ', 'ἔτος', 'θερμός', 'ψυχρός', 'μεστός, πλήρης', 'νέος', 'παλαιός', 'ἀγαθός', 'κακός', 'σαπρός', 'θολερός', 'εὐθύς, ὀρθός', 'κυκλοτερής', 'τομός, ὀξύς', 'ἀμβλύς, βαρύς', 'λεῖος', 'ὑγρός', 'ξηρός', 'δίκαιος', 'ἐγγύς', 'μακράν', 'δεξιός', 'ἀριστερός, εὐώνυμος', 'ἐν', 'ἐν', 'μετά, σύν', 'καί, τε', 'εἰ', 'ὅτι', 'ὄνομα'] +swadesh_sa = ['अहम्' , 'त्वम्', 'स', 'वयम्, नस्', 'यूयम्, वस्', 'ते', 'इदम्', 'तत्', 'अत्र', 'तत्र', 'क', 'किम्', 'कुत्र', 'कदा', 'कथम्', 'न', 'सर्व', 'बहु', 'किञ्चिद्', 'अल्प', 'अन्य', 'एक', 'द्वि', 'त्रि', 'चतुर्', 'पञ्चन्', 'महत्', 'दीर्घ', 'उरु', 'घन', 'गुरु', 'अल्प', 'ह्रस्व', 'अंहु', 'तनु', 'स्त्री', 'पुरुष, नर', 'मनुष्य, मानव', 'बाल, शिशु', 'पत्नी, भार्या', 'पति', 'मातृ', 'पितृ', 'पशु', 'मत्स्य', 'वि, पक्षिन्', 'श्वन्', 'यूका', 'सर्प', 'कृमि', 'वृक्ष, तरु', 'वन', 'दण्ड', 'फल', 'बीज', 'पत्त्र', 'मूल', 'त्वच्', 'पुष्प', 'तृण', 'रज्जु', 'चर्मन्, त्वच्', 'मांस', 'रक्त, असृज्', 'अस्थि', 'पीवस्, मेदस्', 'अण्ड', 'शृङ्ग', 'पुच्छ', 'पर्ण', 'केश', 'शिरस्', 'कर्ण', 'अक्षि', 'नासा', 'वक्त्र, मुख', 'दन्त', 'जिह्वा', 'नख', 'पद', 'जङ्घ', 'जानु', 'हस्त, पाणि', 'पक्ष', 'उदर', 'अन्त्र, आन्त्र, गुद', 'गल, ग्रीवा', 'पृष्ठ', 'स्तन', 'हृदय', 'यकृत्', 'पिबति', 'खादति, अत्ति', 'दशति', 'धयति', 'ष्ठीवति', 'वमति', 'वाति', 'अनिति', 'स्मयते, हसति', 'पश्यति, √दृश्', 'शृणोति', 'जानाति', 'मन्यते, चिन्तयति', 'जिघ्रति', 'बिभेति, भयते', 'स्वपिति', 'जीवति', 'म्रियते', 'हन्ति', 'युध्यते', 'वेति', 'हन्ति, ताडयति', 'कृन्तति', 'भिनत्ति', 'विधति', 'लिखति', 'खनति', 'प्लवते', 'पतति', 'एति, गच्छति, चरति', 'आगच्छति', 'शेते', 'सीदति', 'तिष्ठति', 'वर्तते', 'पद्यते', 'ददाति', 'धरति', 'मृद्नाति', 'घर्षति', 'क्षालयति', 'मार्ष्टि', 'कर्षति', 'नुदति', 'क्षिपति', 'बध्नाति, बन्धति', 'सीव्यति', 'गणयति, कलते', 'वक्ति', 'गायति', 'दीव्यति', 'प्लवते', 'सरति, क्षरति', 'शीयते', 'श्वयति', 'सूर्य, रवि, सूर, भास्कर', 'मास, चन्द्रमस्, चन्द्र', 'नक्षत्र, स्तृ, तारा', 'जल, अप्, पानीय, वारि, उदन्, तोज', 'वर्ष', 'नदी', 'सरस्', 'समुद्र', 'लवण', 'अश्मन्', 'पांसु, शिकता', 'रेणु', 'क्षम्, पृथ्वी', 'नभस्, मेघ', 'मिह्', 'आकाश', 'वायु, वात', 'हिम, तुषार, तुहिन', 'हिम', 'धूम', 'अग्नि', 'आस', 'दहति', 'पथ, अध्वन्, मार्ग', 'गिरि, पर्वत', 'रक्त, रोहित', 'हरित्, हरित, पालाश, पलाश', 'पीत, पीतल', 'श्वेत', 'कृष्ण', 'रात्रि, नक्ति, क्षप्, रजनी', 'दिन, अहर्, दिवस', 'वर्ष, संवत्सर', 'तप्त', 'शीत', 'पूर्ण', 'नव, नूतन', 'जीर्ण, वृद्ध, पुरातन', 'वसु, भद्र', 'पाप, दुष्ट', 'पूति', 'मलिन, समल', 'ऋजु, साधु', 'वृत्त, वर्तुल', 'तीक्ष्ण', 'कुण्ठ', 'श्लक्ष्ण, स्निग्ध', 'आर्द्र, क्लिन्न', 'शुष्क', 'शुद्ध, सत्य', 'नेद, प्रति', 'दूर', 'दक्षिण', 'सव्य', 'काश्यां', 'अंतरे, मध्ये', 'सह', 'च', 'यदि', 'हि', 'नामन्'] + swadesh_txb = ['ñäś', 'tuwe', 'su', 'wes', 'yes', 'cey', 'se', 'su, samp', 'tane', 'tane, omp', 'kᵤse', 'kᵤse', 'ente', 'ente', 'mäkte', 'mā', 'poñc', 'māka', 'ṣemi', 'totka', 'allek', 'ṣe', 'wi', 'trey', 'śtwer', 'piś', 'orotstse', 'pärkare', 'aurtstse', '', 'kramartse', 'lykaśke, totka', '', '', '', 'klyiye, śana', 'eṅkwe', 'śaumo', 'śamaśke', 'śana', 'petso', 'mācer', 'pācer', 'luwo', 'laks', 'salamo luwo', 'ku', 'pärśeriñ', 'arṣāklo, auk', 'yel', 'stām', 'wartto, karāś', 'śakātai', 'oko', 'sārm, śäktālye', 'pilta', 'witsako', 'enmetre', 'pyāpyo', 'atiyai', '', 'ewe, yetse', 'misa', 'yasar', 'āy, āsta pl', 'ṣalype', '', 'krorīyai', 'pako', 'paruwa', 'matsi', 'āśce', 'klautso', 'ek', 'meli', 'koyṃ', 'keme', 'kantwo', '', 'paiyye', 'ckāckai', 'keni', 'ṣar', '', 'kātso', 'kātso', 'kor', 'sark', 'päścane', 'arañce', 'wästarye', 'yokäṃ', 'śuwaṃ', '', '', 'pitke', 'aṅkaiṃ', 'pinaṣṣnäṃ', 'anāṣṣäṃ, satāṣṣäṃ', 'ker-', 'lkāṣṣäṃ', 'klyauṣäṃ', 'aiśtär, kärsanaṃ', 'pälskanaṃ', 'warṣṣäṃ', 'prāskaṃ', 'kläntsaṃ', 'śaiṃ', 'sruketär', 'kauṣäṃ', 'witāre', 'śerītsi', 'karnäṣṣäṃ', 'karsnaṃ, latkanaṃ', 'kautanaṃ', 'tsopäṃ', '', 'rapanaṃ', 'nāṣṣäṃ', 'pluṣäṃ', 'yaṃ', 'känmaṣṣäṃ', 'lyaśäṃ', 'ṣamäṃ, āṣṣäṃ', 'kaltär', 'kluttaṅktär, sporttotär', 'kloyotär', 'aiṣṣäṃ', '', 'klupnātär, nuskaṣṣäṃ', 'lyuwetär, kantanatär', 'laikanatär', 'lyyāstär', 'slaṅktär', 'nätkanaṃ', 'karṣṣäṃ, saläṣṣäṃ', 'śanmästär, kärkaṣṣäṃ', '', 'ṣäṃṣtär', 'weṣṣäṃ', 'piyaṃ', 'kāñmäṃ', 'pluṣäṃ', 'reṣṣäṃ', '', 'staukkanatär', 'kauṃ', 'meñe', 'ścirye', 'war', 'swese', 'cake', 'lyam', 'samudtär', 'salyiye', 'kärweñe', 'warañc', 'tweye, taur', 'keṃ', 'tarkär', '', 'iprer', 'yente', 'śiñcatstse', '', '', 'puwar', 'taur, tweye', 'tsakṣtär,pälketär', 'ytārye', 'ṣale', 'ratre', 'motartstse', 'tute', 'ārkwi', 'erkent-', 'yṣiye', 'kauṃ', 'pikul', 'emalle', 'krośce', 'ite', 'ñuwe', 'ktsaitstse', 'kartse', 'yolo, pakwāre', 'āmpau', 'sal, kraketstse', '', '', 'mātre, akwatse', 'mālle', 'ṣmare', 'karītstse', 'asāre', '', 'akartte, ysape, etsuwai', 'lau, lauke', 'saiwai', 'śwālyai', '-ne', '-ne', 'śle', 'ṣp', 'krui, ente', 'kuce, mäkte', 'ñem'] swadesh_pt_old = ['eu', 'tu', 'ele', 'nos', 'vos', 'eles', 'esto, aquesto', 'aquelo', 'aqui', 'ali', 'quen', 'que', 'u', 'quando', 'como', 'non', 'todo', 'muito', 'algũus', 'pouco', 'outro', 'un, ũu', 'dous', 'tres', 'quatro', 'cinco', 'grande, gran', 'longo', 'ancho', 'grosso', 'pesado', 'pequeno', 'curto', 'estreito', 'magro', 'moller, dona', 'ome', 'ome, pessõa', 'infante, meninno, creatura', 'moller', 'marido', 'madre, mãi', 'padre, pai', 'besta, bestia, bescha', 'peixe', 'ave', 'can', 'peollo', 'coobra', 'vermen', 'arvor', 'furesta, mata, monte', 'baston, pao', 'fruita, fruito', 'semente', 'folla', 'raiz', 'cortiça', 'fror, flor', 'erva', 'corda', 'pele', 'carne', 'sangui, sangue', 'osso', 'gordura', 'ovo', 'corno', 'rabo', 'pena', 'cabelo', 'cabeça', 'orella', 'ollo', 'nariz', 'boca', 'dente', 'lingua', 'unna, unlla', 'pee, pe', 'perna', 'gẽollo', 'mão', 'aa', 'ventre', 'tripas', 'colo', 'costas', 'peito, sẽo', 'coraçon', 'figado', 'bever', 'comer', 'morder', 'mamar', 'cospir', '', 'soprar', '', 'riir', 'veer', 'ouvir, oir, ascuitar', 'saber', 'pensar', 'cheirar', 'temer', 'dormir', 'viver', 'morrer', 'matar', 'pelejar', 'caçar', 'bater', 'cortar, partir', '', 'acuitelar', 'rascar', 'cavar', 'nadar', 'voar', 'andar', 'vĩir', 'jazer, deitar', 'sentar', 'levantar', '', 'caer', 'dar', 'tẽer', 'apertar', '', 'lavar', 'terger, enxugar', 'puxar', 'empuxar', 'lançar', 'atar', 'coser', 'contar', 'contar, dizer, falar', 'cantar', 'jogar', 'boiar', 'correr', 'gelar, *gear', 'inchar', 'sol', 'lũa', 'estrela', 'agua', 'chuvia', 'rio', 'lago', 'mar', 'sal', 'pedra', 'arẽa', 'poo', 'terra', 'nuve', 'nevoeiro', 'ceo', 'vento', 'neve', 'geo', 'fumo, fumaz', 'fogo', 'cĩisa', 'queimar, arder', 'caminno, via', 'montanna, monte', 'vermello', 'verde', 'amarelo', 'branco', 'negro', 'noite', 'dia', 'ano', 'caente', 'frio', 'chẽo', 'novo', 'vello, antigo', 'bon, bõo', 'mal, mao', 'podre', 'lixoso', 'estreito', 'redondo', 'amoado', 'romo', 'chão', 'mollado', 'seco', 'reito, dereito', 'preto', 'longe', 'dereita', 'sẽestra', 'a', 'en', 'con', 'e', 'se', 'porque', 'nome'] @@ -25,6 +27,8 @@ class Swadesh(): return swadesh_la elif self.language == 'gr': return swadesh_gr + elif self.language == 'sa': + return swadesh_sa elif self.language == 'txb': return swadesh_txb elif self.language == 'pt_old': diff --git a/docs/sanskrit.rst b/docs/sanskrit.rst index 680751aa..97473332 100644 --- a/docs/sanskrit.rst +++ b/docs/sanskrit.rst @@ -124,6 +124,20 @@ Other similar functions are here, ['APPROXIMANT_LIST', 'ASPIRATED_LIST', 'AUM_OFFSET', 'COORDINATED_RANGE_END_INCLUSIVE', 'COORDINATED_RANGE_START_INCLUSIVE', 'DANDA', 'DENTAL_RANGE', 'DOUBLE_DANDA', 'FRICATIVE_LIST', 'HALANTA_OFFSET', 'LABIAL_RANGE', 'LC_TA', 'NASAL_LIST', 'NUKTA_OFFSET', 'NUMERIC_OFFSET_END', 'NUMERIC_OFFSET_START', 'PALATAL_RANGE', 'RETROFLEX_RANGE', 'RUPEE_SIGN', 'SCRIPT_RANGES', 'UNASPIRATED_LIST', 'UNVOICED_LIST', 'URDU_RANGES', 'VELAR_RANGE', 'VOICED_LIST', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__spec__', 'get_offset', 'in_coordinated_range', 'is_approximant', 'is_aspirated', 'is_aum', 'is_consonant', 'is_dental', 'is_fricative', 'is_halanta', 'is_indiclang_char', 'is_labial', 'is_nasal', 'is_nukta', 'is_number', 'is_palatal', 'is_retroflex', 'is_unaspirated', 'is_unvoiced', 'is_velar', 'is_voiced', 'is_vowel', 'is_vowel_sign', 'offset_to_char'] +Swadesh +======= +The corpus module has a class for generating a Swadesh list for Sanskrit. + +.. code-block:: python + + In [1]: from cltk.corpus.swadesh import Swadesh + + In [2]: swadesh = Swadesh('sa') + + In [3]: swadesh.words()[:10] + Out[3]: ['अहम्' , 'त्वम्', 'स', 'वयम्, नस्', 'यूयम्, वस्', 'ते', 'इदम्', 'तत्', 'अत्र', 'तत्र'] + + Syllabifier ===========
cltk/cltk
bc104c45d77a187ed8b58d4fb7d820fada9c8663
diff --git a/cltk/tests/test_corpus.py b/cltk/tests/test_corpus.py index a09c4a81..976084f9 100644 --- a/cltk/tests/test_corpus.py +++ b/cltk/tests/test_corpus.py @@ -756,5 +756,11 @@ class TestScriptInformation(unittest.TestCase): match = swadesh.words()[0] self.assertEqual(first_word, match) + def test_swadesh_sanskrit(self): + swadesh = Swadesh('sa') + first_word = 'अहम्' + match = swadesh.words()[0] + self.assertEqual(first_word, match) + if __name__ == '__main__': unittest.main()
Add Swadesh list for Sanskrit Data here: https://en.wiktionary.org/wiki/Appendix:Sanskrit_Swadesh_list Please be sure to cite the author of this in a `# comment` Follow the pattern here: https://github.com/cltk/cltk/blob/4bf42fc9a19cf711f7eb1e908850fb64c65b0582/cltk/corpus/swadesh.py#L6 Call the list `swadesh_sa`.
0.0
bc104c45d77a187ed8b58d4fb7d820fada9c8663
[ "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_sanskrit" ]
[ "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_phi5_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_phi5_works", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_tlg_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_assemble_tlg_works", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_check_id", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_check_number", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_cltk_normalize_compatible", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_cltk_normalize_noncompatible", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpora_import_list_greek", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpora_import_list_latin", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_but_in_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_but_yes_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_no_user_no_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_corpus_importer_variables_user_but_not_core", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_egyptian_transliterate_mdc_to_unicode_q_kopf_False", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_egyptian_transliterate_mdc_to_unicode_q_kopf_True", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_englishToPun_number", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_english_to_punjabi_number_conversion", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_expand_iota_subscript", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_expand_iota_subscript_lower", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_filter_non_greek", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithet_index", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithet_of_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epithets", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_epoch", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_female_authors", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geo_index", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geo_of_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_geographies", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_id_author", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_lists", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_get_works_by_id", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_greek_betacode_to_unicode", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_handle_splits", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_greek_models_cltk", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_greek_software_tlgu", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_lat_text_lat_lib", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_latin_models_cltk", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_latin_text_antique_digiliblt", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_import_nonexistant_corpus", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_normalize", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup_rm_periods", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_phi5_plaintext_cleanup_rm_periods_bytes", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_punjabi_to_english_number_conversion", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_ascii", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_latin", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_remove_non_latin_opt", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_authors_by_epithet", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_authors_by_geo", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_select_id_by_name", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_show_corpora_bad_lang", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlg_plaintext_cleanup", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlg_plaintext_cleanup_rm_periods", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert_corpus_fail", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_convert_fail", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tlgu_init", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tonos_oxia_converter", "cltk/tests/test_corpus.py::TestSequenceFunctions::test_tonos_oxia_converter_reverse", "cltk/tests/test_corpus.py::TestUnicode::test_py23char", "cltk/tests/test_corpus.py::TestTransliteration::test_Indicization", "cltk/tests/test_corpus.py::TestTransliteration::test_Romanization", "cltk/tests/test_corpus.py::TestTransliteration::test_ScriptConversion", "cltk/tests/test_corpus.py::TestTransliteration::test_SinhalaDevanagariTransliterator", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsApproximant", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsAspirated", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsAum", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsConsonant", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsDental", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsFricative", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsHalanta", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsLabial", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNasal", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNukta", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsNumber", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsPalatal", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsRetroflex", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsUnAspirated", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsUnvoiced", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVelar", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVoiced", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVowel", "cltk/tests/test_corpus.py::TestScriptInformation::test_IsVowelSign", "cltk/tests/test_corpus.py::TestScriptInformation::test_in_coordinated_range", "cltk/tests/test_corpus.py::TestScriptInformation::test_is_indiclang_char", "cltk/tests/test_corpus.py::TestScriptInformation::test_offset_to_char", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_greek", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_latin", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_old_portuguese", "cltk/tests/test_corpus.py::TestScriptInformation::test_swadesh_tocharianB" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-02-09 00:43:21+00:00
mit
1,615
coady__multimethod-23
diff --git a/README.md b/README.md index 14199c2..0bb2db6 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Dispatch resolution details: * If the `issubclass` relation is ambiguous, [mro](https://docs.python.org/3/library/stdtypes.html?highlight=mro#class.mro) position is used as a tie-breaker. * If there are still ambiguous methods - or none - a custom `TypeError` is raised. -* Additional `*args` or `**kwargs` may be used when calling, but won't affect the dispatching. +* Default and keyword arguments may be used, but won't affect the dispatching. * A skipped annotation is equivalent to `: object`, which implicitly supports methods by leaving `self` blank. * If no types are specified, it will inherently match all arguments. @@ -151,6 +151,7 @@ dev * Postponed evaluation of nested annotations * Variable-length tuples of homogeneous type +* Ignore default and keyword arguments 1.4 diff --git a/multimethod/__init__.py b/multimethod/__init__.py index 1a11644..80d330b 100644 --- a/multimethod/__init__.py +++ b/multimethod/__init__.py @@ -19,13 +19,17 @@ def groupby(func: Callable, values: Iterable) -> dict: def get_types(func: Callable) -> tuple: - """Return evaluated type hints in order.""" + """Return evaluated type hints for positional required parameters in order.""" if not hasattr(func, '__annotations__'): return () - annotations = dict(typing.get_type_hints(func)) - annotations.pop('return', None) - params = inspect.signature(func).parameters - return tuple(annotations.pop(name, object) for name in params if annotations) + type_hints = typing.get_type_hints(func) + positionals = {inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD} + annotations = [ + type_hints.get(param.name, object) + for param in inspect.signature(func).parameters.values() + if param.default is param.empty and param.kind in positionals + ] # missing annotations are padded with `object`, but trailing objects are unnecessary + return tuple(itertools.dropwhile(lambda cls: cls is object, reversed(annotations)))[::-1] class DispatchError(TypeError):
coady/multimethod
221dc1b4e11523789ef907c5426b68a46d0fe68e
diff --git a/tests/test_dispatch.py b/tests/test_dispatch.py index 8f71386..a628790 100644 --- a/tests/test_dispatch.py +++ b/tests/test_dispatch.py @@ -1,6 +1,7 @@ +import sys from collections.abc import Iterable import pytest -from multimethod import multidispatch, signature, DispatchError +from multimethod import get_types, multidispatch, signature, DispatchError def test_signature(): @@ -74,3 +75,12 @@ def test_cls(): cls.method('', '') cls.method[object, Iterable] = cls.method[Iterable, object] assert cls.method('', '') == 'left' + + +def test_arguments(): + def func(a, b: int, c: int, d, e: int = 0, *, f: int): + pass + + if sys.version_info >= (3, 8): + exec("def func(a, b: int, /, c: int, d, e: int = 0, *, f: int): pass") + assert get_types(func) == (object, int, int)
Overloading with optional parameters Hi, The following example produces an error: ` class A: @multimethod def m(self, c: int, ii: Optional[int] = None): print('1', c, ii) @multimethod def m(self, ff: float): print('2', ff) obj = A() obj.m(20) ` when calling `obj.m(20)`: ` File "/usr/local/lib/python3.8/dist-packages/multimethod/__init__.py", line 184, in __call__ return self[tuple(map(self.get_type, args))](*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/multimethod/__init__.py", line 180, in __missing__ raise DispatchError(msg, types, keys) multimethod.DispatchError: ('a: 0 methods found', (<class '__main__.A'>, <class 'int'>), []) Process finished with exit code 1 ` Is there a way around it?
0.0
221dc1b4e11523789ef907c5426b68a46d0fe68e
[ "tests/test_dispatch.py::test_arguments" ]
[ "tests/test_dispatch.py::test_signature", "tests/test_dispatch.py::test_roshambo", "tests/test_dispatch.py::test_cls" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-12-11 02:26:34+00:00
apache-2.0
1,616
coady__multimethod-26
diff --git a/README.md b/README.md index 4da3048..461c589 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ dev * Ignore default and keyword arguments * Resolved ambiguous `Union` types * Fixed an issue with name collision when defining a multimethod +* Resolved dispatch errors when annotating parameters with meta-types such as `type` 1.4 diff --git a/multimethod/__init__.py b/multimethod/__init__.py index 22ffff3..63cb6a1 100644 --- a/multimethod/__init__.py +++ b/multimethod/__init__.py @@ -99,7 +99,7 @@ def distance(cls, subclass: type) -> int: """Return estimated distance between classes for tie-breaking.""" if getattr(cls, '__origin__', None) is typing.Union: return min(distance(arg, subclass) for arg in cls.__args__) - mro = subclass.mro() + mro = type.mro(subclass) return mro.index(cls if cls in mro else object)
coady/multimethod
4ef8516bdf9e2dfe86297bdb676104e6b534041c
diff --git a/tests/test_methods.py b/tests/test_methods.py index 8c572f8..0409431 100644 --- a/tests/test_methods.py +++ b/tests/test_methods.py @@ -1,3 +1,5 @@ +import enum + import pytest from typing import Any, AnyStr, Dict, Iterable, List, Tuple, TypeVar, Union from multimethod import ( @@ -85,6 +87,13 @@ def test_signature(): assert signature([List[int]]) - signature([list]) assert signature([list]) - signature([List[int]]) == (1,) + # with metaclasses: + assert signature([type]) - signature([type]) == (0,) + assert signature([type]) - signature([object]) == (1,) + # using EnumMeta because it is a standard, stable, metaclass + assert signature([enum.EnumMeta]) - signature([object]) == (2,) + assert signature([Union[type, enum.EnumMeta]]) - signature([object]) == (1,) + def test_get_type(): method = multimethod(lambda: None) @@ -229,6 +238,30 @@ def test_ellipsis(): func(((0, 1.0),)) +def test_meta_types(): + @multimethod + def f(x): + return "object" + + @f.register + def f(x: type): + return "type" + + @f.register + def f(x: enum.EnumMeta): + return "enum" + + @f.register + def f(x: enum.Enum): + return "member" + + dummy_enum = enum.Enum("DummyEnum", names="SPAM EGGS HAM") + assert f(123) == "object" + assert f(int) == "type" + assert f(dummy_enum) == "enum" + assert f(dummy_enum.EGGS) == "member" + + def test_name_shadowing(): # an object with the same name appearing previously in the same namespace temp = 123 # noqa
TypeError when one of the type hints is type or another metaclass Using `type` (or any other subclass of `type`, e.g. a custom metaclass) as the type hint for one of the parameters of a function of a multimethod makes the dispatch process raise a `TypeError` when calling `type.mro()` (which expects the type object as an argument). ## Example ```python @multimethod def f(x: type): print("success") ``` ### Expected ```python >>> f(int) success ``` ### Actual ```python >>> f(int) TypeError: unbound method type.mro() needs an argument ``` Traceback: <details> ``` Traceback (most recent call last): File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-34-0374cd2152b2>", line 1, in <module> f(int) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 184, in __call__ return self[tuple(map(self.get_type, args))](*args, **kwargs) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 184, in __call__ return self[tuple(map(self.get_type, args))](*args, **kwargs) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 174, in __missing__ groups = groupby(signature(types).__sub__, self.parents(types)) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 17, in groupby groups[func(value)].append(value) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 104, in __sub__ return tuple(mro.index(cls if cls in mro else object) for mro, cls in zip(mros, other)) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 104, in <genexpr> return tuple(mro.index(cls if cls in mro else object) for mro, cls in zip(mros, other)) File "C:\Users\Paolo\Code\JB-PycharmProjects\LoveLetter\venv\lib\site-packages\multimethod\__init__.py", line 103, in <genexpr> mros = (subclass.mro() for subclass in self) TypeError: unbound method type.mro() needs an argument ``` </details> ## Cause Methods of metaclasses like `type`, e.g. `.mro()` expect an explicit first argument which is the actual type object being used.
0.0
4ef8516bdf9e2dfe86297bdb676104e6b534041c
[ "tests/test_methods.py::test_signature" ]
[ "tests/test_methods.py::test_join", "tests/test_methods.py::test_subtype", "tests/test_methods.py::test_get_type", "tests/test_methods.py::test_annotations", "tests/test_methods.py::test_register", "tests/test_methods.py::test_overloads", "tests/test_methods.py::test_meta", "tests/test_methods.py::test_ellipsis", "tests/test_methods.py::test_meta_types", "tests/test_methods.py::test_name_shadowing" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-12-31 15:31:22+00:00
apache-2.0
1,617
coady__multimethod-9
diff --git a/.travis.yml b/.travis.yml index da158e0..87b9f79 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: python python: - - 3.5 - 3.6 - 3.7 - 3.8 diff --git a/README.md b/README.md index 753a640..e2e0e4e 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,9 @@ class Foo: ``` # Changes +dev +* Python >=3.6 required + 1.3 * Python 3 required * Support for subscripted ABCs diff --git a/docs/examples.ipynb b/docs/examples.ipynb index a6f77ed..1128cc9 100644 --- a/docs/examples.ipynb +++ b/docs/examples.ipynb @@ -168,6 +168,53 @@ "source": [ "wait(0.5, asyncio.sleep, 0.01)" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "outputs": [], + "source": [ + "## typing subscripts\n", + "Provisional support for type hints with subscripts." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "outputs": [], + "source": [ + "import bisect\n", + "import random\n", + "from typing import Dict\n", + "\n", + "@multimethod\n", + "def samples(weights: Dict):\n", + " \"\"\"Generate weighted random samples using bisection.\"\"\"\n", + " keys = list(weights)\n", + " totals = list(itertools.accumulate(weights.values()))\n", + " values = [total / totals[-1] for total in totals]\n", + " while True:\n", + " yield keys[bisect.bisect_right(values, random.random())]\n", + "\n", + "@multimethod\n", + "def samples(weights: Dict[object, int]):\n", + " \"\"\"Generate weighted random samples more efficiently.\"\"\"\n", + " keys = list(itertools.chain.from_iterable([key] * weights[key] for key in weights))\n", + " while True:\n", + " yield random.choice(keys)\n", + "\n", + "weights = {'a': 1, 'b': 2, 'c': 3}\n", + "next(samples(weights))" + ] + }, + { + "cell_type": "code", + "metadata": {}, + "outputs": [], + "source": [ + "weights = {'a': 1.0, 'b': 2.0, 'c': 3.0}\n", + "next(samples(weights))" + ] } ], "metadata": { @@ -187,7 +234,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.5" + "version": "3.7.6-final" } }, "nbformat": 4, diff --git a/multimethod.py b/multimethod.py index a93d092..711a988 100644 --- a/multimethod.py +++ b/multimethod.py @@ -163,7 +163,7 @@ class multimethod(dict): funcs = {self[key] for key in keys} if len(funcs) == 1: return self.setdefault(types, *funcs) - msg = "{}: {} methods found".format(self.__name__, len(keys)) # type: ignore + msg = f"{self.__name__}: {len(keys)} methods found" # type: ignore raise DispatchError(msg, types, keys) def __call__(self, *args, **kwargs): @@ -179,6 +179,31 @@ class multimethod(dict): while self.pending: func = self.pending.pop() self[get_types(func)] = func + + @property + def __doc__(self): + docs = [] + if any([f.__doc__ is not None for f in set(self.values())]): + docs.append('Signatures with a docstring:') + + other = [] + for func in set(self.values()): + if func.__doc__: + s = f'{func.__name__}{inspect.signature(func)}' + s += '\n' + '-' * len(s) + s += '\n'.join([line.strip() for line in func.__doc__.split('\n')]) + docs.append(s) + else: + other.append(f'{func.__name__}{inspect.signature(func)}') + + if other: + docs.append('Signatures without a docstring:\n ' + '\n '.join(other)) + + return '\n\n'.join(docs) + + @__doc__.setter + def __doc__(self, value): + pass class multidispatch(multimethod): diff --git a/setup.py b/setup.py index 06330be..60247d9 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ setup( license='Apache Software License', py_modules=['multimethod'], extras_require={'docs': ['m2r', 'nbsphinx', 'jupyter']}, - python_requires='>=3.5', + python_requires='>=3.6', tests_require=['pytest-cov'], keywords='multiple dispatch multidispatch generic functions methods overload', classifiers=[ @@ -23,7 +23,6 @@ setup( 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8',
coady/multimethod
a3e4c49a6502659e3d31a7b944c77814523c3903
diff --git a/tests/test_docstring.py b/tests/test_docstring.py new file mode 100644 index 0000000..a4b565a --- /dev/null +++ b/tests/test_docstring.py @@ -0,0 +1,24 @@ +from multimethod import multimethod + + +@multimethod +def foo(bar: int): + """ + Argument is an integer + """ + pass + +@multimethod +def foo(bar: str): + """ + Argument is a string + """ + pass + + +def test_docstring(): + """ + Test if multimethod collects its children's docstrings + """ + assert "Argument is an integer" in foo.__doc__ + assert "Argument is a string" in foo.__doc__
Collect docstring from registered functions Hi! I just found this library and really like it so far, but I miss having the docstring available in the tooltip when calling a multimethod in a Jupyter Notebook.
0.0
a3e4c49a6502659e3d31a7b944c77814523c3903
[ "tests/test_docstring.py::test_docstring" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-28 14:50:26+00:00
apache-2.0
1,618
codalab__codalab-worksheets-2049
diff --git a/codalab/lib/cli_util.py b/codalab/lib/cli_util.py index 1ea35acc..53409e04 100644 --- a/codalab/lib/cli_util.py +++ b/codalab/lib/cli_util.py @@ -62,7 +62,8 @@ def nested_dict_get(obj, *args, **kwargs): def parse_key_target(spec): """ - Parses a keyed target spec into its key and the rest of the target spec + Parses a keyed target spec into its key and the rest of the target spec. + Raise UsageError when the value of the spec is empty. :param spec: a target spec in the form of [[<key>]:][<instance>::][<worksheet_spec>//]<bundle_spec>[/<subpath>] where <bundle_spec> is required and the rest are optional. @@ -71,11 +72,19 @@ def parse_key_target(spec): - <key>: (<key> if present, empty string if ':' in spec but no <key>, None otherwise) - - <value> (where value is everyhing after a <key>: (or everything if no key specified) + - <value> (where value is everything after a <key>: (or everything if no key specified) """ - match = re.match(TARGET_KEY_REGEX, spec) - return match.groups() + key, value = match.groups() + # This check covers three usage errors: + # 1. both key and value are empty, e.g. "cl run : 'echo a'" + # 2. key is not empty, value is empty, e.g. "cl run a.txt: 'echo a'" + if value == '': + raise UsageError( + 'target_spec (%s) in wrong format. Please provide a valid target_spec in the format of %s.' + % (spec, RUN_TARGET_SPEC_FORMAT) + ) + return (key, value) def parse_target_spec(spec): @@ -132,13 +141,6 @@ def desugar_command(orig_target_spec, command): 'key %s exists with multiple values: %s and %s' % (key, key2val[key], val) ) else: - if key is None: - raise UsageError( - 'target_spec is empty. Please provide a valid target_spec in the format of {}.'.format( - RUN_TARGET_SPEC_FORMAT - ) - ) - key2val[key] = val target_spec.append(key + ':' + val) return key
codalab/codalab-worksheets
9647ccf5032218c3a80c1d80e1465573f11f6e3b
diff --git a/tests/lib/cli_util_test.py b/tests/lib/cli_util_test.py index 3d74c8f0..9ea0a6bb 100644 --- a/tests/lib/cli_util_test.py +++ b/tests/lib/cli_util_test.py @@ -59,6 +59,10 @@ class CLIUtilTest(unittest.TestCase): for spec, expected_parse in cases: self.assertEqual(cli_util.parse_key_target(spec), expected_parse) + usage_error_cases = [':', 'a:', ''] + for spec in usage_error_cases: + self.assertRaises(UsageError, lambda: cli_util.parse_key_target(spec)) + def test_parse_target_spec(self): cases = [ ( @@ -107,3 +111,6 @@ class CLIUtilTest(unittest.TestCase): ) self.assertRaises(UsageError, lambda: cli_util.desugar_command([], 'echo %a:b% %a:c%')) self.assertRaises(UsageError, lambda: cli_util.desugar_command([':b'], 'echo %b:c%')) + self.assertRaises(UsageError, lambda: cli_util.desugar_command(['b:'], 'echo %b:c%')) + self.assertRaises(UsageError, lambda: cli_util.desugar_command([':'], 'echo %b:c%')) + self.assertRaises(UsageError, lambda: cli_util.desugar_command([''], 'echo %b:c%'))
TypeError: expected string or bytes-like object ``` Error on request by matt.downey18(0xd72e93b8f2b448fc9318d136e89e555a): POST /cli/command Query params: Form params: JSON body: { "command": "cl run evaluate.py: 0xdcf10e1da32e45ce970bbb07fd4694eb", "worksheet_uuid": "0x1fc53883bf2f432eb3bc0ae4164ee0dd" } Local variables: bundle_spec=None worksheet_uuid='0x1fc53883bf2f432eb3bc0ae4164ee0dd' client=<codalab.client.json_api_client.JsonApiClient object at 0x7f678015a6a0> Traceback (most recent call last): File "/opt/codalab-worksheets/codalab/server/rest_server.py", line 106, in wrapper return callback(*args, **kwargs) File "/usr/local/bin/bottle.py", line 1732, in wrapper rv = callback(*a, **ka) File "/opt/codalab-worksheets/codalab/server/json_api_plugin.py", line 18, in wrapper result = callback(*args, **kwargs) File "/opt/codalab-worksheets/codalab/rest/cli.py", line 48, in post_worksheets_command return general_command(query['worksheet_uuid'], query['command']) File "/opt/codalab-worksheets/codalab/rest/cli.py", line 149, in general_command structured_result = cli.do_command(args) File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 839, in do_command structured_result = command_fn() File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 833, in <lambda> command_fn = lambda: args.function(self, args) File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 1527, in do_run_command targets = self.resolve_key_targets(client, worksheet_uuid, args.target_spec) File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 585, in resolve_key_targets client, worksheet_uuid, target_spec, allow_remote=False File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 563, in resolve_target bundle_uuid = BundleCLI.resolve_bundle_uuid(client, worksheet_uuid, bundle_spec) File "/opt/codalab-worksheets/codalab/lib/bundle_cli.py", line 597, in resolve_bundle_uuid if spec_util.UUID_REGEX.match(bundle_spec): TypeError: expected string or bytes-like object ```
0.0
9647ccf5032218c3a80c1d80e1465573f11f6e3b
[ "tests/lib/cli_util_test.py::CLIUtilTest::test_desugar", "tests/lib/cli_util_test.py::CLIUtilTest::test_parse_key_target" ]
[ "tests/lib/cli_util_test.py::CLIUtilTest::test_parse_target_spec" ]
{ "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-03-01 18:35:20+00:00
apache-2.0
1,619
codalab__codalab-worksheets-2239
diff --git a/codalab/worker/file_util.py b/codalab/worker/file_util.py index 1d7bb0c7..3a7703df 100644 --- a/codalab/worker/file_util.py +++ b/codalab/worker/file_util.py @@ -11,7 +11,20 @@ import bz2 from codalab.common import BINARY_PLACEHOLDER NONE_PLACEHOLDER = '<none>' -GIT_PATTERN = '.git' + +# Patterns to always ignore when zipping up directories +ALWAYS_IGNORE_PATTERNS = ['.git', '._*', '__MACOSX'] + + +def get_tar_version_output(): + """ + Gets the current tar library's version information by returning the stdout + of running `tar --version`. + """ + try: + return subprocess.getoutput('tar --version') + except subprocess.CalledProcessError as e: + raise IOError(e.output) def tar_gzip_directory( @@ -28,19 +41,24 @@ def tar_gzip_directory( the directory structure are excluded. ignore_file: Name of the file where exclusion patterns are read from. """ - # Always ignore entries specified by the ignore file (e.g. .gitignore) args = ['tar', 'czf', '-', '-C', directory_path] + + # If the BSD tar library is being used, append --disable-copy to prevent creating ._* files + if 'bsdtar' in get_tar_version_output(): + args.append('--disable-copyfile') + if ignore_file: + # Ignore entries specified by the ignore file (e.g. .gitignore) args.append('--exclude-ignore=' + ignore_file) if follow_symlinks: args.append('-h') if not exclude_patterns: exclude_patterns = [] - # Always exclude .git - exclude_patterns.append(GIT_PATTERN) + exclude_patterns.extend(ALWAYS_IGNORE_PATTERNS) for pattern in exclude_patterns: args.append('--exclude=' + pattern) + if exclude_names: for name in exclude_names: # Exclude top-level entries provided by exclude_names
codalab/codalab-worksheets
3f6c44b683e3a2d8704118c6ca132a007493a809
diff --git a/tests/files/ignore_test/__MACOSX/ignored.txt b/tests/files/ignore_test/__MACOSX/ignored.txt new file mode 100644 index 00000000..ea10ec85 --- /dev/null +++ b/tests/files/ignore_test/__MACOSX/ignored.txt @@ -0,0 +1,1 @@ +ignored diff --git a/tests/files/ignore_test/dir/__MACOSX/ignored.txt b/tests/files/ignore_test/dir/__MACOSX/ignored.txt new file mode 100644 index 00000000..ea10ec85 --- /dev/null +++ b/tests/files/ignore_test/dir/__MACOSX/ignored.txt @@ -0,0 +1,1 @@ +ignored diff --git a/tests/worker/file_util_test.py b/tests/worker/file_util_test.py index 5b9817e4..8f539ee4 100644 --- a/tests/worker/file_util_test.py +++ b/tests/worker/file_util_test.py @@ -80,3 +80,17 @@ class FileUtilTest(unittest.TestCase): self.assertNotIn('ignored_dir', output_dir_entries) self.assertTrue(os.path.exists(os.path.join(output_dir, 'dir', 'not_ignored2.txt'))) self.assertFalse(os.path.exists(os.path.join(output_dir, 'dir', 'ignored2.txt'))) + + def test_tar_always_ignore(self): + dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'files/ignore_test') + temp_dir = tempfile.mkdtemp() + self.addCleanup(lambda: remove_path(temp_dir)) + output_dir = os.path.join(temp_dir, 'output') + + un_tar_directory(tar_gzip_directory(dir), output_dir, 'gz') + output_dir_entries = os.listdir(output_dir) + self.assertNotIn('._ignored', output_dir_entries) + self.assertIn('dir', output_dir_entries) + self.assertNotIn('__MACOSX', output_dir_entries) + self.assertFalse(os.path.exists(os.path.join(output_dir, 'dir', '__MACOSX'))) + self.assertFalse(os.path.exists(os.path.join(output_dir, 'dir', '._ignored2')))
Get rid of ._ files when uploading from a Mac Get rid of `._` files when using the tar library with `COPYFILE_DISABLE=1`.
0.0
3f6c44b683e3a2d8704118c6ca132a007493a809
[ "tests/worker/file_util_test.py::FileUtilTest::test_tar_always_ignore" ]
[ "tests/worker/file_util_test.py::FileUtilTest::test_bz2_file", "tests/worker/file_util_test.py::FileUtilTest::test_gzip_bytestring", "tests/worker/file_util_test.py::FileUtilTest::test_gzip_stream", "tests/worker/file_util_test.py::FileUtilTest::test_tar_empty", "tests/worker/file_util_test.py::FileUtilTest::test_tar_exclude_ignore", "tests/worker/file_util_test.py::FileUtilTest::test_tar_has_files" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-05-03 04:40:45+00:00
apache-2.0
1,620
codesankalp__dsalgo-73
diff --git a/dsalgo/search.py b/dsalgo/search.py new file mode 100644 index 0000000..3cbb7c3 --- /dev/null +++ b/dsalgo/search.py @@ -0,0 +1,223 @@ +import math + + +class Search: + + def __init__(self, arr, number): + """ + Class to search a number in array + + :args: arr (list) -> number to search from + n (int) -> number to search + + :return: index (int) -> if number found + -1 (int) -> if not found + """ + self.arr = arr + self.number = number + + def binary_search(self): + + """ + Binary Search: + Search a sorted array by repeatedly + dividing the search interval in half. + Begin with an interval covering the whole array. + If the value of the search key is less than + the item in the middle of the interval, + narrow the interval to the lower half. + Otherwise narrow it to the upper half. + Repeatedly check until the value is found or the + interval is empty. + + params : array/list arr, x --> search value + + return : found --> returns index, not found --> -1 + """ + arr = sorted(self.arr) + x = self.number + low = 0 + high = len(arr) - 1 + mid = 0 + + while low <= high: + + mid = (high + low) // 2 + if arr[mid] < x: + low = mid + 1 + + elif arr[mid] > x: + high = mid - 1 + + else: + return mid + + return -1 + + def linear_search(self): + """ + Linear Search + Start from the leftmost element of arr[] and one by + one compare x with each element of arr[] + If x matches with an element, return the index. + If x doesn’t match with any of elements, return -1. + + params : array/list --> arr, value --> x + + return : found --> int index, not found --> -1 + + """ + arr = self.arr + x = self.number + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + + def jump_search(self): + """ + Jump Search + + Like Binary Search, Jump Search is a searching algorithm for + sorted arrays. The basic idea is to check fewer elements + (than linear search) by jumping ahead by fixed steps + or skipping some elements + in place of searching all elements. + + params : array --> arr, value --> x + + returns : found --> int index, not found --> -1 + + """ + arr = sorted(self.arr) + x = self.number + flag = 0 + interval = int(math.sqrt(len(arr))) + for i in range(0, len(arr), interval): + if arr[i] > x: + chunk = i + flag = 1 + break + if arr[i] == x: + return i + if flag == 0: + c = i + for j in arr[i:]: + if j == x: + return c + c += 1 + else: + arr_ls = arr[chunk-interval:chunk] + ind = [i for i, d in enumerate(arr_ls) if d == x] + return chunk-interval+ind[0] + + def interpolation_search(self): + + """ + Interpolation Search + The Interpolation Search is an improvement over Binary Search + for instances, where the values in a sorted array are uniformly + distributed. Binary Search always goes to the middle element + to check. On the other hand, interpolation search may go to + different locations according to the value of the key being + searched. + + params : array --> arr, array length --> length, value --> x + + return : found --> int index, not found --> -1 + """ + arr = sorted(self.arr) + x = self.number + length = len(arr) + lo = 0 + hi = (length - 1) + + while lo <= hi and x >= arr[lo] and x <= arr[hi]: + if lo == hi: + if arr[lo] == x: + return lo + return -1 + + pos = lo + int(((float(hi - lo) / + (arr[hi] - arr[lo])) * (x - arr[lo]))) + + if arr[pos] == x: + return pos + + if arr[pos] < x: + lo = pos + 1 + + else: + hi = pos - 1 + return -1 + + def fibonacci_search(self): + + """ + Fibonacci Search + The idea is to first find the smallest Fibonacci number + that is greater than or equal to the length of given array. + Let the found Fibonacci number be fib (m’th Fibonacci number). + We use (m-2)’th Fibonacci number as the index + (If it is a valid index). Let (m-2)’th Fibonacci Number be i, + we compare arr[i] with x, if x is same, we return i. + Else if x is greater, we recur for subarray after i, + else we recur for subarray before i. + + Params : array --> arr, value --> x, array length + + return : found --> int index, not found --> -1 + + """ + arr = sorted(self.arr) + x = self.number + arr_len = len(arr) + fibMMm2 = 0 # (m-2)'th Fibonacci No. + fibMMm1 = 1 # (m-1)'th Fibonacci No. + fibM = fibMMm2 + fibMMm1 # m'th Fibonacci + + while (fibM < arr_len): + fibMMm2 = fibMMm1 + fibMMm1 = fibM + fibM = fibMMm2 + fibMMm1 + + # Marks the eliminated range from front + offset = -1 + + # while there are elements to be inspected. + # Note that we compare arr[fibMm2] with x. + # When fibM becomes 1, fibMm2 becomes 0 + while (fibM > 1): + + # Check if fibMm2 is a valid location + i = min(offset+fibMMm2, arr_len-1) + + # If x is greater than the value at + # index fibMm2, cut the subarray array + # from offset to i + if (arr[i] < x): + fibM = fibMMm1 + fibMMm1 = fibMMm2 + fibMMm2 = fibM - fibMMm1 + offset = i + + # If x is less than the value at + # index fibMm2, cut the subarray + # after i+1 + elif (arr[i] > x): + fibM = fibMMm2 + fibMMm1 = fibMMm1 - fibMMm2 + fibMMm2 = fibM - fibMMm1 + + # element found. return index + else: + return i + + # comparing the last element with x */ + if(fibMMm1 and arr[offset+1] == x): + return offset+1 + + # element not found. return -1 + return -1
codesankalp/dsalgo
97cd3fd44fefc5321136e98eca4537c959e39285
diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/heap_tests.py b/tests/test_heap.py similarity index 92% rename from tests/heap_tests.py rename to tests/test_heap.py index 817f304..35cb266 100644 --- a/tests/heap_tests.py +++ b/tests/test_heap.py @@ -17,7 +17,3 @@ class TestHeap(unittest.TestCase): self.maxHeap.insert(i) self.assertEqual(self.minHeap.root(), min(self.minHeap.to_list())) self.assertEqual(self.maxHeap.root(), max(self.maxHeap.to_list())) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_search.py b/tests/test_search.py new file mode 100644 index 0000000..e3912ef --- /dev/null +++ b/tests/test_search.py @@ -0,0 +1,30 @@ +import unittest +from dsalgo.search import Search +import random + + +class Test_seacrch(unittest.TestCase): + def setUp(self): + self.test_array = [i for i in range(random.randint(0, 100))] + self.to_search = random.choice(self.test_array) + self.search = Search(self.test_array, self.to_search) + + def test_linear_search(self): + self.answer = self.test_array.index(self.to_search) + self.assertEqual(self.answer, self.search.linear_search()) + + def test_binary_search(self): + self.answer = sorted(self.test_array).index(self.to_search) + self.assertEqual(self.answer, self.search.binary_search()) + + def test_jump_search(self): + self.answer = sorted(self.test_array).index(self.to_search) + self.assertEqual(self.answer, self.search.jump_search()) + + def test_interpolation_search(self): + self.answer = sorted(self.test_array).index(self.to_search) + self.assertEqual(self.answer, self.search.interpolation_search()) + + def test_fibonacci_search(self): + self.answer = sorted(self.test_array).index(self.to_search) + self.assertEqual(self.answer, self.search.fibonacci_search()) diff --git a/tests/sort_tests.py b/tests/test_sort.py similarity index 97% rename from tests/sort_tests.py rename to tests/test_sort.py index 690f6d2..7c1cca2 100644 --- a/tests/sort_tests.py +++ b/tests/test_sort.py @@ -42,10 +42,3 @@ class TestSort(unittest.TestCase): self.assertEqual(self.bySort,sortedArray) revsortedArray=Sort(self.testArray,"merge",True) self.assertEqual(self.revBySort,revsortedArray) - -if __name__=='__main__': - unittest.main() - - - -
Implement searching algorithms Add these algorithms - [x] 1. Linear Search - [x] 2. Binary Search - [x] 3. Jump Search - [x] 4. Interpolation Search - [ ] 5. Exponential Search - [x] 6. Fibonacci Search - [ ] 7. Recursive program to linearly search an element in a given array - [ ] 8. Recursive function to do a substring search Also write test cases for the same. Tests and code can be divided in two commits though.
0.0
97cd3fd44fefc5321136e98eca4537c959e39285
[ "tests/test_heap.py::TestHeap::test_root", "tests/test_search.py::Test_seacrch::test_binary_search", "tests/test_search.py::Test_seacrch::test_fibonacci_search", "tests/test_search.py::Test_seacrch::test_interpolation_search", "tests/test_search.py::Test_seacrch::test_jump_search", "tests/test_search.py::Test_seacrch::test_linear_search", "tests/test_sort.py::TestSort::test_bubble", "tests/test_sort.py::TestSort::test_bubble_recursion", "tests/test_sort.py::TestSort::test_merge", "tests/test_sort.py::TestSort::test_quick", "tests/test_sort.py::TestSort::test_selection" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-10-05 13:17:16+00:00
mit
1,621
codesankalp__dsalgo-78
diff --git a/dsalgo/doubly_linked_list.py b/dsalgo/doubly_linked_list.py new file mode 100644 index 0000000..fb339ba --- /dev/null +++ b/dsalgo/doubly_linked_list.py @@ -0,0 +1,59 @@ +class Node(object): + # Doubly linked node + def __init__(self, data=None, next=None, prev=None): + self.data = data + self.next = next + self.prev = prev + + +class doubly_linked_list(object): + # Use items = doubly_linked_list() + def __init__(self): + self.head = None + self.tail = None + self.count = 0 + + def append(self, data): + # items.append_item() append elements any number of times + new_item = Node(data, None, None) + if self.head is None: + self.head = new_item + self.tail = self.head + else: + new_item.prev = self.tail + self.tail.next = new_item + self.tail = new_item + self.count += 1 + + def prepend(self, data): + # Insert a node in the beginning + new_item = Node(data, None, None) + new_item.next = self.head + self.head = new_item + if self.tail is None: + self.tail = self.head + self.count += 1 + + def print_foward(self): + # to print the output use items.print_foward() + for node in self.__iter(): + print(node) + + def size(self): + return self.count + + def __iter(self): + # Iterate the list + current = self.head + while current: + item_val = current.data + current = current.next + yield item_val + + def to_list(self): + current_node = self.head + arr = [] + while current_node is not None: + arr.append(current_node.data) + current_node = current_node.next + return arr
codesankalp/dsalgo
0d093520ab05f55a0715e2edfc146864f05e30c3
diff --git a/tests/test_doubly_linked_list.py b/tests/test_doubly_linked_list.py new file mode 100644 index 0000000..fb507b9 --- /dev/null +++ b/tests/test_doubly_linked_list.py @@ -0,0 +1,27 @@ +import unittest +from dsalgo.doubly_linked_list import ( + doubly_linked_list as dll) +import random + + +class TestDoublyLinkedList(unittest.TestCase): + + def setUp(self): + self.test_array = \ + [random.randint(-100, 100) for _ in range(random.randint(0, 100))] + + def test_append(self): + self.dll = dll() + for i in self.test_array: + self.dll.append(i) + self.assertEqual(self.dll.to_list(), self.test_array) + + def test_prepend(self): + self.dll = dll() + for i in self.test_array: + self.dll.prepend(i) + self.assertEqual(self.dll.to_list(), self.test_array[::-1]) + + def test_size(self): + self.test_append() + self.assertEqual(self.dll.size(), len(self.test_array))
Insert an item in front of a doubly linked list Currently there is a `doubly_linked_list.py` file in dsalgo (not merged yet) folder but there is no way to insert an item in front of a given doubly linked list for example, if function name is `insert_start()` (this is preferred name) then: - [ ] code for which items.insert_start([_this contains required object_]) will show up the new object added in front of the doubly linked list created previously in continuation with issue #67 - [ ] make a pull request for queue branch not for master branch. - [ ] update the queue branch with the master. P.S : Refer [this](https://github.com/codesankalp/dsalgo/pull/57/commits/a9e3e248d7d5745b00661f46ed5324c9f0ea17e2) commit for doubly_linked_list.py file. or the issue #56 in continuation with issue #67
0.0
0d093520ab05f55a0715e2edfc146864f05e30c3
[ "tests/test_doubly_linked_list.py::TestDoublyLinkedList::test_append", "tests/test_doubly_linked_list.py::TestDoublyLinkedList::test_prepend", "tests/test_doubly_linked_list.py::TestDoublyLinkedList::test_size" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-10-06 19:39:35+00:00
mit
1,622
codesankalp__dsalgo-9
diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c0548c9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 0.1.x | :white_check_mark: | + + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. diff --git a/dsalgo/sort.py b/dsalgo/sort.py index 0804112..5d30b2f 100644 --- a/dsalgo/sort.py +++ b/dsalgo/sort.py @@ -8,7 +8,12 @@ class Sort: :array: (list) : a python list :algo: (str): sorting algorithm type values supported are: - 1. bubble + 1.bubble + 2.merge + 3.bubble_recursion + 4.selection + 5.quick + :reverse: (bool) : default = False if True order is reversed. return: @@ -20,9 +25,16 @@ class Sort: if self.algo == 'bubble': return bubble(self.array, self.reverse) + if self.algo == 'merge': + return merge(self.array, self.reverse) + if self.algo =='bubble_recursion': + return bubble_recursion(self.array,self.reverse) + if self.algo =='selection': + return selection(self.array,self.reverse) + if self.algo =='quick': + return quick(self.array,self.reverse) else: sys.stderr.write("Error: unsupported sorting algorithm passed!") - def bubble(array, reverse=False): ''' @@ -50,3 +62,142 @@ def bubble(array, reverse=False): if reverse==True: return array[::-1] return array + +def merge(array,reverse=False): + + + """ + 1.Divide: + If q is the half-way point between p and r, then we can split the subarray A[p..r] + into two arrays A[p..q] and A[q+1, r]. + 2.Conquer: + In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1, r]. + If we haven't yet reached the base case, + we again divide both these subarrays and try to sort them. + 3.Combine: + When the conquer step reaches the base step and we get two sorted subarrays A[p..q] and A[q+1, r] for array A[p..r], + we combine the results by creating a sorted array A[p..r] from two sorted subarrays A[p..q] and A[q+1, r]. + """ + + if len(array) >1: + mid = len(array)//2 # mid + left = array[:mid] # Dividing the array elements + right = array[mid:] # into 2 halves + + merge(left) # Sorting the first half + merge(right) # Sorting the second half + i = j = k = 0 + + # Copy data to left[] and right[] + while i < len(left) and j < len(right): + if left[i] < right[j]: + array[k] = left[i] + i+= 1 + else: + array[k] = right[j] + j+= 1 + k+= 1 + + # Checking if any element was left + while i < len(left): + array[k] = left[i] + i+= 1 + k+= 1 + + while j < len(right): + array[k] = right[j] + j+= 1 + k+= 1 + if reverse==True : + return array[::-1] + return array + +def bubble_recursion(array,reverse=False): + for i, num in enumerate(array): + try: + if array[i+1] < num: + array[i] = array[i+1] + array[i+1] = num + bubble_recursion(array) + except IndexError: + pass + if reverse==True: + return array[::-1] + return array + +def selection(array,reverse=False): + """The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) + from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. + + 1) The subarray which is already sorted. + 2) Remaining subarray which is unsorted. + In every iteration of selection sort, the minimum element (considering ascending order) + from the unsorted subarray is picked and moved to the sorted subarray.""" + + for i in range(len(array)): + min_idx = i + for j in range(i+1, len(array)): + if array[min_idx] > array[j]: + min_idx = j + array[i], array[min_idx] = array[min_idx], array[i] #Swapping values + + if reverse==True: + return array[::-1] + + return array + +def quick(array,reverse=False): + """The algorithm can be broken down into three parts​​: + 1.Partitioning the array about the pivot. + 2.Passing the smaller arrays to the recursive calls. + 3.Joining the sorted arrays that are returned from the recursive call and the pivot. + + """ + start=0 + end=len(array)-1 + quick_sort(array,start,end) + + if reverse==True: + return array[::-1] + + return array + +def quick_sort(array, start, end): + if start >= end: + return + + p = partition(array, start, end) + quick_sort(array, start, p-1) + quick_sort(array, p+1, end) + +def partition(array, start, end): + pivot = array[start] + low = start + 1 + high = end + + while True: + #If the current value we're looking at is larger than the pivot + # it's in the right place (right side of pivot) and we can move left, + # to the next element. + # We also need to make sure we haven't surpassed the low pointer, since that + # indicates we have already moved all the elements to their correct side of the pivot + while low <= high and array[high] >= pivot: + high = high - 1 + + # Opposite process of the one above + while low <= high and array[low] <= pivot: + low = low + 1 + + # We either found a value for both high and low that is out of order + # or low is higher than high, in which case we exit the loop + if low <= high: + array[low], array[high] = array[high], array[low] + # The loop continues + else: + # We exit out of the loop + break + + array[start], array[high] = array[high], array[start] + + return high +
codesankalp/dsalgo
8c7a94849dd8a777a6cade7c8344f5745dc9ccdf
diff --git a/tests/sort_tests.py b/tests/sort_tests.py new file mode 100644 index 0000000..690f6d2 --- /dev/null +++ b/tests/sort_tests.py @@ -0,0 +1,51 @@ +import unittest +from dsalgo.sort import Sort +import random +class TestSort(unittest.TestCase): + def setUp(self): + self.testArray=[] + self.bySort=[] + self.revBySort=[] + for item in range(0,5): + self.testArray.append(round(((item*random.random())*20),2)) + self.bySort=self.testArray.copy() + self.revBySort=self.testArray.copy() + self.bySort.sort() + self.revBySort.sort(reverse=True) + + def test_bubble(self): + sortedArray=Sort(self.testArray,"bubble") + self.assertEqual(self.bySort,sortedArray) + revsortedArray=Sort(self.testArray,"bubble",True) + self.assertEqual(self.revBySort,revsortedArray) + + def test_merge(self): + sortedArray=Sort(self.testArray,"merge") + self.assertEqual(self.bySort,sortedArray) + revsortedArray=Sort(self.testArray,"merge",True) + self.assertEqual(self.revBySort,revsortedArray) + + def test_bubble_recursion(self): + sortedArray=Sort(self.testArray,"merge") + self.assertEqual(self.bySort,sortedArray) + revsortedArray=Sort(self.testArray,"merge",True) + self.assertEqual(self.revBySort,revsortedArray) + + def test_selection(self): + sortedArray=Sort(self.testArray,"merge") + self.assertEqual(self.bySort,sortedArray) + revsortedArray=Sort(self.testArray,"merge",True) + self.assertEqual(self.revBySort,revsortedArray) + + def test_quick(self): + sortedArray=Sort(self.testArray,"merge") + self.assertEqual(self.bySort,sortedArray) + revsortedArray=Sort(self.testArray,"merge",True) + self.assertEqual(self.revBySort,revsortedArray) + +if __name__=='__main__': + unittest.main() + + + +
Basic sorting algorithms Implement all the sorting algorithms using class in one python file. For more details about implementation contact @KapilBansal320
0.0
8c7a94849dd8a777a6cade7c8344f5745dc9ccdf
[ "tests/sort_tests.py::TestSort::test_bubble_recursion", "tests/sort_tests.py::TestSort::test_merge", "tests/sort_tests.py::TestSort::test_quick", "tests/sort_tests.py::TestSort::test_selection" ]
[ "tests/sort_tests.py::TestSort::test_bubble" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2020-08-31 08:19:19+00:00
mit
1,623
codingedward__flask-sieve-17
diff --git a/docs/source/index.md b/docs/source/index.md index fedf4c7..8a4e9ce 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -112,7 +112,11 @@ def register(): 'avatar': ['image', 'dimensions:200x200'], 'username': ['required', 'string', 'min:6'], } - validator = Validator(rules=rules, request=request) + messages = { + 'email.required': 'Yikes! The email is required', + 'avatar.dimensions': 'Please provide an avatar with the right dimensions' + } + validator = Validator(rules=rules, messages=messages, request=request) if validator.passes(): return jsonify({'message': 'Registered!'}), 200 return jsonify(validator.messages()), 400 diff --git a/flask_sieve/translator.py b/flask_sieve/translator.py index c57d3d0..12fdc1e 100644 --- a/flask_sieve/translator.py +++ b/flask_sieve/translator.py @@ -26,9 +26,9 @@ class Translator: translated = [] for validation in validations: if not validation['is_valid']: - custom_message_key = validation['attribute'] + '.' + validation['rule'] - if custom_message_key in self._custom_messages: - translated.append(self._custom_messages[custom_message_key]) + validation_key = validation['attribute'] + '.' + validation['rule'] + if validation_key in self._custom_messages: + translated.append(self._custom_messages[validation_key]) else: translated.append(self._translate_validation(validation)) if len(translated): @@ -41,13 +41,13 @@ class Translator: if validation['rule'] in self._size_rules: message = message[validation['attribute_type']] message_fields = self._extract_message_fields(message) - fields_to_params = self._zip_fields_to_params( - fields=message_fields, - params=validation['params'] - ) + fields_to_params = \ + self._zip_fields_to_params(fields=message_fields, + params=validation['params']) for field in message_fields: if field == ':attribute': - message = message.replace(field, validation['attribute']) + message = message.replace(field, ' '.join([word for word in + validation['attribute'].split('_') if word != ''])) else: message = message.replace(field, fields_to_params[field]) return message diff --git a/flask_sieve/validator.py b/flask_sieve/validator.py index 0c205c0..17eaf6e 100644 --- a/flask_sieve/validator.py +++ b/flask_sieve/validator.py @@ -8,9 +8,10 @@ from flask_sieve.rules_processor import RulesProcessor class Validator: - def __init__(self, rules=None, request=None, custom_handlers=None): + def __init__(self, rules=None, request=None, custom_handlers=None, + messages=None, **kwargs): self._parser = Parser() - self._translator = Translator() + self._translator = Translator(custom_messages=messages) self._processor = RulesProcessor() self._rules = rules or {} self._custom_handlers = custom_handlers or {} diff --git a/setup.py b/setup.py index adc5945..c8e2469 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name='flask-sieve', description='A Laravel inspired requests validator for Flask', long_description='Find the documentation at https://flask-sieve.readthedocs.io/en/latest/', - version='1.2.0', + version='1.2.1', url='https://github.com/codingedward/flask-sieve', license='BSD-2', author='Edward Njoroge',
codingedward/flask-sieve
7eb31d399a054df1a3397f20a30203d847323f4e
diff --git a/tests/test_validator.py b/tests/test_validator.py index a29371a..d41ebd9 100644 --- a/tests/test_validator.py +++ b/tests/test_validator.py @@ -11,19 +11,20 @@ class TestValidator(unittest.TestCase): def test_translates_validations(self): self.set_validator_params( - rules={'email': ['required', 'email']}, - request={'email': 'invalid_email'}, + rules={'email_address': ['required', 'email']}, + request={'email_address': 'invalid_email'}, ) self.assertTrue(self._validator.fails()) - self.assertIn('valid email', str(self._validator.messages())) + self.assertIn('valid email address', str(self._validator.messages())) def test_translates_validations_with_param(self): self.set_validator_params( - rules={'name': ['required', 'string', 'min:6']}, - request={'name': 'joe'}, + rules={'first_name': ['required', 'string', 'min:6']}, + request={'first_name': 'joe'}, ) self.assertTrue(self._validator.fails()) self.assertIn('6 characters', str(self._validator.messages())) + self.assertIn('first name', str(self._validator.messages())) def test_translates_validations_with_rest_params(self): self.set_validator_params( @@ -95,6 +96,23 @@ class TestValidator(unittest.TestCase): ] }, self._validator.messages()) + def test_translates_validations_with_custom_messages_on_constructor(self): + validator = Validator( + rules={'email': ['required', 'email']}, + request={'email': ''}, + messages={ + 'email.required': 'Kindly provide the email', + 'email.email': 'Whoa! That is not valid', + } + ) + self.assertTrue(validator.fails()) + self.assertDictEqual({ + 'email': [ + 'Kindly provide the email', + 'Whoa! That is not valid' + ] + }, validator.messages()) + def test_translates_validations_with_custom_handler(self): def validate_odd(value, **kwargs): return int(value) % 2
Custom message in manual validation Hi bro, I do not see that we can custom messages in docs in manual validation mode. Can you add these features? this what I need.
0.0
7eb31d399a054df1a3397f20a30203d847323f4e
[ "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_messages_on_constructor", "tests/test_validator.py::TestValidator::test_translates_validations_with_param" ]
[ "tests/test_validator.py::TestValidator::test_cannot_set_custom_handler_without_validate_keyword", "tests/test_validator.py::TestValidator::test_handles_different_types_of_requests", "tests/test_validator.py::TestValidator::test_translates_validations", "tests/test_validator.py::TestValidator::test_translates_validations_set_through_custom_handlers", "tests/test_validator.py::TestValidator::test_translates_validations_with_all_params", "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_handler", "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_messages", "tests/test_validator.py::TestValidator::test_translates_validations_with_rest_params", "tests/test_validator.py::TestValidator::test_validate_decorator" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-17 01:24:08+00:00
bsd-2-clause
1,624
codingedward__flask-sieve-20
diff --git a/flask_sieve/conditional_inclusion_rules.py b/flask_sieve/conditional_inclusion_rules.py new file mode 100644 index 0000000..99001ba --- /dev/null +++ b/flask_sieve/conditional_inclusion_rules.py @@ -0,0 +1,8 @@ +conditional_inclusion_rules = [ + 'required_if', + 'required_unless', + 'required_with', + 'required_with_all', + 'required_without', + 'required_without_all', +] diff --git a/flask_sieve/rules_processor.py b/flask_sieve/rules_processor.py index c6e4f7e..d6f58b2 100644 --- a/flask_sieve/rules_processor.py +++ b/flask_sieve/rules_processor.py @@ -13,6 +13,7 @@ from PIL import Image from dateutil.parser import parse as dateparse from werkzeug.datastructures import FileStorage +from .conditional_inclusion_rules import conditional_inclusion_rules class RulesProcessor: def __init__(self, app=None, rules=None, request=None): @@ -36,24 +37,27 @@ class RulesProcessor: self._attributes_validations = {} for attribute, rules in self._rules.items(): should_bail = self._has_rule(rules, 'bail') - nullable = self._has_rule(rules, 'nullable') validations = [] for rule in rules: + is_valid = False handler = self._get_rule_handler(rule['name']) value = self._attribute_value(attribute) attr_type = self._get_type(value, rules) - is_valid = False - if value is None and nullable: + is_nullable = self._is_attribute_nullable( + attribute=attribute, + params=rule['params'], + rules=rules, + ) + if value is None and is_nullable: is_valid = True else: is_valid = handler( value=value, attribute=attribute, params=rule['params'], - nullable=nullable, + nullable=is_nullable, rules=rules ) - validations.append({ 'attribute': attribute, 'rule': rule['name'], @@ -523,6 +527,29 @@ class RulesProcessor: r'^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$', str(value).lower() ) is not None + + def _is_attribute_nullable(self, attribute, params, rules, **kwargs): + is_explicitly_nullable = self._has_rule(rules, 'nullable') + if is_explicitly_nullable: + return True + value = self._attribute_value(attribute) + if value is not None: + return False + attribute_conditional_rules = list(filter(lambda rule: rule['name'] in conditional_inclusion_rules, rules)) + if len(attribute_conditional_rules) == 0: + return False + for conditional_rule in attribute_conditional_rules: + handler = self._get_rule_handler(conditional_rule['name']) + is_conditional_rule_valid = handler( + value=value, + attribute=attribute, + params=conditional_rule['params'], + nullable=False, + rules=rules + ) + if not is_conditional_rule_valid: + return False + return True @staticmethod def _compare_dates(first, second, comparator): @@ -628,4 +655,3 @@ class RulesProcessor: 'Cannot call method %s with value %s' % (method.__name__, str(value)) ) - diff --git a/watch.sh b/watch.sh new file mode 100755 index 0000000..340fb07 --- /dev/null +++ b/watch.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +watchman-make -p "**/*.py" --run "nosetests --with-coverage --cover-package flask_sieve"
codingedward/flask-sieve
2a8e2851c2a2f91a73f9d494883a867469af3f26
diff --git a/tests/test_rules_processor.py b/tests/test_rules_processor.py index abbf64b..167145c 100644 --- a/tests/test_rules_processor.py +++ b/tests/test_rules_processor.py @@ -696,8 +696,8 @@ class TestRulesProcessor(unittest.TestCase): request={'field': '', 'field_2': 'three'} ) self.assert_passes( - rules={'field': ['size:0']}, - request={'field': self.image_file} + rules={'field': ['required_if:field_2,one,two', 'integer']}, + request={'field_1': '', 'field_2': 'xxxx'} ) self.assert_fails( rules={'field': ['required_if:field_2,one,two']}, @@ -714,8 +714,8 @@ class TestRulesProcessor(unittest.TestCase): request={'field': '', 'field_2': 'one'} ) self.assert_fails( - rules={'field': ['required_unless:field_2,one,two']}, - request={'field': '', 'field_2': 'three'} + rules={'field': ['required_unless:field_2,one,two', 'string']}, + request={'field_2': 'three'} ) def test_validates_required_with(self): @@ -763,6 +763,43 @@ class TestRulesProcessor(unittest.TestCase): rules={'field': ['required_without:field_2,field_3']}, request={'field': '', 'field_2': ''} ) + self.assert_passes( + rules={ + 'id': ['required_without:name', 'integer'], + 'name': ['required_without:id', 'string', 'confirmed'] + }, + request={'id': 123} + ) + + def test_validates_required_multiple_required_withouts(self): + self.assert_passes( + rules={ + 'id': ['required_without:name', 'integer'], + 'name': ['required_without:id', 'string'], + }, + request={'id': 1, 'name': ''} + ) + self.assert_passes( + rules={ + 'id': ['required_without:name', 'integer'], + 'name': ['required_without:id', 'string', 'nullable'], + }, + request={'id': 1}, + ) + self.assert_passes( + rules={ + 'id': ['required_without:name', 'integer'], + 'id2': ['required_without:id', 'integer'], + }, + request={'id': 1} + ) + self.assert_fails( + rules={ + 'id': ['required_without:name', 'integer'], + 'id2': ['required_without:id', 'integer'], + }, + request={'name': 'hi'} + ) def test_validates_required_without_all(self): self.assert_passes( @@ -787,6 +824,10 @@ class TestRulesProcessor(unittest.TestCase): rules={'field': ['same:field_2']}, request={'field': 1, 'field_2': 1} ) + self.assert_fails( + rules={'field': ['same:field_2']}, + request={'field': '1', 'field_2': 1} + ) self.assert_fails( rules={'field': ['same:field_2']}, request={'field': 1, 'field_2': 2}
validation error Hello I think I found a bug with `required_without` and `required_without_all` when I used it with parameter type. example: ``` def rules(self): return { 'id': ['required_without:name', integer], 'name': ['required_without:id', 'string'] } ``` and When the request json only has ID ``` { "id": 123 } ``` the error response is: ``` { "errors": { "user_id": [ "The name must be an string." ] }, "message": "Validation error", "success": false } ``` Can You please check this issue?
0.0
2a8e2851c2a2f91a73f9d494883a867469af3f26
[ "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_if", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_multiple_required_withouts", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_without" ]
[ "tests/test_rules_processor.py::TestRulesProcessor::test_allows_nullable_fields", "tests/test_rules_processor.py::TestRulesProcessor::test_assert_params_size", "tests/test_rules_processor.py::TestRulesProcessor::test_compare_dates", "tests/test_rules_processor.py::TestRulesProcessor::test_custom_handlers", "tests/test_rules_processor.py::TestRulesProcessor::test_get_rule_handler", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_accepted", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_active_url", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_after", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_after_or_equal", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_alpha", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_alpha_dash", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_alpha_num", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_array", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_before", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_before_or_equal", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_between", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_boolean", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_confirmed", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_date", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_date_equals", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_different", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_digits", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_digits_between", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_dimensions", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_distinct", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_email", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_exists", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_extension", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_file", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_filled", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_gt", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_gte", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_image", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_in", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_in_array", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_integer", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_ip", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_ipv4", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_ipv6", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_json", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_lt", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_lte", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_max", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_mime_types", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_min", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_not_in", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_not_regex", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_numeric", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_present", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_regex", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_unless", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_with", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_with_all", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_required_without_all", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_same", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_size", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_starts_with", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_string", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_timezone", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_unique", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_url", "tests/test_rules_processor.py::TestRulesProcessor::test_validates_uuid" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-05 23:20:04+00:00
mit
1,625
codingedward__flask-sieve-28
diff --git a/docs/source/index.md b/docs/source/index.md index 8a4e9ce..cad4271 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -580,6 +580,10 @@ The given _field_ must match the field under validation. The field under validation must have a size matching the given _value_. For string data, _value_ corresponds to the number of characters. For numeric data, _value_ corresponds to a given integer value. For an array, _size_ corresponds to the `count` of the array. For files, _size_ corresponds to the file size in kilobytes. +#### sometimes + +The other validations will only apply if this field is present and non-empty. Incompatible with _required_ and _nullable_. + #### starts_with:_foo_,_bar_,... The field under validation must start with one of the given values. diff --git a/flask_sieve/lang/en.py b/flask_sieve/lang/en.py index 5ba658f..ac34fb2 100644 --- a/flask_sieve/lang/en.py +++ b/flask_sieve/lang/en.py @@ -54,18 +54,21 @@ rule_messages = { 'file': 'The :attribute must be less than :value_0 kilobytes.', 'string': 'The :attribute must be less than :value_0 characters.', 'array': 'The :attribute must have less than :value_0 items.', + 'empty': 'The :attribute could not be validated since it is empty.' }, 'lte': { 'numeric': 'The :attribute must be less than or equal :value_0.', 'file': 'The :attribute must be less than or equal :value_0 kilobytes.', 'string': 'The :attribute must be less than or equal :value_0 characters.', 'array': 'The :attribute must not have more than :value_0 items.', + 'empty': 'The :attribute could not be validated since it is empty.' }, 'max': { 'numeric': 'The :attribute may not be greater than :max_0.', 'file': 'The :attribute may not be greater than :max_0 kilobytes.', 'string': 'The :attribute may not be greater than :max_0 characters.', 'array': 'The :attribute may not have more than :max_0 items.', + 'empty': 'The :attribute could not be validated since it is empty.' }, 'mime_types': 'The :attribute must be a file of type: :values_0.', 'min': { @@ -73,6 +76,7 @@ rule_messages = { 'file': 'The :attribute must be at least :min_0 kilobytes.', 'string': 'The :attribute must be at least :min_0 characters.', 'array': 'The :attribute must have at least :min_0 items.', + 'empty': 'The :attribute could not be validated since it is empty.' }, 'not_in': 'The selected :attribute is invalid.', 'not_regex': 'The :attribute format is invalid.', diff --git a/flask_sieve/rules_processor.py b/flask_sieve/rules_processor.py index d6f58b2..1fee1ba 100644 --- a/flask_sieve/rules_processor.py +++ b/flask_sieve/rules_processor.py @@ -246,6 +246,10 @@ class RulesProcessor: def validate_file(value, **kwargs): return isinstance(value, FileStorage) + @staticmethod + def validate_empty(value, **kwargs): + return value == '' + def validate_filled(self, value, attribute, nullable, **kwargs): if self.validate_present(attribute): return self.validate_required(value, attribute, nullable) @@ -364,18 +368,24 @@ class RulesProcessor: def validate_lt(self, value, params, **kwargs): self._assert_params_size(size=1, params=params, rule='lt') + if value == '': + return False value = self._get_size(value) lower = self._get_size(self._attribute_value(params[0])) return value < lower def validate_lte(self, value, params, **kwargs): self._assert_params_size(size=1, params=params, rule='lte') + if value == '': + return False value = self._get_size(value) lower = self._get_size(self._attribute_value(params[0])) return value <= lower def validate_max(self, value, params, **kwargs): self._assert_params_size(size=1, params=params, rule='max') + if value == '': + return False value = self._get_size(value) upper = self._get_size(params[0]) return value <= upper @@ -406,6 +416,9 @@ class RulesProcessor: def validate_nullable(value, **kwargs): return True + def validate_sometimes(self, value, **kwargs): + return True + def validate_numeric(self, value, **kwargs): return self._can_call_with_method(float, value) @@ -527,14 +540,16 @@ class RulesProcessor: r'^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$', str(value).lower() ) is not None - + def _is_attribute_nullable(self, attribute, params, rules, **kwargs): is_explicitly_nullable = self._has_rule(rules, 'nullable') if is_explicitly_nullable: return True value = self._attribute_value(attribute) - if value is not None: - return False + is_optional = self._has_rule(rules, 'sometimes') + if is_optional and value is not None: + return True + attribute_conditional_rules = list(filter(lambda rule: rule['name'] in conditional_inclusion_rules, rules)) if len(attribute_conditional_rules) == 0: return False @@ -621,6 +636,8 @@ class RulesProcessor: return 'array' elif self.validate_file(value): return 'file' + elif self.validate_empty(value): + return 'empty' return 'string' def _has_any_of_rules(self, subset, rules):
codingedward/flask-sieve
f072fd86fd7d68d577a9c70e92524912dcad7a42
diff --git a/tests/test_validator.py b/tests/test_validator.py index d41ebd9..fecfe45 100644 --- a/tests/test_validator.py +++ b/tests/test_validator.py @@ -163,6 +163,17 @@ class TestValidator(unittest.TestCase): ) self.assertTrue(self._validator.passes()) + def test_translates_validations_set_through_custom_handlers(self): + def validate_odd(value, **kwargs): + return int(value) % 2 + self._validator.set_custom_handlers([ + { + 'handler': validate_odd, + 'message':'This number must be odd.', + 'params_count':0 + } + ]) + def test_cannot_set_custom_handler_without_validate_keyword(self): def method_odd(value, **kwargs): return int(value) % 2 @@ -173,9 +184,43 @@ class TestValidator(unittest.TestCase): params_count=0 ) + def test_sometimes_request(self): + self.set_validator_params( + rules={'number': ['sometimes', 'max:5']}, + request={} + ) + self.assertTrue(self._validator.passes()) + + self.set_validator_params( + rules={'number': ['sometimes', 'max:5']}, + request={'number': ''} + ) + self.assertTrue(self._validator.fails()) + self.assertDictEqual({ + 'number': [ + 'The number could not be validated since it is empty.' + ] + }, self._validator.messages()) + + self.set_validator_params( + rules={'number': ['sometimes', 'max:5']}, + request={'number': 2} + ) + self.assertTrue(self._validator.passes()) + + self.set_validator_params( + rules={'number': ['sometimes', 'max:5']}, + request={'number': 10} + ) + self.assertTrue(self._validator.fails()) + self.assertDictEqual({ + 'number': [ + 'The number may not be greater than 5.' + ] + }, self._validator.messages()) + def set_validator_params(self, rules=None, request=None): rules = rules or {} request = request or {} self._validator.set_rules(rules) self._validator.set_request(request) -
Equivalent of "sometimes" Is there an equivalent of "sometimes" from Laravel validation? i.e. only validate the value if present and non-empty, otherwise skip the validation.
0.0
f072fd86fd7d68d577a9c70e92524912dcad7a42
[ "tests/test_validator.py::TestValidator::test_sometimes_request" ]
[ "tests/test_validator.py::TestValidator::test_cannot_set_custom_handler_without_validate_keyword", "tests/test_validator.py::TestValidator::test_handles_different_types_of_requests", "tests/test_validator.py::TestValidator::test_translates_validations", "tests/test_validator.py::TestValidator::test_translates_validations_set_through_custom_handlers", "tests/test_validator.py::TestValidator::test_translates_validations_with_all_params", "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_handler", "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_messages", "tests/test_validator.py::TestValidator::test_translates_validations_with_custom_messages_on_constructor", "tests/test_validator.py::TestValidator::test_translates_validations_with_param", "tests/test_validator.py::TestValidator::test_translates_validations_with_rest_params", "tests/test_validator.py::TestValidator::test_validate_decorator" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-21 22:09:11+00:00
mit
1,626