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
holoviz__datashader-1185
diff --git a/datashader/datatypes.py b/datashader/datatypes.py index 6c48e24..77dfff0 100644 --- a/datashader/datatypes.py +++ b/datashader/datatypes.py @@ -638,6 +638,17 @@ Invalid indices for take with allow_fill True: {inds}""".format( return np.array([v for v in self], dtype=dtype, copy=copy) + def tolist(self): + # Based on pandas ExtensionArray.tolist + if self.ndim > 1: + return [item.tolist() for item in self] + else: + return list(self) + + def __array__(self, dtype=None): + dtype = np.dtype(object) if dtype is None else np.dtype(dtype) + return np.asarray(self.tolist(), dtype=dtype) + @jit(nopython=True, nogil=True) def _eq_ragged_ragged(start_indices1,
holoviz/datashader
aed1760f9967454f356d9882d0c73b3de7ed9170
diff --git a/datashader/tests/test_dask.py b/datashader/tests/test_dask.py index 57ebc72..593eb98 100644 --- a/datashader/tests/test_dask.py +++ b/datashader/tests/test_dask.py @@ -11,6 +11,7 @@ from dask.context import config from numpy import nan import datashader as ds +from datashader.datatypes import RaggedArray import datashader.utils as du import pytest @@ -713,8 +714,8 @@ line_manual_range_params = [ # axis1 RaggedArray (dict(data={ - 'x': [[4, 0, -4], [-4, 0, 4, 4, 0, -4]], - 'y': [[0, -4, 0], [0, 4, 0, 0, 0, 0]], + 'x': RaggedArray([[4, 0, -4], [-4, 0, 4, 4, 0, -4]]), + 'y': RaggedArray([[0, -4, 0], [0, 4, 0, 0, 0, 0]]), }, dtype='Ragged[int64]'), dict(x='x', y='y', axis=1)), ] if sp: @@ -725,8 +726,8 @@ if sp: [-4, 0, 0, 4, 4, 0, 4, 0, 0, 0, -4, 0]] }, dtype='Line[int64]'), dict(geometry='geom')) ) [email protected]('DataFrame', DataFrames) [email protected]('df_kwargs,cvs_kwargs', line_manual_range_params) [email protected]('DataFrame', DataFrames[:1]) [email protected]('df_kwargs,cvs_kwargs', line_manual_range_params[5:7]) def test_line_manual_range(DataFrame, df_kwargs, cvs_kwargs): if DataFrame is dask_cudf_DataFrame: dtype = df_kwargs.get('dtype', '') @@ -999,8 +1000,8 @@ def test_auto_range_line(DataFrame): # axis1 ragged arrays (dict(data={ - 'x': pd.array([[-4, -2, 0], [2, 4]]), - 'y': pd.array([[0, -4, 0], [4, 0]]) + 'x': pd.array([[-4, -2, 0], [2, 4]], dtype='Ragged[float32]'), + 'y': pd.array([[0, -4, 0], [4, 0]], dtype='Ragged[float32]') }, dtype='Ragged[float32]'), dict(x='x', y='y', axis=1)) ]) def test_area_to_zero_fixedrange(DataFrame, df_kwargs, cvs_kwargs): diff --git a/datashader/tests/test_datatypes.py b/datashader/tests/test_datatypes.py index 0b2a5a3..68e3128 100644 --- a/datashader/tests/test_datatypes.py +++ b/datashader/tests/test_datatypes.py @@ -716,6 +716,11 @@ class TestRaggedGetitem(eb.BaseGetitemTests): def test_getitem_invalid(self, data): pass + @pytest.mark.skip(reason="Can't autoconvert ragged array to numpy array") + def test_getitem_series_integer_with_missing_raises(self, data, idx): + pass + + class TestRaggedGroupby(eb.BaseGroupbyTests): @pytest.mark.skip(reason="agg not supported") def test_groupby_agg_extension(self): @@ -835,7 +840,13 @@ class TestRaggedMethods(eb.BaseMethodsTests): pass class TestRaggedPrinting(eb.BasePrintingTests): - pass + @pytest.mark.skip(reason="Can't autoconvert ragged array to numpy array") + def test_dataframe_repr(self): + pass + + @pytest.mark.skip(reason="Can't autoconvert ragged array to numpy array") + def test_series_repr(self): + pass class TestRaggedMissing(eb.BaseMissingTests):
Support numpy 1.24 Prior to `numpy` 1.24 creating an array from ragged nested sequences produced a `VisibleDeprecationWarning`. With 1.24 this is now a `ValueError`. This is OK currently as `numba` doesn't yet support `numpy` 1.24 but it needs to be fixed here before that happens, so it is quite urgent. Thanks to @Hoxbro for identifying this (https://github.com/holoviz/geoviews/pull/608).
0.0
aed1760f9967454f356d9882d0c73b3de7ed9170
[ "datashader/tests/test_dask.py::test_line_manual_range[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_fixedrange[df_kwargs3-cvs_kwargs3-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange_gap[df_kwargs3-cvs_kwargs3-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange_gap[df_kwargs3-cvs_kwargs3-dask_DataFrame]" ]
[ "datashader/tests/test_dask.py::test_gpu_dependencies", "datashader/tests/test_dask.py::test_count[ddf0]", "datashader/tests/test_dask.py::test_any[ddf0]", "datashader/tests/test_dask.py::test_sum[ddf0]", "datashader/tests/test_dask.py::test_min[ddf0]", "datashader/tests/test_dask.py::test_max[ddf0]", "datashader/tests/test_dask.py::test_where_max[1-ddf0]", "datashader/tests/test_dask.py::test_where_max[2-ddf0]", "datashader/tests/test_dask.py::test_where_max[3-ddf0]", "datashader/tests/test_dask.py::test_where_max[4-ddf0]", "datashader/tests/test_dask.py::test_where_min[1-ddf0]", "datashader/tests/test_dask.py::test_where_min[2-ddf0]", "datashader/tests/test_dask.py::test_where_min[3-ddf0]", "datashader/tests/test_dask.py::test_where_min[4-ddf0]", "datashader/tests/test_dask.py::test_mean[ddf0]", "datashader/tests/test_dask.py::test_var[ddf0]", "datashader/tests/test_dask.py::test_std[ddf0]", "datashader/tests/test_dask.py::test_count_cat[ddf0]", "datashader/tests/test_dask.py::test_categorical_sum[ddf0]", "datashader/tests/test_dask.py::test_categorical_sum_binning[ddf0]", "datashader/tests/test_dask.py::test_categorical_mean[ddf0]", "datashader/tests/test_dask.py::test_categorical_mean_binning[ddf0]", "datashader/tests/test_dask.py::test_categorical_var[ddf0]", "datashader/tests/test_dask.py::test_categorical_std[ddf0]", "datashader/tests/test_dask.py::test_multiple_aggregates[ddf0]", "datashader/tests/test_dask.py::test_auto_range_points[dask_DataFrame]", "datashader/tests/test_dask.py::test_uniform_points[dask_DataFrame]", "datashader/tests/test_dask.py::test_uniform_diagonal_points[0-9-dask_DataFrame]", "datashader/tests/test_dask.py::test_uniform_diagonal_points[0-10-dask_DataFrame]", "datashader/tests/test_dask.py::test_uniform_diagonal_points[0-99-dask_DataFrame]", "datashader/tests/test_dask.py::test_uniform_diagonal_points[0-100-dask_DataFrame]", "datashader/tests/test_dask.py::test_log_axis_points[ddf0]", "datashader/tests/test_dask.py::test_line[dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs3-cvs_kwargs3-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs4-cvs_kwargs4-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_autorange[df_kwargs5-cvs_kwargs5-dask_DataFrame]", "datashader/tests/test_dask.py::test_line_x_constant_autorange[dask_DataFrame]", "datashader/tests/test_dask.py::test_log_axis_line[ddf0]", "datashader/tests/test_dask.py::test_auto_range_line[dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_fixedrange[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_fixedrange[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_fixedrange[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs3-cvs_kwargs3-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs4-cvs_kwargs4-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange[df_kwargs5-cvs_kwargs5-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange_gap[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange_gap[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_zero_autorange_gap[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs3-cvs_kwargs3-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs4-cvs_kwargs4-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange[df_kwargs5-cvs_kwargs5-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange_gap[df_kwargs0-cvs_kwargs0-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange_gap[df_kwargs1-cvs_kwargs1-dask_DataFrame]", "datashader/tests/test_dask.py::test_area_to_line_autorange_gap[df_kwargs2-cvs_kwargs2-dask_DataFrame]", "datashader/tests/test_dask.py::test_trimesh_no_double_edge", "datashader/tests/test_dask.py::test_trimesh_dask_partitions[1]", "datashader/tests/test_dask.py::test_trimesh_dask_partitions[2]", "datashader/tests/test_dask.py::test_trimesh_dask_partitions[3]", "datashader/tests/test_dask.py::test_trimesh_dask_partitions[4]", "datashader/tests/test_dask.py::test_trimesh_dask_partitions[5]", "datashader/tests/test_dask.py::test_combine_dtype[reduction0-bool-float32-ddf0]", "datashader/tests/test_dask.py::test_combine_dtype[reduction1-uint32-float32-ddf0]", "datashader/tests/test_dask.py::test_combine_dtype[reduction2-float64-float64-ddf0]", "datashader/tests/test_dask.py::test_combine_dtype[reduction3-float64-float64-ddf0]", "datashader/tests/test_dask.py::test_combine_dtype[reduction4-float64-float64-ddf0]", "datashader/tests/test_dask.py::test_log_axis_not_positive[canvas0-ddf0]", "datashader/tests/test_dask.py::test_log_axis_not_positive[canvas1-ddf0]", "datashader/tests/test_dask.py::test_log_axis_not_positive[canvas2-ddf0]", "datashader/tests/test_dask.py::test_log_axis_not_positive[canvas3-ddf0]", "datashader/tests/test_dask.py::test_line_antialias_where[1]", "datashader/tests/test_dask.py::test_line_antialias_where[2]", "datashader/tests/test_dask.py::test_line_antialias_where[3]", "datashader/tests/test_dask.py::test_canvas_size", "datashader/tests/test_datatypes.py::test_construct_ragged_dtype", "datashader/tests/test_datatypes.py::test_construct_ragged_array", "datashader/tests/test_datatypes.py::test_construct_ragged_array_from_ragged_array", "datashader/tests/test_datatypes.py::test_construct_ragged_array_fastpath", "datashader/tests/test_datatypes.py::test_validate_ragged_array_fastpath", "datashader/tests/test_datatypes.py::test_start_indices_dtype", "datashader/tests/test_datatypes.py::test_flat_array_type_inference[arg0-int64]", "datashader/tests/test_datatypes.py::test_flat_array_type_inference[arg1-bool]", "datashader/tests/test_datatypes.py::test_flat_array_type_inference[arg2-int32]", "datashader/tests/test_datatypes.py::test_flat_array_type_inference[arg3-float64]", "datashader/tests/test_datatypes.py::test_flat_array_type_inference[arg4-float32]", "datashader/tests/test_datatypes.py::test_isna", "datashader/tests/test_datatypes.py::test_get_item_scalar", "datashader/tests/test_datatypes.py::test_get_item_scalar_out_of_bounds[-1000]", "datashader/tests/test_datatypes.py::test_get_item_scalar_out_of_bounds[-6]", "datashader/tests/test_datatypes.py::test_get_item_scalar_out_of_bounds[5]", "datashader/tests/test_datatypes.py::test_get_item_scalar_out_of_bounds[1000]", "datashader/tests/test_datatypes.py::test_get_item_slice", "datashader/tests/test_datatypes.py::test_get_item_mask[mask0]", "datashader/tests/test_datatypes.py::test_get_item_mask[mask1]", "datashader/tests/test_datatypes.py::test_get_item_mask[mask2]", "datashader/tests/test_datatypes.py::test_get_item_list[inds0]", "datashader/tests/test_datatypes.py::test_get_item_list[inds1]", "datashader/tests/test_datatypes.py::test_get_item_list[inds2]", "datashader/tests/test_datatypes.py::test_get_item_list[inds3]", "datashader/tests/test_datatypes.py::test_get_item_list[inds4]", "datashader/tests/test_datatypes.py::test_factorization", "datashader/tests/test_datatypes.py::test_from_sequence", "datashader/tests/test_datatypes.py::test_copy", "datashader/tests/test_datatypes.py::test_take", "datashader/tests/test_datatypes.py::test_pandas_array_construction", "datashader/tests/test_datatypes.py::test_series_construction", "datashader/tests/test_datatypes.py::test_array_eq_scalar[scalar0]", "datashader/tests/test_datatypes.py::test_array_eq_scalar[scalar1]", "datashader/tests/test_datatypes.py::test_array_eq_numpy1", "datashader/tests/test_datatypes.py::test_array_eq_numpy2d", "datashader/tests/test_datatypes.py::test_array_eq_ragged", "datashader/tests/test_datatypes.py::test_equality_validation[a", "datashader/tests/test_datatypes.py::test_equality_validation[32]", "datashader/tests/test_datatypes.py::test_equality_validation[other2]", "datashader/tests/test_datatypes.py::test_equality_validation[other3]", "datashader/tests/test_datatypes.py::test_equality_validation[other4]", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_from_sequence_from_cls", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_array_from_scalars", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_series_constructor", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_series_constructor_no_data_with_index", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_series_constructor_scalar_na_with_index", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_dataframe_constructor_from_dict[True]", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_dataframe_constructor_from_dict[False]", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_dataframe_from_series", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_series_given_mismatched_index_raises", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_pandas_array", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_pandas_array_dtype", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_construct_empty_dataframe", "datashader/tests/test_datatypes.py::TestRaggedConstructors::test_empty", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_name", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_kind", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_dtype_from_name", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_dtype_unboxes_dtype", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_dtype_from_self", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_dtype_other_input", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_not_string_type", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_is_not_object_type", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_eq_with_str", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_eq_with_numpy_object", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_eq_with_self", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_array_type", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_check_dtype", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_hashable", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_str", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_eq", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_construct_from_string_own_name", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_construct_from_string_another_type_raises", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_construct_from_string_wrong_type_raises", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_get_common_dtype", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_infer_dtype[True]", "datashader/tests/test_datatypes.py::TestRaggedDtype::test_infer_dtype[False]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_iloc_series", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_iloc_frame", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_iloc_frame_single_block", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_loc_series", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_loc_frame", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_loc_iloc_frame_single_dtype", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_scalar", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_scalar_na", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_empty", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_mask", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_mask_raises", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_boolean_array_mask", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_boolean_na_treated_as_false", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_integer_array[list]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_integer_array[integer-array]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_integer_array[numpy-array]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_integer_with_missing_raises[list]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_integer_with_missing_raises[integer-array]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_getitem_slice", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_empty", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_negative", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_non_na_fill_value", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_pandas_style_negative_raises", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_out_of_bounds_raises[True]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_out_of_bounds_raises[False]", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_series", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_reindex", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_reindex_non_na_fill_value", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_loc_len1", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take_sequence", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_take", "datashader/tests/test_datatypes.py::TestRaggedGetitem::test_item", "datashader/tests/test_datatypes.py::TestRaggedGroupby::test_grouping_grouper", "datashader/tests/test_datatypes.py::TestRaggedGroupby::test_groupby_extension_no_sort", "datashader/tests/test_datatypes.py::TestRaggedGroupby::test_groupby_apply_identity", "datashader/tests/test_datatypes.py::TestRaggedGroupby::test_in_numeric_groupby", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_len", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_size", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_ndim", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_can_hold_na_valid", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_contains", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_memory_usage", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_is_extension_array_dtype", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_no_values_attribute", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_is_numeric_honored", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_isna_extension_array", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_array_interface", "datashader/tests/test_datatypes.py::TestRaggedInterface::test_tolist", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_hash_pandas_object", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_count", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_series_count", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argsort", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argsort_missing_array", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argsort_missing", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmin_argmax", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmin_argmax_empty_array[argmax]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmin_argmax_empty_array[argmin]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmin_argmax_all_na[argmax]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmin_argmax_all_na[argmin]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[idxmax-True-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[idxmin-True-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[argmax-True-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[argmin-True-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[idxmax-False-nan]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[idxmin-False-nan]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[argmax-False--1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argreduce_series[argmin-False--1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_argmax_argmin_no_skipna_notimplemented", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_nargsort[last-expected0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_nargsort[first-expected1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values[None-True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values[None-False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values[<lambda>-True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values[<lambda>-False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values_missing[None-True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values_missing[None-False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values_missing[<lambda>-True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_sort_values_missing[<lambda>-False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_factorize", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_factorize_equivalence", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_factorize_empty", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_fillna_length_mismatch", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_container_shift[0-indices1-True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_container_shift[0-indices1-False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_non_empty_array[0-indices2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_empty_array[-4]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_empty_array[-1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_empty_array[0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_empty_array[1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_empty_array[4]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_shift_zero_copies", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_not_hashable", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_hash_pandas_object_works[True]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_hash_pandas_object_works[False]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-True-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-True-1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-True-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-True-repeats3]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-False-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-False-1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-False-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[True-False-repeats3]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-True-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-True-1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-True-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-True-repeats3]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-False-0]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-False-1]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-False-2]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat[False-False-repeats3]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[True-2-kwargs0-ValueError-axis]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[True--1-kwargs1-ValueError-negative]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[True-repeats2-kwargs2-ValueError-shape]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[True-2-kwargs3-TypeError-'foo']", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[False-2-kwargs0-ValueError-axis]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[False--1-kwargs1-ValueError-negative]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[False-repeats2-kwargs2-ValueError-shape]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_repeat_raises[False-2-kwargs3-TypeError-'foo']", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_insert_invalid", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_insert_invalid_loc", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[True-array]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[True-Series]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[True-DataFrame]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[False-array]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[False-Series]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals[False-DataFrame]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_equals_same_data_different_object", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_unique[<lambda>-Series]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_unique[<lambda>-<lambda>]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_unique[unique-Series]", "datashader/tests/test_datatypes.py::TestRaggedMethods::test_unique[unique-<lambda>]", "datashader/tests/test_datatypes.py::TestRaggedPrinting::test_array_repr[small]", "datashader/tests/test_datatypes.py::TestRaggedPrinting::test_array_repr_unicode", "datashader/tests/test_datatypes.py::TestRaggedPrinting::test_dtype_name_in_info", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_isna", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_isna_returns_copy[isna]", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_isna_returns_copy[notna]", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_dropna_array", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_dropna_series", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_dropna_frame", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_fillna_scalar", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_fillna_no_op_returns_copy", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_fillna_fill_other", "datashader/tests/test_datatypes.py::TestRaggedMissing::test_use_inf_as_na_no_effect", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_concat_columns", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_concat_extension_arrays_copy_false", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_align", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_align_frame", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_align_series_frame", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_set_frame_expand_regular_with_extension", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_set_frame_expand_extension_with_regular", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_set_frame_overwrite_object", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_merge", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_merge_on_extension_array", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_merge_on_extension_array_duplicates", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[series-index0]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[series-index1]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[series-index2]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[series-index3]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[frame-index0]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[frame-index1]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[frame-index2]", "datashader/tests/test_datatypes.py::TestRaggedReshaping::test_unstack[frame-index3]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2023-02-20 14:19:54+00:00
bsd-3-clause
2,735
honeycombio__beeline-python-199
diff --git a/beeline/__init__.py b/beeline/__init__.py index e6dce92..ed238fc 100644 --- a/beeline/__init__.py +++ b/beeline/__init__.py @@ -9,7 +9,7 @@ from libhoney import Client from beeline.trace import SynchronousTracer from beeline.version import VERSION from beeline import internal -import beeline.propagation.honeycomb +import beeline.propagation.default import sys # pyflakes assert internal @@ -59,8 +59,8 @@ class Beeline(object): max_concurrent_batches=10, max_batch_size=100, send_frequency=0.25, block_on_send=False, block_on_response=False, transmission_impl=None, sampler_hook=None, presend_hook=None, - http_trace_parser_hook=beeline.propagation.honeycomb.http_trace_parser_hook, - http_trace_propagation_hook=beeline.propagation.honeycomb.http_trace_propagation_hook, + http_trace_parser_hook=beeline.propagation.default.http_trace_parser_hook, + http_trace_propagation_hook=beeline.propagation.default.http_trace_propagation_hook, debug=False): self.client = None diff --git a/beeline/propagation/default.py b/beeline/propagation/default.py new file mode 100644 index 0000000..633eecc --- /dev/null +++ b/beeline/propagation/default.py @@ -0,0 +1,21 @@ +from beeline.propagation import honeycomb, w3c + + +def http_trace_parser_hook(request): + """ + Retrieves the propagation context out of the request. Uses the honeycomb header, with W3C header as fallback. + """ + honeycomb_header_value = honeycomb.http_trace_parser_hook(request) + w3c_header_value = w3c.http_trace_parser_hook(request) + if honeycomb_header_value: + return honeycomb_header_value + else: + return w3c_header_value + + +def http_trace_propagation_hook(propagation_context): + """ + Given a propagation context, returns a dictionary of key value pairs that should be + added to outbound requests (usually HTTP headers). Uses the honeycomb format. + """ + return honeycomb.http_trace_propagation_hook(propagation_context) diff --git a/beeline/trace.py b/beeline/trace.py index 7f5561e..06a5bd5 100644 --- a/beeline/trace.py +++ b/beeline/trace.py @@ -18,6 +18,7 @@ from contextlib import contextmanager from beeline.internal import log, stringify_exception import beeline.propagation +import beeline.propagation.default import beeline.propagation.honeycomb MAX_INT32 = math.pow(2, 32) - 1 @@ -49,8 +50,8 @@ class Tracer(object): self.presend_hook = None self.sampler_hook = None - self.http_trace_parser_hook = beeline.propagation.honeycomb.http_trace_parser_hook - self.http_trace_propagation_hook = beeline.propagation.honeycomb.http_trace_propagation_hook + self.http_trace_parser_hook = beeline.propagation.default.http_trace_parser_hook + self.http_trace_propagation_hook = beeline.propagation.default.http_trace_propagation_hook @contextmanager def __call__(self, name, trace_id=None, parent_id=None):
honeycombio/beeline-python
ef7ed2aab06339750322433f22567a7b6b69cdb5
diff --git a/beeline/test_trace.py b/beeline/test_trace.py index 43beece..5033618 100644 --- a/beeline/test_trace.py +++ b/beeline/test_trace.py @@ -623,7 +623,7 @@ class TestSpan(unittest.TestCase): class TestPropagationHooks(unittest.TestCase): - def test_propagate_and_start_trace(self): + def test_propagate_and_start_trace_uses_honeycomb_header(self): # FIXME: Test basics, including error handling and custom hooks # implicitly tests finish_span @@ -653,6 +653,61 @@ class TestPropagationHooks(unittest.TestCase): # ensure that there is no current trace self.assertIsNone(tracer._trace) + def test_propagate_and_start_trace_uses_w3c_header_as_fallback(self): + # implicitly tests finish_span + m_client = Mock() + # these values are used before sending + m_client.new_event.return_value.start_time = datetime.datetime.now() + m_client.new_event.return_value.sample_rate = 1 + tracer = SynchronousTracer(m_client) + + header_value = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00' + req = DictRequest({ + 'traceparent': header_value, + }) + + span = tracer.propagate_and_start_trace( + context={'big': 'important_stuff'}, request=req) + self.assertEqual(tracer._trace.stack[0], span) + self.assertEqual(span.trace_id, "0af7651916cd43dd8448eb211c80319c") + self.assertEqual(span.parent_id, "b7ad6b7169203331") + + tracer.finish_trace(span) + + # ensure the event is sent + span.event.send_presampled.assert_called_once_with() + # ensure that there is no current trace + self.assertIsNone(tracer._trace) + + def test_propagate_and_start_trace_uses_honeycomb_header_when_w3c_also_present(self): + # implicitly tests finish_span + m_client = Mock() + # these values are used before sending + m_client.new_event.return_value.start_time = datetime.datetime.now() + m_client.new_event.return_value.sample_rate = 1 + tracer = SynchronousTracer(m_client) + + w3c_value = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00' + honeycomb_value = '1;dataset=flibble,trace_id=bloop,parent_id=scoop,context=e30K' + req = DictRequest({ + 'traceparent': w3c_value, + 'x-honeycomb-trace': honeycomb_value + }) + + span = tracer.propagate_and_start_trace( + context={'big': 'important_stuff'}, request=req) + self.assertEqual(tracer._trace.stack[0], span) + self.assertEqual(span.trace_id, "bloop") + self.assertEqual(span.parent_id, "scoop") + + tracer.finish_trace(span) + self.assertEqual(span.event.dataset, 'flibble') + + # ensure the event is sent + span.event.send_presampled.assert_called_once_with() + # ensure that there is no current trace + self.assertIsNone(tracer._trace) + def test_error_handling(self): class TestException(Exception): pass
Enable Beeline to simultaneously accept w3c and honeycomb propagation headers <!--- Thank you for contributing an idea to this project! Please see our [OSS process document](https://github.com/honeycombio/home/blob/main/honeycomb-oss-lifecycle-and-practices.md#) to get an idea of how we operate. ---> **Is your feature request related to a problem? Please describe.** Currently, it's not possible to incrementally move a microservices architecture from the honeycomb propagation headers format to the w3c propagation headers format. This makes it difficult if not impossible for beeline customers with a large enough deployment to move towards interoperating with OpenTelemetry. **Describe the solution you'd like** Allow the beeline to simultaneously accept both w3c and honeycomb propagation headers, whichever is found on the incoming request. The outgoing propagation header format can still be static and set by configuration. **Describe alternatives you've considered** **Additional context**
0.0
ef7ed2aab06339750322433f22567a7b6b69cdb5
[ "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_w3c_header_as_fallback" ]
[ "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_empty_context", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_dataset_included", "beeline/test_trace.py::TestSynchronousTracer::test_custom_dataset_propagates_to_event", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_adds_trace_fields", "beeline/test_trace.py::TestSynchronousTracer::test_start_span_returns_none_if_no_trace", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_trace_if_trace_id_supplied", "beeline/test_trace.py::TestSynchronousTracer::test_start_trace", "beeline/test_trace.py::TestSynchronousTracer::test_finish_trace", "beeline/test_trace.py::TestSynchronousTracer::test_add_rollup_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_start_trace_with_trace_id_set", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_exception", "beeline/test_trace.py::TestSynchronousTracer::test_get_active_span", "beeline/test_trace.py::TestSynchronousTracer::test_add_trace_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_does_not_crash_if_span_is_none", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_sampler", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_no_hooks", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_span_if_trace_active", "beeline/test_trace.py::TestSynchronousTracer::test_start_span", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_presend_hook", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_passes_parent_id_if_supplied", "beeline/test_trace.py::TestSynchronousTracer::test_trace_with_custom_dataset", "beeline/test_trace.py::TestTraceSampling::test_deterministic", "beeline/test_trace.py::TestTraceSampling::test_probability", "beeline/test_trace.py::TestTraceSampling::test_deterministic_interop", "beeline/test_trace.py::TestSpan::test_span_context", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header", "beeline/test_trace.py::TestPropagationHooks::test_error_handling", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header_when_w3c_also_present", "beeline/test_trace.py::TestIDGeneration::test_span_id", "beeline/test_trace.py::TestIDGeneration::test_trace_id" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-12-22 20:16:47+00:00
apache-2.0
2,736
honeycombio__beeline-python-213
diff --git a/beeline/__init__.py b/beeline/__init__.py index ed238fc..edabdee 100644 --- a/beeline/__init__.py +++ b/beeline/__init__.py @@ -10,6 +10,7 @@ from beeline.trace import SynchronousTracer from beeline.version import VERSION from beeline import internal import beeline.propagation.default +import beeline.propagation import sys # pyflakes assert internal @@ -74,15 +75,68 @@ class Beeline(object): if debug: self._init_logger() + def IsClassicKey(writekey): + return len(writekey) == 32 + # allow setting some values from the environment if not writekey: writekey = os.environ.get('HONEYCOMB_WRITEKEY', '') + # also check API_KEY just in case + if not writekey: + writekey = os.environ.get('HONEYCOMB_API_KEY', '') + if not writekey: + logging.error( + 'writekey not set! set the writekey if you want to send data to honeycomb' + ) + + if IsClassicKey(writekey): + if not dataset: + dataset = os.environ.get('HONEYCOMB_DATASET', '') + if not dataset: + logging.error( + 'dataset not set! set a value for dataset if you want to send data to honeycomb' + ) + else: + if dataset: + logging.error( + 'dataset will be ignored in favor of service name' + ) - if not dataset: - dataset = os.environ.get('HONEYCOMB_DATASET', '') - + default_service_name = "unknown_service" + process_name = os.environ.get('PROCESS_EXECUTABLE_NAME', '') if not service_name: - service_name = os.environ.get('HONEYCOMB_SERVICE', dataset) + service_name = os.environ.get('HONEYCOMB_SERVICE') + # also check SERVICE_NAME just in case + if not service_name: + service_name = os.environ.get('SERVICE_NAME', '') + # no service name, set default + if not service_name: + service_name = default_service_name + if process_name: + service_name += ":" + process_name + else: + service_name += ":python" + logging.error( + 'service name not set! service name will be ' + service_name + ) + if not IsClassicKey(writekey): + logging.error( + 'data will be sent to unknown_service' + ) + + if not IsClassicKey(writekey): + # set dataset based on service name + dataset = service_name + if dataset.strip() != dataset: + # whitespace detected. trim whitespace, warn on diff + logging.error( + 'service name has unexpected spaces' + ) + dataset = service_name.strip() + + # set default, truncate to unknown_service if needed + if dataset == "" or dataset.startswith("unknown_service"): + dataset = "unknown_service" self.client = Client( writekey=writekey, dataset=dataset, sample_rate=sample_rate, @@ -94,16 +148,16 @@ class Beeline(object): debug=debug, ) + if IsClassicKey(writekey): + beeline.propagation.propagate_dataset = True + else: + beeline.propagation.propagate_dataset = False + self.log('initialized honeycomb client: writekey=%s dataset=%s service_name=%s', writekey, dataset, service_name) - if not writekey: - self.log( - 'writekey not set! set the writekey if you want to send data to honeycomb') - if not dataset: - self.log( - 'dataset not set! set a value for dataset if you want to send data to honeycomb') self.client.add_field('service_name', service_name) + self.client.add_field('service.name', service_name) self.client.add_field('meta.beeline_version', VERSION) self.client.add_field('meta.local_hostname', socket.gethostname()) diff --git a/beeline/propagation/__init__.py b/beeline/propagation/__init__.py index 7b9c1d9..0e3a7ca 100644 --- a/beeline/propagation/__init__.py +++ b/beeline/propagation/__init__.py @@ -3,6 +3,10 @@ from abc import ABCMeta, abstractmethod import beeline +def propagate_dataset(): + return bool + + class PropagationContext(object): ''' PropagationContext represents information that can either be read from, or diff --git a/beeline/propagation/honeycomb.py b/beeline/propagation/honeycomb.py index 6957a0a..04db12f 100644 --- a/beeline/propagation/honeycomb.py +++ b/beeline/propagation/honeycomb.py @@ -51,7 +51,7 @@ def marshal_propagation_context(propagation_context): "parent_id={}".format(propagation_context.parent_id), "context={}".format(trace_fields)] - if propagation_context.dataset: + if beeline.propagation.propagate_dataset and propagation_context.dataset: components.insert(0, "dataset={}".format(quote(propagation_context.dataset))) trace_header = "{};{}".format(version, ",".join(components)) @@ -94,7 +94,7 @@ def unmarshal_propagation_context_with_dataset(trace_header): parent_id = v elif k == 'context': context = json.loads(base64.b64decode(v.encode()).decode()) - elif k == 'dataset': + elif k == 'dataset' and beeline.propagation.propagate_dataset: dataset = unquote(v) # context should be a dict diff --git a/examples/hello-world/README.md b/examples/hello-world/README.md new file mode 100644 index 0000000..95572b6 --- /dev/null +++ b/examples/hello-world/README.md @@ -0,0 +1,9 @@ +# hello world example + +## Setup and Run + +1. Set environment variable for `HONEYCOMB_API_KEY` +1. In top-level directory of repo, run `poetry build` to create a wheel package in the `dist` directory +1. In hello-world directory, ensure version of beeline in `pyproject.toml` matches the wheel package +1. In hello-world directory, run `poetry install` +1. In hello-world directory, run `poetry run python3 app.py` diff --git a/examples/hello-world/app.py b/examples/hello-world/app.py new file mode 100644 index 0000000..09f8351 --- /dev/null +++ b/examples/hello-world/app.py @@ -0,0 +1,21 @@ +import beeline +import os + +beeline.init( + # Get this via https://ui.honeycomb.io/account after signing up for Honeycomb + writekey=os.environ.get('HONEYCOMB_API_KEY'), + api_host=os.environ.get('HONEYCOMB_API_ENDPOINT', 'http://api.honeycomb.io:443'), + # The name of your app is a good choice to start with + # dataset='my-python-beeline-app', # only needed for classic + service_name=os.environ.get('SERVICE_NAME', 'my-python-app'), + debug=True, # enable to see telemetry in console +) + [email protected](name='hello_world') +def hello_world(): + print('hello world') + beeline.add_context_field('message', 'hello world') + +hello_world() + +beeline.close() \ No newline at end of file diff --git a/examples/hello-world/pyproject.toml b/examples/hello-world/pyproject.toml new file mode 100644 index 0000000..7c7ef9f --- /dev/null +++ b/examples/hello-world/pyproject.toml @@ -0,0 +1,14 @@ +[tool.poetry] +name = "hello-world" +version = "0.1.0" +description = "print hello world" +authors = ["honeycombio"] + +[tool.poetry.dependencies] +python = "^3.9" +honeycomb-beeline = {path = "../../dist/honeycomb_beeline-3.42.99-py3-none-any.whl", develop = false} +# honeycomb-beeline = "^3.2.0" + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api"
honeycombio/beeline-python
0e9aad4db57a9194a5a1909e42c027938be06568
diff --git a/beeline/propagation/test_honeycomb.py b/beeline/propagation/test_honeycomb.py index 23f321a..d5ddd43 100644 --- a/beeline/propagation/test_honeycomb.py +++ b/beeline/propagation/test_honeycomb.py @@ -1,4 +1,5 @@ import unittest +import beeline.propagation from beeline.propagation import DictRequest, PropagationContext import beeline.propagation.honeycomb as hc @@ -21,6 +22,7 @@ class TestMarshalUnmarshal(unittest.TestCase): def test_roundtrip_with_dataset(self): '''Verify that we can successfully roundtrip (marshal and unmarshal)''' + beeline.propagation.propagate_dataset = True dataset = "blorp blorp" trace_id = "bloop" parent_id = "scoop" @@ -34,6 +36,22 @@ class TestMarshalUnmarshal(unittest.TestCase): self.assertEqual(parent_id, new_parent_id) self.assertEqual(trace_fields, new_trace_fields) + def test_roundtrip_with_dataset_propagation_disabled(self): + '''Verify that we can successfully roundtrip (marshal and unmarshal) without dataset propagation''' + beeline.propagation.propagate_dataset = False + dataset = "blorp blorp" + trace_id = "bloop" + parent_id = "scoop" + trace_fields = {"key": "value"} + pc = PropagationContext(trace_id, parent_id, trace_fields, dataset) + header = hc.marshal_propagation_context(pc) + new_trace_id, new_parent_id, new_trace_fields, new_dataset = hc.unmarshal_propagation_context_with_dataset( + header) + self.assertIsNone(new_dataset) + self.assertEqual(trace_id, new_trace_id) + self.assertEqual(parent_id, new_parent_id) + self.assertEqual(trace_fields, new_trace_fields) + class TestHoneycombHTTPTraceParserHook(unittest.TestCase): def test_has_header(self): @@ -55,6 +73,7 @@ class TestHoneycombHTTPTraceParserHook(unittest.TestCase): class TestHoneycombHTTPTracePropagationHook(unittest.TestCase): def test_generates_correct_header(self): + beeline.propagation.propagate_dataset = True dataset = "blorp blorp" trace_id = "bloop" parent_id = "scoop" @@ -65,3 +84,16 @@ class TestHoneycombHTTPTracePropagationHook(unittest.TestCase): self.assertIn('X-Honeycomb-Trace', headers) self.assertEqual(headers['X-Honeycomb-Trace'], "1;dataset=blorp%20blorp,trace_id=bloop,parent_id=scoop,context=eyJrZXkiOiAidmFsdWUifQ==") + + def test_generates_correct_header_with_dataset_propagation_disabled(self): + beeline.propagation.propagate_dataset = False + dataset = "blorp blorp" + trace_id = "bloop" + parent_id = "scoop" + trace_fields = {"key": "value"} + pc = PropagationContext( + trace_id, parent_id, trace_fields, dataset) + headers = hc.http_trace_propagation_hook(pc) + self.assertIn('X-Honeycomb-Trace', headers) + self.assertEqual(headers['X-Honeycomb-Trace'], + "1;trace_id=bloop,parent_id=scoop,context=eyJrZXkiOiAidmFsdWUifQ==") diff --git a/beeline/test_trace.py b/beeline/test_trace.py index 5033618..84ef4d1 100644 --- a/beeline/test_trace.py +++ b/beeline/test_trace.py @@ -7,6 +7,7 @@ import unittest import re import os import binascii +import beeline.propagation from libhoney import Event @@ -624,6 +625,7 @@ class TestSpan(unittest.TestCase): class TestPropagationHooks(unittest.TestCase): def test_propagate_and_start_trace_uses_honeycomb_header(self): + beeline.propagation.propagate_dataset = True # FIXME: Test basics, including error handling and custom hooks # implicitly tests finish_span @@ -653,6 +655,40 @@ class TestPropagationHooks(unittest.TestCase): # ensure that there is no current trace self.assertIsNone(tracer._trace) + def test_propagate_and_start_trace_uses_honeycomb_header_with_dataset_propagation_disabled(self): + beeline.propagation.propagate_dataset = False + # FIXME: Test basics, including error handling and custom hooks + + # implicitly tests finish_span + m_client = Mock() + # these values are used before sending + m_client.new_event.return_value.start_time = datetime.datetime.now() + m_client.new_event.return_value.sample_rate = 1 + tracer = SynchronousTracer(m_client) + + header_value = '1;dataset=flibble,trace_id=bloop,parent_id=scoop,context=e30K' + req = DictRequest({ + # case shouldn't matter + 'X-HoNEyComb-TrACE': header_value, + }) + + span = tracer.propagate_and_start_trace( + context={'big': 'important_stuff'}, request=req) + self.assertEqual(tracer._trace.stack[0], span) + self.assertEqual(span.trace_id, "bloop") + self.assertEqual(span.parent_id, "scoop") + + tracer.finish_trace(span) + + # testing the absence of dataset + self.assertNotEqual(getattr(span.event, 'dataset'), "flibble") + self.assertNotIsInstance(span.event.dataset, str) + + # ensure the event is sent + span.event.send_presampled.assert_called_once_with() + # ensure that there is no current trace + self.assertIsNone(tracer._trace) + def test_propagate_and_start_trace_uses_w3c_header_as_fallback(self): # implicitly tests finish_span m_client = Mock()
update for e&s **Is your feature request related to a problem? Please describe.** Environments & Services are coming to Honeycomb. The beeline should be updated to support sending data to environments while maintaining backward compatibility. To achieve this, we will set dataset from service name, and provide appropriate warnings depending on environment vs. non-environment teams. **Describe the solution you'd like** Tracing scenario for environment-aware teams: * Dataset should no longer propagate across services for new environment key. * `ServiceName` "required"†. If unset, will warn and set `service_name` AND `service.name` to `unknown_service:<process>` or `unknown_service:language`. Service name is used to populate dataset name; if `unknown_service.*` then truncate to`unknown_service` for dataset name. `service.name` field will be added to the already added `service_name` for closer consistency with OTel. * `WriteKey` required. If unset, will warn. * `Dataset` **ignored**. If unset, no warning (because no longer used). If set, will warn to clarify that it will be ignored in favor of service name. Tracing scenario for legacy (non-environment-aware) teams: * `ServiceName` "required"†. If unset, will warn. * `WriteKey` required. If unset, will warn. * `Dataset` required. If unset, will warn and default to `beeline-<language>`. † While not technically required, service name is highly encouraged to avoid `unknown_service` and to instead properly describe the data being sent to Honeycomb (and the data being viewed in Honeycomb UI). This will be addressed in a separate issue/PR: Set [spanKind value based on OTel spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#spankind) for consistency across beelines and OTel. ### Notes from decision around defaulting when no service name is provided: *Given* a beeline configured with a v2 api key and without a service name *When* it sends HNY events *Then* it should use `unknown_service` as the dataset *And* it should use `unknown_service:process-name` as service_name When given a legacy key, the behavior remains the same as today. [Notes on trimming whitespace](https://honeycomb.quip.com/qdrvA6a9AHEI/notes-trimming-whitespace-ingest)
0.0
0e9aad4db57a9194a5a1909e42c027938be06568
[ "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header_with_dataset_propagation_disabled", "beeline/propagation/test_honeycomb.py::TestHoneycombHTTPTracePropagationHook::test_generates_correct_header_with_dataset_propagation_disabled", "beeline/propagation/test_honeycomb.py::TestMarshalUnmarshal::test_roundtrip_with_dataset_propagation_disabled" ]
[ "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_dataset_included", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_empty_context", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context", "beeline/test_trace.py::TestTraceSampling::test_probability", "beeline/test_trace.py::TestTraceSampling::test_deterministic", "beeline/test_trace.py::TestTraceSampling::test_deterministic_interop", "beeline/test_trace.py::TestSynchronousTracer::test_add_trace_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_trace_if_trace_id_supplied", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_span_if_trace_active", "beeline/test_trace.py::TestSynchronousTracer::test_get_active_span", "beeline/test_trace.py::TestSynchronousTracer::test_custom_dataset_propagates_to_event", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_adds_trace_fields", "beeline/test_trace.py::TestSynchronousTracer::test_add_rollup_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_presend_hook", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_sampler", "beeline/test_trace.py::TestSynchronousTracer::test_start_span_returns_none_if_no_trace", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_does_not_crash_if_span_is_none", "beeline/test_trace.py::TestSynchronousTracer::test_trace_with_custom_dataset", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_exception", "beeline/test_trace.py::TestSynchronousTracer::test_start_span", "beeline/test_trace.py::TestSynchronousTracer::test_start_trace", "beeline/test_trace.py::TestSynchronousTracer::test_finish_trace", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_passes_parent_id_if_supplied", "beeline/test_trace.py::TestSynchronousTracer::test_start_trace_with_trace_id_set", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_no_hooks", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header_when_w3c_also_present", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_w3c_header_as_fallback", "beeline/test_trace.py::TestPropagationHooks::test_error_handling", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header", "beeline/test_trace.py::TestSpan::test_span_context", "beeline/test_trace.py::TestIDGeneration::test_span_id", "beeline/test_trace.py::TestIDGeneration::test_trace_id", "beeline/propagation/test_honeycomb.py::TestHoneycombHTTPTracePropagationHook::test_generates_correct_header", "beeline/propagation/test_honeycomb.py::TestMarshalUnmarshal::test_roundtrip", "beeline/propagation/test_honeycomb.py::TestMarshalUnmarshal::test_roundtrip_with_dataset", "beeline/propagation/test_honeycomb.py::TestHoneycombHTTPTraceParserHook::test_no_header", "beeline/propagation/test_honeycomb.py::TestHoneycombHTTPTraceParserHook::test_has_header" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-03-07 23:29:47+00:00
apache-2.0
2,737
honeycombio__beeline-python-219
diff --git a/CHANGELOG.md b/CHANGELOG.md index a03dbd3..47a1880 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ ### Enhancements +**NOTE** If you are using the [FileTransmission](https://github.com/honeycombio/libhoney-py/blob/main/libhoney/transmission.py#L448) method and setting a false API key - and still working in Classic mode - you must update the key to be 32 characters in length to keep the same behavior. + - feat: Add Environment & Services support (#213) | [@JamieDanielson](https://github.com/JamieDanielson) ## 3.2.0 2022-02-10 diff --git a/README.md b/README.md index 87a6326..af05e2a 100644 --- a/README.md +++ b/README.md @@ -14,17 +14,15 @@ Currently, supports Django (>2), Flask, Bottle, and Tornado. Compatible with Python 3. -## Get in touch +## Updating to 3.3.0 -Please reach out to [[email protected]](mailto:[email protected]) or ping -us with the chat bubble on [our website](https://www.honeycomb.io) for any -assistance. We also welcome [bug reports](https://github.com/honeycombio/beeline-python/issues). +Version 3.3.0 added support for Environment & Services, which changes sending behavior based on API Key. + +If you are using the [FileTransmission](https://github.com/honeycombio/libhoney-py/blob/main/libhoney/transmission.py#L448) method and setting a false API key - and still working in Classic mode - you must update the key to be 32 characters in length to keep the same behavior. ## Contributions -Features, bug fixes and other changes to `beeline-python` are gladly accepted. Please -open issues or a pull request with your change. Remember to add your name to the -CONTRIBUTORS file! +Features, bug fixes and other changes to `beeline-python` are gladly accepted. If you add a new test module, be sure and update `beeline.test_suite` to pick up the new tests. diff --git a/beeline/trace.py b/beeline/trace.py index 7606102..2c546e9 100644 --- a/beeline/trace.py +++ b/beeline/trace.py @@ -101,9 +101,9 @@ class Tracer(object): self._trace = Trace(generate_trace_id(), dataset) # start the root span - return self.start_span(context=context, parent_id=parent_span_id) + return self.start_span(context=context, parent_id=parent_span_id, is_root_span=True) - def start_span(self, context=None, parent_id=None): + def start_span(self, context=None, parent_id=None, is_root_span=False): if not self._trace: log('start_span called but no trace is active') return None @@ -117,11 +117,18 @@ class Tracer(object): if context: ev.add(data=context) - ev.add(data={ + fields = { 'trace.trace_id': self._trace.id, 'trace.parent_id': parent_span_id, 'trace.span_id': span_id, - }) + } + if is_root_span: + spanType = "root" + if parent_span_id: + spanType = "subroot" + fields['meta.span_type'] = spanType + ev.add(data=fields) + is_root = len(self._trace.stack) == 0 span = Span(trace_id=self._trace.id, parent_id=parent_span_id, id=span_id, event=ev, is_root=is_root)
honeycombio/beeline-python
40156dfc16badce91695caa74d38235c30b59e3d
diff --git a/beeline/test_trace.py b/beeline/test_trace.py index 84ef4d1..5963e44 100644 --- a/beeline/test_trace.py +++ b/beeline/test_trace.py @@ -178,7 +178,7 @@ class TestSynchronousTracer(unittest.TestCase): pass tracer.start_span.assert_called_once_with( - context={'name': 'foo'}, parent_id='zyxw') + context={'name': 'foo'}, parent_id='zyxw', is_root_span=True) tracer.finish_span.assert_called_once_with(mock_span) def test_trace_context_manager_starts_trace_if_trace_id_supplied(self): @@ -210,6 +210,7 @@ class TestSynchronousTracer(unittest.TestCase): 'trace.trace_id': span.trace_id, 'trace.parent_id': span.parent_id, 'trace.span_id': span.id, + 'meta.span_type': "root", }), ]) self.assertEqual(tracer._trace.stack[0], span) @@ -284,6 +285,7 @@ class TestSynchronousTracer(unittest.TestCase): 'trace.trace_id': span.trace_id, 'trace.parent_id': span.parent_id, 'trace.span_id': span.id, + 'meta.span_type': 'subroot' }), ]) @@ -532,7 +534,7 @@ class TestSynchronousTracer(unittest.TestCase): pass tracer.start_span.assert_called_once_with( - context={'name': 'foo'}, parent_id=None) + context={'name': 'foo'}, parent_id=None, is_root_span=True) def test_trace_with_custom_dataset(self): dataset = 'flibble'
Categorize span types on send <!--- Thank you for contributing an idea to this project! Please see our [OSS process document](https://github.com/honeycombio/home/blob/main/honeycomb-oss-lifecycle-and-practices.md#) to get an idea of how we operate. ---> **Is your feature request related to a problem? Please describe.** **Describe the solution you'd like** **Describe alternatives you've considered** **Additional context**
0.0
40156dfc16badce91695caa74d38235c30b59e3d
[ "beeline/test_trace.py::TestSynchronousTracer::test_start_trace", "beeline/test_trace.py::TestSynchronousTracer::test_start_trace_with_trace_id_set", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_does_not_crash_if_span_is_none", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_passes_parent_id_if_supplied" ]
[ "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_no_hooks", "beeline/test_trace.py::TestSynchronousTracer::test_finish_trace", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_sampler", "beeline/test_trace.py::TestSynchronousTracer::test_add_trace_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_add_rollup_field_propagates", "beeline/test_trace.py::TestSynchronousTracer::test_get_active_span", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_trace_if_trace_id_supplied", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_adds_trace_fields", "beeline/test_trace.py::TestSynchronousTracer::test_trace_with_custom_dataset", "beeline/test_trace.py::TestSynchronousTracer::test_start_span_returns_none_if_no_trace", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_starts_span_if_trace_active", "beeline/test_trace.py::TestSynchronousTracer::test_custom_dataset_propagates_to_event", "beeline/test_trace.py::TestSynchronousTracer::test_trace_context_manager_exception", "beeline/test_trace.py::TestSynchronousTracer::test_run_hooks_and_send_presend_hook", "beeline/test_trace.py::TestSynchronousTracer::test_start_span", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_w3c_header_as_fallback", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header_when_w3c_also_present", "beeline/test_trace.py::TestPropagationHooks::test_error_handling", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header_with_dataset_propagation_disabled", "beeline/test_trace.py::TestPropagationHooks::test_propagate_and_start_trace_uses_honeycomb_header", "beeline/test_trace.py::TestTraceSampling::test_deterministic_interop", "beeline/test_trace.py::TestTraceSampling::test_deterministic", "beeline/test_trace.py::TestTraceSampling::test_probability", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_dataset_included", "beeline/test_trace.py::TestTraceContext::test_marshal_trace_context_empty_context", "beeline/test_trace.py::TestIDGeneration::test_trace_id", "beeline/test_trace.py::TestIDGeneration::test_span_id", "beeline/test_trace.py::TestSpan::test_span_context" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-26 13:27:04+00:00
apache-2.0
2,738
horejsek__python-fastjsonschema-116
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index a5b132b..394f263 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -26,7 +26,7 @@ class CodeGeneratorDraft04(CodeGenerator): # vs. 9 ms with a regex! Other modules are also ineffective or not available in standard # library. Some regexps are not 100% precise but good enough, fast and without dependencies. FORMAT_REGEXS = { - 'date-time': r'^\d{4}-[01]\d-[0-3]\d(t|T)[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|z|Z)\Z', + 'date-time': r'^\d{4}-[01]\d-[0-3]\d(t|T)[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|[+-][0-2]\d[0-5]\d|z|Z)\Z', 'email': r'^[^@]+@[^@]+\.[^@]+\Z', 'hostname': r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])\Z', 'ipv4': r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\Z',
horejsek/python-fastjsonschema
32476cfd4d97f92cae52d686eb471361503bf4ba
diff --git a/tests/test_format.py b/tests/test_format.py index f742344..c43abc5 100644 --- a/tests/test_format.py +++ b/tests/test_format.py @@ -14,6 +14,7 @@ exc = JsonSchemaValueException('data must be date-time', value='{data}', name='d ('2018-02-05T14:17:10.00Z\n', exc), ('2018-02-05T14:17:10.00Z', '2018-02-05T14:17:10.00Z'), ('2018-02-05T14:17:10Z', '2018-02-05T14:17:10Z'), + ('2020-09-09T01:01:01+0100', '2020-09-09T01:01:01+0100'), ]) def test_datetime(asserter, value, expected): asserter({'type': 'string', 'format': 'date-time'}, value, expected)
"date-time" not full supported e.g.: ```python >>> import fastjsonschema >>> fastjsonschema.validate({'type': 'string', 'format': 'date-time'},'2020-09-09T01:01:01+0100') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/jens/repos/python-fastjsonschema/fastjsonschema/__init__.py", line 113, in validate return compile(definition, handlers, formats, use_default)(data) File "<string>", line 8, in validate fastjsonschema.exceptions.JsonSchemaValueException: data must be date-time ``` Support was added with: https://github.com/horejsek/python-fastjsonschema/pull/7/ But a later refactor seems to remove this. And there is no test for it: https://github.com/horejsek/python-fastjsonschema/blob/32476cfd4d97f92cae52d686eb471361503bf4ba/tests/test_format.py#L9-L19
0.0
32476cfd4d97f92cae52d686eb471361503bf4ba
[ "tests/test_format.py::test_datetime[2020-09-09T01:01:01+0100-2020-09-09T01:01:01+0100]" ]
[ "tests/test_format.py::test_datetime[-expected0]", "tests/test_format.py::test_datetime[bla-expected1]", "tests/test_format.py::test_datetime[2018-02-05T14:17:10.00-expected2]", "tests/test_format.py::test_datetime[2018-02-05T14:17:10.00Z\\n-expected3]", "tests/test_format.py::test_datetime[2018-02-05T14:17:10.00Z-2018-02-05T14:17:10.00Z]", "tests/test_format.py::test_datetime[2018-02-05T14:17:10Z-2018-02-05T14:17:10Z]", "tests/test_format.py::test_hostname[-expected0]", "tests/test_format.py::test_hostname[LDhsjf878&d-expected1]", "tests/test_format.py::test_hostname[bla.bla--expected2]", "tests/test_format.py::test_hostname[example.example.com--expected3]", "tests/test_format.py::test_hostname[example.example.com\\n-expected4]", "tests/test_format.py::test_hostname[localhost-localhost]", "tests/test_format.py::test_hostname[example.com-example.com]", "tests/test_format.py::test_hostname[example.de-example.de]", "tests/test_format.py::test_hostname[example.fr-example.fr]", "tests/test_format.py::test_hostname[example.example.com-example.example.com]", "tests/test_format.py::test_custom_format[-expected0-^[ab]$]", "tests/test_format.py::test_custom_format[-expected1-<lambda>]", "tests/test_format.py::test_custom_format[a-a-^[ab]$]", "tests/test_format.py::test_custom_format[a-a-<lambda>]", "tests/test_format.py::test_custom_format[c-expected4-^[ab]$]", "tests/test_format.py::test_custom_format[c-expected5-<lambda>]", "tests/test_format.py::test_custom_format_override" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-03-01 15:09:31+00:00
bsd-3-clause
2,739
horejsek__python-fastjsonschema-126
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 1b1232d..620a830 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,3 +1,8 @@ +=== UNRELEASED + +* Fix nested oneOf and anyOf + + === 2.15.1 (2021-05-05) * Fix parsing date-time with +hhmm format diff --git a/fastjsonschema/__init__.py b/fastjsonschema/__init__.py index 6dd90f6..572e6c1 100644 --- a/fastjsonschema/__init__.py +++ b/fastjsonschema/__init__.py @@ -75,6 +75,7 @@ Note that there are some differences compared to JSON schema standard: API *** """ +from functools import partial, update_wrapper from .draft04 import CodeGeneratorDraft04 from .draft06 import CodeGeneratorDraft06 @@ -177,7 +178,10 @@ def compile(definition, handlers={}, formats={}, use_default=True): global_state = code_generator.global_state # Do not pass local state so it can recursively call itself. exec(code_generator.func_code, global_state) - return global_state[resolver.get_scope_name()] + func = global_state[resolver.get_scope_name()] + if formats: + return update_wrapper(partial(func, custom_formats=formats), func) + return func # pylint: disable=dangerous-default-value diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 394f263..8209efc 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -65,6 +65,7 @@ class CodeGeneratorDraft04(CodeGenerator): ('patternProperties', self.generate_pattern_properties), ('additionalProperties', self.generate_additional_properties), )) + self._any_or_one_of_count = 0 @property def global_state(self): @@ -145,16 +146,18 @@ class CodeGeneratorDraft04(CodeGenerator): Valid values for this definition are 3, 4, 5, 10, 11, ... but not 8 for example. """ - self.l('{variable}_any_of_count = 0') + self._any_or_one_of_count += 1 + count = self._any_or_one_of_count + self.l('{variable}_any_of_count{count} = 0', count=count) for definition_item in self._definition['anyOf']: # When we know it's passing (at least once), we do not need to do another expensive try-except. - with self.l('if not {variable}_any_of_count:', optimize=False): + with self.l('if not {variable}_any_of_count{count}:', count=count, optimize=False): with self.l('try:', optimize=False): self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) - self.l('{variable}_any_of_count += 1') + self.l('{variable}_any_of_count{count} += 1', count=count) self.l('except JsonSchemaValueException: pass') - with self.l('if not {variable}_any_of_count:', optimize=False): + with self.l('if not {variable}_any_of_count{count}:', count=count, optimize=False): self.exc('{name} must be valid by one of anyOf definition', rule='anyOf') def generate_one_of(self): @@ -173,16 +176,18 @@ class CodeGeneratorDraft04(CodeGenerator): Valid values for this definition are 3, 5, 6, ... but not 15 for example. """ - self.l('{variable}_one_of_count = 0') + self._any_or_one_of_count += 1 + count = self._any_or_one_of_count + self.l('{variable}_one_of_count{count} = 0', count=count) for definition_item in self._definition['oneOf']: # When we know it's failing (one of means exactly once), we do not need to do another expensive try-except. - with self.l('if {variable}_one_of_count < 2:', optimize=False): + with self.l('if {variable}_one_of_count{count} < 2:', count=count, optimize=False): with self.l('try:', optimize=False): self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) - self.l('{variable}_one_of_count += 1') + self.l('{variable}_one_of_count{count} += 1', count=count) self.l('except JsonSchemaValueException: pass') - with self.l('if {variable}_one_of_count != 1:'): + with self.l('if {variable}_one_of_count{count} != 1:', count=count): self.exc('{name} must be valid exactly by one of oneOf definition', rule='oneOf') def generate_not(self): diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index bedd7ed..71e9b58 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -32,6 +32,7 @@ class CodeGenerator: def __init__(self, definition, resolver=None): self._code = [] self._compile_regexps = {} + self._custom_formats = {} # Any extra library should be here to be imported only once. # Lines are imports to be printed in the file and objects @@ -136,7 +137,7 @@ class CodeGenerator: self._validation_functions_done.add(uri) self.l('') with self._resolver.resolving(uri) as definition: - with self.l('def {}(data):', name): + with self.l('def {}(data, custom_formats={{}}):', name): self.generate_func_code_block(definition, 'data', 'data', clear_variables=True) self.l('return data') @@ -190,7 +191,7 @@ class CodeGenerator: if uri not in self._validation_functions_done: self._needed_validation_functions[uri] = name # call validation function - self.l('{}({variable})', name) + self.l('{}({variable}, custom_formats)', name) # pylint: disable=invalid-name
horejsek/python-fastjsonschema
1e214911fe83dbaeea3d50dfb3a539118de8a442
diff --git a/tests/test_compile_to_code.py b/tests/test_compile_to_code.py index 509e044..84bc981 100644 --- a/tests/test_compile_to_code.py +++ b/tests/test_compile_to_code.py @@ -2,6 +2,7 @@ import os import pytest import shutil +from fastjsonschema import JsonSchemaValueException from fastjsonschema import compile_to_code, compile as compile_spec @pytest.yield_fixture(autouse=True) @@ -84,3 +85,40 @@ def test_compile_complex_one_of_all_of(): } ] }) + + +def test_compile_to_code_custom_format(): + formats = {'my-format': str.isidentifier} + code = compile_to_code({'type': 'string', 'format': 'my-format'}, formats=formats) + with open('temp/schema_3.py', 'w') as f: + f.write(code) + from temp.schema_3 import validate + assert validate("valid", formats) == "valid" + with pytest.raises(JsonSchemaValueException) as exc: + validate("not-valid", formats) + assert exc.value.message == "data must be my-format" + + +def test_compile_to_code_custom_format_with_refs(): + schema = { + 'type': 'object', + 'properties': { + 'a': {'$ref': '#/definitions/a'} + }, + 'definitions': { + 'a': { + '$id': '#/definitions/a', + 'type': 'array', + 'items': {'type': 'string', 'format': 'my-format'} + } + } + } + formats = {'my-format': str.isidentifier} + code = compile_to_code(schema, formats=formats) + with open('temp/schema_4.py', 'w') as f: + f.write(code) + from temp.schema_4 import validate + assert validate({"a": ["identifier"]}, formats) is not None + with pytest.raises(JsonSchemaValueException) as exc: + validate({"a": ["identifier", "not-valid"]}, formats) + assert exc.value.message == "data[1] must be my-format" \ No newline at end of file
Error in output of `compile_to_code` when using custom formats Hello and thank you very much for the very nice package. I notice that when compiling code to string, the generated file assumes a `custom_formats` global variable that is not defined anywhere, and therefore results in errors. In #126, I propose adding a second argument that should fix this scenario. This argument is automatically "curried"-away when the `compile` function is called, and just take effect when using `compile_to_code`, so there is no need for changes in API or docs.
0.0
1e214911fe83dbaeea3d50dfb3a539118de8a442
[ "tests/test_compile_to_code.py::test_compile_to_code_custom_format", "tests/test_compile_to_code.py::test_compile_to_code_custom_format_with_refs" ]
[ "tests/test_compile_to_code.py::test_compile_to_code", "tests/test_compile_to_code.py::test_compile_to_code_ipv6_regex", "tests/test_compile_to_code.py::test_compile_complex_one_of_all_of" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-10-22 10:32:25+00:00
bsd-3-clause
2,740
horejsek__python-fastjsonschema-140
diff --git a/fastjsonschema/exceptions.py b/fastjsonschema/exceptions.py index 63d9819..d2dddd6 100644 --- a/fastjsonschema/exceptions.py +++ b/fastjsonschema/exceptions.py @@ -16,8 +16,8 @@ class JsonSchemaValueException(JsonSchemaException): * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``), * invalid ``value`` (e.g. ``60``), - * ``name`` of a path in the data structure (e.g. ``data.propery[index]``), - * ``path`` as an array in the data structure (e.g. ``['data', 'propery', 'index']``), + * ``name`` of a path in the data structure (e.g. ``data.property[index]``), + * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``), * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``), * ``rule`` which the ``value`` is breaking (e.g. ``maximum``) * and ``rule_definition`` (e.g. ``42``). diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index 57b65a6..cebf302 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -136,7 +136,7 @@ class CodeGenerator: self._validation_functions_done.add(uri) self.l('') with self._resolver.resolving(uri) as definition: - with self.l('def {}(data, custom_formats={{}}):', name): + with self.l('def {}(data, custom_formats={{}}, name_prefix=None):', name): self.generate_func_code_block(definition, 'data', 'data', clear_variables=True) self.l('return data') @@ -190,7 +190,10 @@ class CodeGenerator: if uri not in self._validation_functions_done: self._needed_validation_functions[uri] = name # call validation function - self.l('{}({variable}, custom_formats)', name) + assert self._variable_name.startswith("data") + path = self._variable_name[4:] + name_arg = '(name_prefix or "data") + "{}"'.format(path) + self.l('{}({variable}, custom_formats, {name_arg})', name, name_arg=name_arg) # pylint: disable=invalid-name @@ -216,8 +219,12 @@ class CodeGenerator: spaces = ' ' * self.INDENT * self._indent name = self._variable_name - if name and '{' in name: - name = '"+"{}".format(**locals())+"'.format(self._variable_name) + if name: + # Add name_prefix to the name when it is being outputted. + assert name.startswith('data') + name = '" + (name_prefix or "data") + "' + name[4:] + if '{' in name: + name = name + '".format(**locals()) + "' context = dict( self._definition or {},
horejsek/python-fastjsonschema
d03f3835da4899bdeb597a9d3f30a709e7c3254f
diff --git a/tests/test_compile_to_code.py b/tests/test_compile_to_code.py index 84bc981..8e40db5 100644 --- a/tests/test_compile_to_code.py +++ b/tests/test_compile_to_code.py @@ -121,4 +121,4 @@ def test_compile_to_code_custom_format_with_refs(): assert validate({"a": ["identifier"]}, formats) is not None with pytest.raises(JsonSchemaValueException) as exc: validate({"a": ["identifier", "not-valid"]}, formats) - assert exc.value.message == "data[1] must be my-format" \ No newline at end of file + assert exc.value.message == "data.a[1] must be my-format" diff --git a/tests/test_object.py b/tests/test_object.py index d880dc4..19967a3 100644 --- a/tests/test_object.py +++ b/tests/test_object.py @@ -225,4 +225,24 @@ def test_dependencies(asserter, value, expected): "dependencies": { "foo": ["bar"], }, - }, value, expected) \ No newline at end of file + }, value, expected) + + [email protected]('value, expected', [ + ({"prop1": {"str": 1}}, JsonSchemaValueException('data.prop1.str must be string', value=1, name='data.prop1.str', definition={'type': 'string'}, rule='type')), +]) +def test_full_name_after_ref(asserter, value, expected): + asserter({ + "definitions": { + "SomeType": { + "type": "object", + "properties": { + "str": {"type": "string"}, + }, + }, + }, + "type": "object", + "properties": { + "prop1": {"$ref": "#/definitions/SomeType"}, + } + }, value, expected)
Keep the variable name and path through references > for me the most important feature is to keep track of the context/scope of where the validation process is at when the exception is thrown. so given: a schema: article.json ```{ "$schema": "http://json-schema.org/draft-07/schema#", "type" : "object", "additionalProperties": false, "properties": { "teaser" : { "$ref": "intro.json" }, "prolog" : { "$ref": "intro.json" } } } ``` when the error occurs during the prolog validation, the exception contains an attribute with value `article.prolog.....` about where it happened (like the jsonschema library does). _Originally posted by @isomogyi in https://github.com/horejsek/python-fastjsonschema/pull/61_
0.0
d03f3835da4899bdeb597a9d3f30a709e7c3254f
[ "tests/test_compile_to_code.py::test_compile_to_code_custom_format_with_refs", "tests/test_object.py::test_full_name_after_ref[value0-expected0]" ]
[ "tests/test_compile_to_code.py::test_compile_to_code", "tests/test_compile_to_code.py::test_compile_to_code_ipv6_regex", "tests/test_compile_to_code.py::test_compile_complex_one_of_all_of", "tests/test_compile_to_code.py::test_compile_to_code_custom_format", "tests/test_object.py::test_object[0-expected0]", "tests/test_object.py::test_object[None-expected1]", "tests/test_object.py::test_object[True-expected2]", "tests/test_object.py::test_object[False-expected3]", "tests/test_object.py::test_object[abc-expected4]", "tests/test_object.py::test_object[value5-expected5]", "tests/test_object.py::test_object[value6-expected6]", "tests/test_object.py::test_object[value7-expected7]", "tests/test_object.py::test_max_properties[value0-expected0]", "tests/test_object.py::test_max_properties[value1-expected1]", "tests/test_object.py::test_max_properties[value2-expected2]", "tests/test_object.py::test_min_properties[value0-expected0]", "tests/test_object.py::test_min_properties[value1-expected1]", "tests/test_object.py::test_min_properties[value2-expected2]", "tests/test_object.py::test_required[value0-expected0]", "tests/test_object.py::test_required[value1-expected1]", "tests/test_object.py::test_required[value2-expected2]", "tests/test_object.py::test_properties[value0-expected0]", "tests/test_object.py::test_properties[value1-expected1]", "tests/test_object.py::test_properties[value2-expected2]", "tests/test_object.py::test_properties[value3-expected3]", "tests/test_object.py::test_properties[value4-expected4]", "tests/test_object.py::test_invalid_properties", "tests/test_object.py::test_properties_with_additional_properties[value0-expected0]", "tests/test_object.py::test_properties_with_additional_properties[value1-expected1]", "tests/test_object.py::test_properties_with_additional_properties[value2-expected2]", "tests/test_object.py::test_properties_with_additional_properties[value3-expected3]", "tests/test_object.py::test_properties_with_additional_properties[value4-expected4]", "tests/test_object.py::test_properties_with_additional_properties[value5-expected5]", "tests/test_object.py::test_properties_without_additional_properties[value0-expected0]", "tests/test_object.py::test_properties_without_additional_properties[value1-expected1]", "tests/test_object.py::test_properties_without_additional_properties[value2-expected2]", "tests/test_object.py::test_properties_without_additional_properties[value3-expected3]", "tests/test_object.py::test_properties_without_additional_properties[value4-expected4]", "tests/test_object.py::test_properties_without_additional_properties[value5-expected5]", "tests/test_object.py::test_properties_without_additional_properties[value6-expected6]", "tests/test_object.py::test_pattern_properties[value0-expected0]", "tests/test_object.py::test_pattern_properties[value1-expected1]", "tests/test_object.py::test_pattern_properties[value2-expected2]", "tests/test_object.py::test_pattern_properties[value3-expected3]", "tests/test_object.py::test_pattern_properties[value4-expected4]", "tests/test_object.py::test_additional_properties[value0-expected0]", "tests/test_object.py::test_additional_properties[value1-expected1]", "tests/test_object.py::test_additional_properties[value2-expected2]", "tests/test_object.py::test_additional_properties[value3-expected3]", "tests/test_object.py::test_additional_properties[value4-expected4]", "tests/test_object.py::test_any_additional_properties[value0-expected0]", "tests/test_object.py::test_any_additional_properties[value1-expected1]", "tests/test_object.py::test_any_additional_properties[value2-expected2]", "tests/test_object.py::test_any_additional_properties[value3-expected3]", "tests/test_object.py::test_any_additional_properties[value4-expected4]", "tests/test_object.py::test_any_additional_properties[value5-expected5]", "tests/test_object.py::test_any_additional_properties[value6-expected6]", "tests/test_object.py::test_any_additional_properties[value7-expected7]", "tests/test_object.py::test_object_with_id_property[value0-expected0]", "tests/test_object.py::test_object_with_id_property[value1-expected1]", "tests/test_object.py::test_object_with_ref_property[value0-expected0]", "tests/test_object.py::test_object_with_ref_property[value1-expected1]", "tests/test_object.py::test_dependencies[value0-expected0]", "tests/test_object.py::test_dependencies[value1-expected1]", "tests/test_object.py::test_dependencies[value2-expected2]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-02-23 16:02:06+00:00
bsd-3-clause
2,741
horejsek__python-fastjsonschema-144
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 7dd097e..8c25863 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -413,19 +413,23 @@ class CodeGeneratorDraft04(CodeGenerator): self.exc('{name} must contain only specified items', rule='items') else: with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(items_definition)): - self.generate_func_code_block( + count = self.generate_func_code_block( self._definition['additionalItems'], '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), ) + if count == 0: + self.l('pass') else: if items_definition: with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'): - self.generate_func_code_block( + count = self.generate_func_code_block( items_definition, '{}_item'.format(self._variable), '{}[{{{}_x}}]'.format(self._variable_name, self._variable), ) + if count == 0: + self.l('pass') def generate_min_properties(self): self.create_variable_is_dict() diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index 5e08030..c5b57aa 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -143,6 +143,8 @@ class CodeGenerator: def generate_func_code_block(self, definition, variable, variable_name, clear_variables=False): """ Creates validation rules for current definition. + + Returns the number of validation rules generated as code. """ backup = self._definition, self._variable, self._variable_name self._definition, self._variable, self._variable_name = definition, variable, variable_name @@ -150,25 +152,31 @@ class CodeGenerator: backup_variables = self._variables self._variables = set() - self._generate_func_code_block(definition) + count = self._generate_func_code_block(definition) self._definition, self._variable, self._variable_name = backup if clear_variables: self._variables = backup_variables + return count + def _generate_func_code_block(self, definition): if not isinstance(definition, dict): raise JsonSchemaDefinitionException("definition must be an object") if '$ref' in definition: # needed because ref overrides any sibling keywords - self.generate_ref() + return self.generate_ref() else: - self.run_generate_functions(definition) + return self.run_generate_functions(definition) def run_generate_functions(self, definition): + """Returns the number of generate functions that were executed.""" + count = 0 for key, func in self._json_keywords_to_function.items(): if key in definition: func() + count += 1 + return count def generate_ref(self): """
horejsek/python-fastjsonschema
d63d682e003aa89a5cf6fc0b8cf6f477c34931ba
diff --git a/tests/test_array.py b/tests/test_array.py index 99c9254..3da479f 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -180,3 +180,22 @@ def test_mixed_arrays(asserter, value, expected): }, }, value, expected) + +def test_issue_114(asserter): + """Prevent the faulty scheme to generate an empty for-loop.""" + schema = { + "type": "object", + "properties": { + "a": { + "type": "array", + "items": { + "b": { + "type": "string" + } + } + } + } + } + value = {"a": []} + expected = value + asserter(schema, value, expected)
Missleading IndentationError with a faulty schema The following (faulty) schema ``` { "type": "object", "properties": { "a": { "type": "array", "items": { "b": { "type": "string" } } } } } ``` raises a missleading `IndentationError: expected an indented block`. This is especially confusing as jsonschema does not raise an error.
0.0
d63d682e003aa89a5cf6fc0b8cf6f477c34931ba
[ "tests/test_array.py::test_issue_114" ]
[ "tests/test_array.py::test_array[0-expected0]", "tests/test_array.py::test_array[None-expected1]", "tests/test_array.py::test_array[True-expected2]", "tests/test_array.py::test_array[False-expected3]", "tests/test_array.py::test_array[abc-expected4]", "tests/test_array.py::test_array[value5-expected5]", "tests/test_array.py::test_array[value6-expected6]", "tests/test_array.py::test_array[value7-expected7]", "tests/test_array.py::test_max_items[value0-expected0]", "tests/test_array.py::test_max_items[value1-expected1]", "tests/test_array.py::test_max_items[value2-expected2]", "tests/test_array.py::test_max_items[value3-expected3]", "tests/test_array.py::test_min_items[value0-expected0]", "tests/test_array.py::test_min_items[value1-expected1]", "tests/test_array.py::test_min_items[value2-expected2]", "tests/test_array.py::test_min_items[value3-expected3]", "tests/test_array.py::test_unique_items[value0-expected0]", "tests/test_array.py::test_unique_items[value1-expected1]", "tests/test_array.py::test_unique_items[value2-expected2]", "tests/test_array.py::test_unique_items[value3-expected3]", "tests/test_array.py::test_unique_items[value4-expected4]", "tests/test_array.py::test_unique_items[value5-expected5]", "tests/test_array.py::test_unique_items[value6-expected6]", "tests/test_array.py::test_unique_items[value7-expected7]", "tests/test_array.py::test_unique_items[value8-expected8]", "tests/test_array.py::test_unique_items[value9-expected9]", "tests/test_array.py::test_unique_items[value10-expected10]", "tests/test_array.py::test_unique_items[value11-expected11]", "tests/test_array.py::test_unique_items[value12-expected12]", "tests/test_array.py::test_unique_items[value13-expected13]", "tests/test_array.py::test_unique_items[value14-expected14]", "tests/test_array.py::test_unique_items[value15-expected15]", "tests/test_array.py::test_unique_items[value16-expected16]", "tests/test_array.py::test_unique_items[value17-expected17]", "tests/test_array.py::test_min_and_unique_items", "tests/test_array.py::test_items_all_same[value0-expected0]", "tests/test_array.py::test_items_all_same[value1-expected1]", "tests/test_array.py::test_items_all_same[value2-expected2]", "tests/test_array.py::test_different_items[value0-expected0]", "tests/test_array.py::test_different_items[value1-expected1]", "tests/test_array.py::test_different_items[value2-expected2]", "tests/test_array.py::test_different_items[value3-expected3]", "tests/test_array.py::test_different_items[value4-expected4]", "tests/test_array.py::test_different_items[value5-expected5]", "tests/test_array.py::test_different_items_with_additional_items[value0-expected0]", "tests/test_array.py::test_different_items_with_additional_items[value1-expected1]", "tests/test_array.py::test_different_items_with_additional_items[value2-expected2]", "tests/test_array.py::test_different_items_with_additional_items[value3-expected3]", "tests/test_array.py::test_different_items_with_additional_items[value4-expected4]", "tests/test_array.py::test_different_items_with_additional_items[value5-expected5]", "tests/test_array.py::test_different_items_without_additional_items[value0-expected0]", "tests/test_array.py::test_different_items_without_additional_items[value1-expected1]", "tests/test_array.py::test_different_items_without_additional_items[value2-expected2]", "tests/test_array.py::test_different_items_without_additional_items[value3-expected3]", "tests/test_array.py::test_different_items_without_additional_items[value4-expected4]", "tests/test_array.py::test_different_items_without_additional_items[value5-expected5]", "tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-02-27 23:11:24+00:00
bsd-3-clause
2,742
horejsek__python-fastjsonschema-176
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index cfc3b7b..25cb374 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -457,9 +457,10 @@ class CodeGeneratorDraft04(CodeGenerator): with self.l('if {variable}_is_dict:'): if not isinstance(self._definition['required'], (list, tuple)): raise JsonSchemaDefinitionException('required must be an array') - self.create_variable_with_length() - with self.l('if not all(prop in {variable} for prop in {required}):'): - self.exc('{name} must contain {} properties', self.e(self._definition['required']), rule='required') + self.l('{variable}__missing_keys = set({required}) - {variable}.keys()') + with self.l('if {variable}__missing_keys:'): + dynamic = 'str(sorted({variable}__missing_keys)) + " properties"' + self.exc('{name} must contain ', self.e(self._definition['required']), rule='required', append_to_msg=dynamic) def generate_properties(self): """
horejsek/python-fastjsonschema
aa7be271c233278c43096ed0a401dcb3c4a12708
diff --git a/tests/test_integration.py b/tests/test_integration.py index d778b63..4ff8ee6 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -84,9 +84,13 @@ definition = { [9, 'hello', [1, 2, 3], {'a': 'a', 'b': 'b', 'c': 'xy'}, 'str', 5], JsonSchemaValueException('data[2][1] must be string', value=2, name='data[2][1]', definition={'type': 'string'}, rule='type'), ), + ( + [9, 'hello', [1], {'q': 'q', 'x': 'x', 'y': 'y'}, 'str', 5], + JsonSchemaValueException('data[3] must contain [\'a\', \'b\'] properties', value={'q': 'q', 'x': 'x', 'y': 'y'}, name='data[3]', definition=definition['items'][3], rule='required'), + ), ( [9, 'hello', [1], {'a': 'a', 'x': 'x', 'y': 'y'}, 'str', 5], - JsonSchemaValueException('data[3] must contain [\'a\', \'b\'] properties', value={'a': 'a', 'x': 'x', 'y': 'y'}, name='data[3]', definition=definition['items'][3], rule='required'), + JsonSchemaValueException('data[3] must contain [\'b\'] properties', value={'a': 'a', 'x': 'x', 'y': 'y'}, name='data[3]', definition=definition['items'][3], rule='required'), ), ( [9, 'hello', [1], {}, 'str', 5], diff --git a/tests/test_object.py b/tests/test_object.py index 19967a3..228aa9d 100644 --- a/tests/test_object.py +++ b/tests/test_object.py @@ -43,10 +43,11 @@ def test_min_properties(asserter, value, expected): }, value, expected) -exc = JsonSchemaValueException('data must contain [\'a\', \'b\'] properties', value='{data}', name='data', definition='{definition}', rule='required') +def make_exc(missing): + return JsonSchemaValueException('data must contain {} properties'.format(missing), value='{data}', name='data', definition='{definition}', rule='required') @pytest.mark.parametrize('value, expected', [ - ({}, exc), - ({'a': 1}, exc), + ({}, make_exc(['a', 'b'])), + ({'a': 1}, make_exc(['b'])), ({'a': 1, 'b': 2}, {'a': 1, 'b': 2}), ]) def test_required(asserter, value, expected):
errors for missing required properties currently, if a required property is missing, the error message lists _all the required properties. could we consider listing only the missing ones? ``` >>> fastjsonschema.validate({'required': ['foo', 'bar']}, {'foo': 1}) JsonSchemaValueException: data must contain ['foo', 'bar'] properties ``` this is particularly useful with a large number of required properties where eg only one may be missing
0.0
aa7be271c233278c43096ed0a401dcb3c4a12708
[ "tests/test_integration.py::test_integration[value11-expected11]", "tests/test_object.py::test_required[value1-expected1]" ]
[ "tests/test_integration.py::test_integration[value0-expected0]", "tests/test_integration.py::test_integration[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]", "tests/test_integration.py::test_integration[value3-expected3]", "tests/test_integration.py::test_integration[value4-expected4]", "tests/test_integration.py::test_integration[value5-expected5]", "tests/test_integration.py::test_integration[value6-expected6]", "tests/test_integration.py::test_integration[value7-expected7]", "tests/test_integration.py::test_integration[value8-expected8]", "tests/test_integration.py::test_integration[value9-expected9]", "tests/test_integration.py::test_integration[value10-expected10]", "tests/test_integration.py::test_integration[value12-expected12]", "tests/test_integration.py::test_integration[value13-expected13]", "tests/test_integration.py::test_integration[value14-expected14]", "tests/test_integration.py::test_any_of_with_patterns", "tests/test_integration.py::test_swap_handlers", "tests/test_object.py::test_object[0-expected0]", "tests/test_object.py::test_object[None-expected1]", "tests/test_object.py::test_object[True-expected2]", "tests/test_object.py::test_object[False-expected3]", "tests/test_object.py::test_object[abc-expected4]", "tests/test_object.py::test_object[value5-expected5]", "tests/test_object.py::test_object[value6-expected6]", "tests/test_object.py::test_object[value7-expected7]", "tests/test_object.py::test_max_properties[value0-expected0]", "tests/test_object.py::test_max_properties[value1-expected1]", "tests/test_object.py::test_max_properties[value2-expected2]", "tests/test_object.py::test_min_properties[value0-expected0]", "tests/test_object.py::test_min_properties[value1-expected1]", "tests/test_object.py::test_min_properties[value2-expected2]", "tests/test_object.py::test_required[value0-expected0]", "tests/test_object.py::test_required[value2-expected2]", "tests/test_object.py::test_properties[value0-expected0]", "tests/test_object.py::test_properties[value1-expected1]", "tests/test_object.py::test_properties[value2-expected2]", "tests/test_object.py::test_properties[value3-expected3]", "tests/test_object.py::test_properties[value4-expected4]", "tests/test_object.py::test_invalid_properties", "tests/test_object.py::test_properties_with_additional_properties[value0-expected0]", "tests/test_object.py::test_properties_with_additional_properties[value1-expected1]", "tests/test_object.py::test_properties_with_additional_properties[value2-expected2]", "tests/test_object.py::test_properties_with_additional_properties[value3-expected3]", "tests/test_object.py::test_properties_with_additional_properties[value4-expected4]", "tests/test_object.py::test_properties_with_additional_properties[value5-expected5]", "tests/test_object.py::test_properties_without_additional_properties[value0-expected0]", "tests/test_object.py::test_properties_without_additional_properties[value1-expected1]", "tests/test_object.py::test_properties_without_additional_properties[value2-expected2]", "tests/test_object.py::test_properties_without_additional_properties[value3-expected3]", "tests/test_object.py::test_properties_without_additional_properties[value4-expected4]", "tests/test_object.py::test_properties_without_additional_properties[value5-expected5]", "tests/test_object.py::test_properties_without_additional_properties[value6-expected6]", "tests/test_object.py::test_pattern_properties[value0-expected0]", "tests/test_object.py::test_pattern_properties[value1-expected1]", "tests/test_object.py::test_pattern_properties[value2-expected2]", "tests/test_object.py::test_pattern_properties[value3-expected3]", "tests/test_object.py::test_pattern_properties[value4-expected4]", "tests/test_object.py::test_additional_properties[value0-expected0]", "tests/test_object.py::test_additional_properties[value1-expected1]", "tests/test_object.py::test_additional_properties[value2-expected2]", "tests/test_object.py::test_additional_properties[value3-expected3]", "tests/test_object.py::test_additional_properties[value4-expected4]", "tests/test_object.py::test_any_additional_properties[value0-expected0]", "tests/test_object.py::test_any_additional_properties[value1-expected1]", "tests/test_object.py::test_any_additional_properties[value2-expected2]", "tests/test_object.py::test_any_additional_properties[value3-expected3]", "tests/test_object.py::test_any_additional_properties[value4-expected4]", "tests/test_object.py::test_any_additional_properties[value5-expected5]", "tests/test_object.py::test_any_additional_properties[value6-expected6]", "tests/test_object.py::test_any_additional_properties[value7-expected7]", "tests/test_object.py::test_object_with_id_property[value0-expected0]", "tests/test_object.py::test_object_with_id_property[value1-expected1]", "tests/test_object.py::test_object_with_ref_property[value0-expected0]", "tests/test_object.py::test_object_with_ref_property[value1-expected1]", "tests/test_object.py::test_dependencies[value0-expected0]", "tests/test_object.py::test_dependencies[value1-expected1]", "tests/test_object.py::test_dependencies[value2-expected2]", "tests/test_object.py::test_full_name_after_ref[value0-expected0]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-07-13 09:35:04+00:00
bsd-3-clause
2,743
horejsek__python-fastjsonschema-24
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 3ee257b..6d79a1e 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -18,7 +18,7 @@ JSON_TYPE_TO_PYTHON_TYPE = { class CodeGeneratorDraft04(CodeGenerator): # pylint: disable=line-too-long FORMAT_REGEXS = { - 'date-time': r'^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)?$', + 'date-time': r'^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|Z)?$', 'email': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', 'hostname': ( r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*'
horejsek/python-fastjsonschema
dc3ae94332ce901181120db8a2f9f8b6d5339622
diff --git a/tests/test_datetime.py b/tests/test_datetime.py new file mode 100644 index 0000000..2263e9f --- /dev/null +++ b/tests/test_datetime.py @@ -0,0 +1,15 @@ + +import pytest + +from fastjsonschema import JsonSchemaException + + +exc = JsonSchemaException('data must be date-time') [email protected]('value, expected', [ + ('', exc), + ('bla', exc), + ('2018-02-05T14:17:10.00Z', '2018-02-05T14:17:10.00Z'), + ('2018-02-05T14:17:10Z', '2018-02-05T14:17:10Z'), +]) +def test_datetime(asserter, value, expected): + asserter({'type': 'string', 'format': 'date-time'}, value, expected)
JsonSchemaException when using date-time with RFC 3339 compliant string Validation fails with this example: ``` import json import fastjsonschema schema = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/example.schema.json", "title": "Example", "description": "An example schema", "type": "object", "properties": { "date": { "type": "string", "description": "Some date", "format": "date-time" } } } validate = fastjsonschema.compile(schema) validate({"date": "2018-02-05T14:17:10Z"}) ``` The output is: ``` Traceback (most recent call last): File "validate_simple_example.py", line 22, in <module> validate({"date": "2018-02-05T14:17:10Z"}) File "<string>", line 16, in validate_https___example_com_example_schema_json fastjsonschema.exceptions.JsonSchemaException ``` According to the [json schema docs](http://json-schema.org/latest/json-schema-validation.html#rfc.section.7.3.1) all RFC 3339 timestamps should be valid. I think the problem is the milliseconds part. It should be optional if I'm not wrong. The above example runs fine with: `validate({"date": "2018-02-05T14:17:10.00Z"})` The current regex is: ``` ^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)?$ ``` I suggest changing it to: ``` ^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|Z)?$ ``` Also maybe it's worth thinking about not using regexes for format validation for some of the stuff (like ips, dates, etc.)
0.0
dc3ae94332ce901181120db8a2f9f8b6d5339622
[ "tests/test_datetime.py::test_datetime[2018-02-05T14:17:10Z-2018-02-05T14:17:10Z]" ]
[ "tests/test_datetime.py::test_datetime[-expected0]", "tests/test_datetime.py::test_datetime[bla-expected1]", "tests/test_datetime.py::test_datetime[2018-02-05T14:17:10.00Z-2018-02-05T14:17:10.00Z]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-09-12 12:06:19+00:00
bsd-3-clause
2,744
horejsek__python-fastjsonschema-25
diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index 11358d2..28b9480 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -93,7 +93,7 @@ class CodeGenerator: '', ] ) - regexs = ['"{}": {}'.format(key, value) for key, value in self._compile_regexps.items()] + regexs = ['"{}": re.compile(r"{}")'.format(key, value.pattern) for key, value in self._compile_regexps.items()] return '\n'.join( [ 'import re',
horejsek/python-fastjsonschema
97d45db2d13c3a769d9805cca2a672643b17bb6b
diff --git a/tests/test_compile_to_code.py b/tests/test_compile_to_code.py index 394e648..7312f38 100644 --- a/tests/test_compile_to_code.py +++ b/tests/test_compile_to_code.py @@ -1,8 +1,19 @@ import os import pytest +import shutil from fastjsonschema import JsonSchemaException, compile_to_code [email protected]_fixture(autouse=True) +def run_around_tests(): + temp_dir = 'temp' + # Code that will run before your test, for example: + if not os.path.isdir(temp_dir): + os.makedirs(temp_dir) + # A test function will be run at this point + yield + # Code that will run after your test, for example: + shutil.rmtree(temp_dir) def test_compile_to_code(): code = compile_to_code({ @@ -12,11 +23,9 @@ def test_compile_to_code(): 'c': {'format': 'hostname'}, } }) - if not os.path.isdir('temp'): - os.makedirs('temp') - with open('temp/schema.py', 'w') as f: + with open('temp/schema_1.py', 'w') as f: f.write(code) - from temp.schema import validate + from temp.schema_1 import validate assert validate({ 'a': 'a', 'b': 1, @@ -26,3 +35,18 @@ def test_compile_to_code(): 'b': 1, 'c': 'example.com', } + +def test_compile_to_code_ipv6_regex(): + code = compile_to_code({ + 'properties': { + 'ip': {'format': 'ipv6'}, + } + }) + with open('temp/schema_2.py', 'w') as f: + f.write(code) + from temp.schema_2 import validate + assert validate({ + 'ip': '2001:0db8:85a3:0000:0000:8a2e:0370:7334' + }) == { + 'ip': '2001:0db8:85a3:0000:0000:8a2e:0370:7334' + } \ No newline at end of file
ipv6 format leads to cut off string in generated code Thanks for the quick fix of #21 ! I just tried it, and indeed, the regex pattern is now there. But the code is still broken due to a different issue. When I generate the code for this schema: ``` { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/example.schema.json", "title": "Example", "description": "An example schema", "type": "object", "properties": { "ip": { "type": "string", "description": "The IP of the future", "format": "ipv6" } }, "required": [ "ip" ] } ``` The resulting code contains the following dict: ``` REGEX_PATTERNS = { "ipv6_re_pattern": re.compile('^(?:(?:[0-9A-Fa-f]{1,4}:){6}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|::(?:[0-9A-Fa-f]{1,4) } ``` It looks like the line is just cut off at that point, so the code won't work. `SyntaxError: EOL while scanning string literal`
0.0
97d45db2d13c3a769d9805cca2a672643b17bb6b
[ "tests/test_compile_to_code.py::test_compile_to_code_ipv6_regex" ]
[ "tests/test_compile_to_code.py::test_compile_to_code" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2018-09-12 12:38:34+00:00
bsd-3-clause
2,745
horejsek__python-fastjsonschema-27
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 6d79a1e..57b2a85 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -20,10 +20,7 @@ class CodeGeneratorDraft04(CodeGenerator): FORMAT_REGEXS = { 'date-time': r'^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:[+-][0-2]\d:[0-5]\d|Z)?$', 'email': r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', - 'hostname': ( - r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*' - r'([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{1,62}[A-Za-z0-9])$' - ), + 'hostname': r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9])$', 'ipv4': r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', 'ipv6': r'^(?:(?:[0-9A-Fa-f]{1,4}:){6}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|::(?:[0-9A-Fa-f]{1,4}:){5}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,3}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}:(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,4}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,5}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}|(?:(?:[0-9A-Fa-f]{1,4}:){,6}[0-9A-Fa-f]{1,4})?::)$', 'uri': r'^\w+:(\/?\/?)[^\s]+$',
horejsek/python-fastjsonschema
6c07d2300c5018628dab9487bd5a89b85acb3084
diff --git a/tests/test_datetime.py b/tests/test_datetime.py index 2263e9f..b9e460b 100644 --- a/tests/test_datetime.py +++ b/tests/test_datetime.py @@ -1,4 +1,3 @@ - import pytest from fastjsonschema import JsonSchemaException diff --git a/tests/test_hostname.py b/tests/test_hostname.py new file mode 100644 index 0000000..8620ed1 --- /dev/null +++ b/tests/test_hostname.py @@ -0,0 +1,19 @@ +import pytest + +from fastjsonschema import JsonSchemaException + + +exc = JsonSchemaException('data must be hostname') [email protected]('value, expected', [ + ('', exc), + ('LDhsjf878&d', exc), + ('bla.bla-', exc), + ('example.example.com-', exc), + ('localhost', 'localhost'), + ('example.com', 'example.com'), + ('example.de', 'example.de'), + ('example.fr', 'example.fr'), + ('example.example.com', 'example.example.com'), +]) +def test_hostname(asserter, value, expected): + asserter({'type': 'string', 'format': 'hostname'}, value, expected)
'example.de' (and many others hostnames) not valid with hostname format Aaand another one. Hope you aren't getting annoyed. Running this example throws a JsonSchemaException: ``` import fastjsonschema schema = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://example.com/example.schema.json", "title": "Example", "description": "An example schema", "type": "object", "properties": { "host": { "type": "string", "description": "Some hostname", "format": "hostname" } } } validate = fastjsonschema.compile(schema) validate({"host": "example.de"}) ``` For 'google.com' it works fine. I'll create a PR soon, probably.
0.0
6c07d2300c5018628dab9487bd5a89b85acb3084
[ "tests/test_hostname.py::test_hostname[example.de-example.de]", "tests/test_hostname.py::test_hostname[example.fr-example.fr]" ]
[ "tests/test_datetime.py::test_datetime[-expected0]", "tests/test_datetime.py::test_datetime[bla-expected1]", "tests/test_datetime.py::test_datetime[2018-02-05T14:17:10.00Z-2018-02-05T14:17:10.00Z]", "tests/test_datetime.py::test_datetime[2018-02-05T14:17:10Z-2018-02-05T14:17:10Z]", "tests/test_hostname.py::test_hostname[-expected0]", "tests/test_hostname.py::test_hostname[LDhsjf878&d-expected1]", "tests/test_hostname.py::test_hostname[bla.bla--expected2]", "tests/test_hostname.py::test_hostname[example.example.com--expected3]", "tests/test_hostname.py::test_hostname[localhost-localhost]", "tests/test_hostname.py::test_hostname[example.com-example.com]", "tests/test_hostname.py::test_hostname[example.example.com-example.example.com]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-09-12 15:25:25+00:00
bsd-3-clause
2,746
horejsek__python-fastjsonschema-88
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 01cc07e..6c50a21 100644 --- a/fastjsonschema/draft04.py +++ b/fastjsonschema/draft04.py @@ -11,7 +11,7 @@ JSON_TYPE_TO_PYTHON_TYPE = { 'number': 'int, float', 'integer': 'int', 'string': 'str', - 'array': 'list', + 'array': 'list, tuple', 'object': 'dict', } diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index fc5b4b1..17cebd6 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -281,7 +281,7 @@ class CodeGenerator: if variable_name in self._variables: return self._variables.add(variable_name) - self.l('{variable}_is_list = isinstance({variable}, list)') + self.l('{variable}_is_list = isinstance({variable}, (list, tuple))') def create_variable_is_dict(self): """
horejsek/python-fastjsonschema
e845f622d6340703342a58318d94a295d86bbfaf
diff --git a/tests/test_array.py b/tests/test_array.py index 33f6a06..3d77435 100644 --- a/tests/test_array.py +++ b/tests/test_array.py @@ -134,3 +134,35 @@ def test_different_items_without_additional_items(asserter, value, expected): ], 'additionalItems': False, }, value, expected) + + [email protected]('value, expected', [ + ((), ()), + (('a',), ('a',)), + (('a', 'b'), ('a', 'b')), + (('a', 'b', 3), JsonSchemaException('data[2] must be string', value=3, name='data[2]', + definition={'type': 'string'}, rule='type')), +]) +def test_tuples_as_arrays(asserter, value, expected): + asserter({ + '$schema': 'http://json-schema.org/draft-06/schema', + 'type': 'array', + 'items': + {'type': 'string'}, + + }, value, expected) + + [email protected]('value, expected', [ + ({'a': [], 'b': ()}, {'a': [], 'b': ()}), + ({'a': (1, 2), 'b': (3, 4)}, {'a': (1, 2), 'b': (3, 4)}), +]) +def test_mixed_arrays(asserter, value, expected): + asserter({ + 'type': 'object', + 'properties': { + 'a': {'type': 'array'}, + 'b': {'type': 'array'}, + }, + }, value, expected) + diff --git a/tests/test_integration.py b/tests/test_integration.py index 5ea2c08..27135f9 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -52,6 +52,10 @@ definition = { [9, 'world', [1], {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3], [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3], ), + ( + (9, 'world', (1,), {'a': 'a', 'b': 'b', 'd': 'd'}, 42, 3), + (9, 'world', (1,), {'a': 'a', 'b': 'b', 'c': 'abc', 'd': 'd'}, 42, 3), + ), ( [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3], [9, 'world', [1], {'a': 'a', 'b': 'b', 'c': 'xy'}, 42, 3],
Support for validating tuples as arrays? Would a PR be accepted that modified fastjsonschema to validate a `tuple` object as an array? Possible as an optional behavior? The array validation function here https://github.com/horejsek/python-fastjsonschema/blob/master/fastjsonschema/generator.py#L275 only accepts a list, and I have a situation where I have data structures coming in from httpapi endpoints and custom RPC endpoints; and the RPC endpoints have all their array objects deserialized as tuples; so currently i'm having to wrap the fastjsonschema callable objects with a function that will recursively list-ify all values I pass in for validation. This is similar to https://github.com/Julian/jsonschema/issues/148
0.0
e845f622d6340703342a58318d94a295d86bbfaf
[ "tests/test_array.py::test_tuples_as_arrays[value0-expected0]", "tests/test_array.py::test_tuples_as_arrays[value1-expected1]", "tests/test_array.py::test_tuples_as_arrays[value2-expected2]", "tests/test_array.py::test_tuples_as_arrays[value3-expected3]", "tests/test_array.py::test_mixed_arrays[value0-expected0]", "tests/test_array.py::test_mixed_arrays[value1-expected1]", "tests/test_integration.py::test_integration[value2-expected2]" ]
[ "tests/test_array.py::test_array[0-expected0]", "tests/test_array.py::test_array[None-expected1]", "tests/test_array.py::test_array[True-expected2]", "tests/test_array.py::test_array[False-expected3]", "tests/test_array.py::test_array[abc-expected4]", "tests/test_array.py::test_array[value5-expected5]", "tests/test_array.py::test_array[value6-expected6]", "tests/test_array.py::test_array[value7-expected7]", "tests/test_array.py::test_max_items[value0-expected0]", "tests/test_array.py::test_max_items[value1-expected1]", "tests/test_array.py::test_max_items[value2-expected2]", "tests/test_array.py::test_max_items[value3-expected3]", "tests/test_array.py::test_min_items[value0-expected0]", "tests/test_array.py::test_min_items[value1-expected1]", "tests/test_array.py::test_min_items[value2-expected2]", "tests/test_array.py::test_min_items[value3-expected3]", "tests/test_array.py::test_unique_items[value0-expected0]", "tests/test_array.py::test_unique_items[value1-expected1]", "tests/test_array.py::test_unique_items[value2-expected2]", "tests/test_array.py::test_unique_items[value3-expected3]", "tests/test_array.py::test_min_and_unique_items", "tests/test_array.py::test_items_all_same[value0-expected0]", "tests/test_array.py::test_items_all_same[value1-expected1]", "tests/test_array.py::test_items_all_same[value2-expected2]", "tests/test_array.py::test_different_items[value0-expected0]", "tests/test_array.py::test_different_items[value1-expected1]", "tests/test_array.py::test_different_items[value2-expected2]", "tests/test_array.py::test_different_items[value3-expected3]", "tests/test_array.py::test_different_items[value4-expected4]", "tests/test_array.py::test_different_items[value5-expected5]", "tests/test_array.py::test_different_items_with_additional_items[value0-expected0]", "tests/test_array.py::test_different_items_with_additional_items[value1-expected1]", "tests/test_array.py::test_different_items_with_additional_items[value2-expected2]", "tests/test_array.py::test_different_items_with_additional_items[value3-expected3]", "tests/test_array.py::test_different_items_with_additional_items[value4-expected4]", "tests/test_array.py::test_different_items_with_additional_items[value5-expected5]", "tests/test_array.py::test_different_items_without_additional_items[value0-expected0]", "tests/test_array.py::test_different_items_without_additional_items[value1-expected1]", "tests/test_array.py::test_different_items_without_additional_items[value2-expected2]", "tests/test_array.py::test_different_items_without_additional_items[value3-expected3]", "tests/test_array.py::test_different_items_without_additional_items[value4-expected4]", "tests/test_array.py::test_different_items_without_additional_items[value5-expected5]", "tests/test_integration.py::test_integration[value0-expected0]", "tests/test_integration.py::test_integration[value1-expected1]", "tests/test_integration.py::test_integration[value3-expected3]", "tests/test_integration.py::test_integration[value4-expected4]", "tests/test_integration.py::test_integration[value5-expected5]", "tests/test_integration.py::test_integration[value6-expected6]", "tests/test_integration.py::test_integration[value7-expected7]", "tests/test_integration.py::test_integration[value8-expected8]", "tests/test_integration.py::test_integration[value9-expected9]", "tests/test_integration.py::test_integration[value10-expected10]", "tests/test_integration.py::test_integration[value11-expected11]", "tests/test_integration.py::test_integration[value12-expected12]", "tests/test_integration.py::test_integration[value13-expected13]", "tests/test_integration.py::test_any_of_with_patterns" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-02-27 04:57:45+00:00
bsd-3-clause
2,747
hsahovic__poke-env-127
diff --git a/fixture_data/gmax.showdown b/fixture_data/gmax.showdown new file mode 100644 index 0000000..252929c --- /dev/null +++ b/fixture_data/gmax.showdown @@ -0,0 +1,60 @@ +Coalossal @ Weakness Policy +Ability: Steam Engine +Level: 50 +Gigantamax: Yes +EVs: 252 HP / 1 Atk / 252 SpA / 4 SpD +Modest Nature +IVs: 0 Atk +- Heat Wave +- Meteor Beam +- Protect +- Solar Beam + +Corviknight @ Choice Band +Ability: Mirror Armor +Gigantamax: Yes +EVs: 248 HP / 252 Atk / 1 Def / 8 SpA +Brave Nature +- Air Slash +- Bulk Up +- Flash Cannon +- Iron Head + +Venusaur @ Choice Band +Ability: Chlorophyll +Gigantamax: Yes +EVs: 252 HP / 4 Atk / 1 SpA / 252 Spe +Hasty Nature +- Double-Edge +- Leaf Storm +- Protect +- Sleep Powder + +Snorlax @ Aguav Berry +Ability: Gluttony +EVs: 252 HP / 252 Atk / 1 Def / 4 SpA +Brave Nature +- Curse +- Fire Blast +- Gunk Shot +- Heavy Slam + +Butterfree-Gmax @ Figy Berry +Ability: Tinted Lens +Gigantamax: Yes +EVs: 248 HP / 8 Atk / 1 SpA / 252 SpD +Gentle Nature +- Baton Pass +- Double-Edge +- Giga Drain +- Protect + +Gengar-Gmax @ Life Orb +Ability: Cursed Body +EVs: 252 Atk / 1 Def / 4 SpD / 252 Spe +Jolly Nature +- Disable +- Explosion +- Focus Punch +- Haze + diff --git a/fixture_data/teams.json b/fixture_data/teams.json index 5d9ee2e..403ae8e 100644 --- a/fixture_data/teams.json +++ b/fixture_data/teams.json @@ -1,4 +1,10 @@ { + "gen8nationaldexag": [ + { + "showdown-file": "gmax.showdown", + "packed-format": "Coalossal||weaknesspolicy|steamengine|heatwave,meteorbeam,protect,solarbeam|Modest|252,1,,252,4,||,0,,,,||50|,,,G]Corviknight||choiceband|mirrorarmor|airslash,bulkup,flashcannon,ironhead|Brave|248,252,1,8,,|||||,,,G]Venusaur||choiceband|chlorophyll|doubleedge,leafstorm,protect,sleeppowder|Hasty|252,4,,1,,252|||||,,,G]Snorlax||aguavberry|gluttony|curse,fireblast,gunkshot,heavyslam|Brave|252,252,1,4,,|||||]Butterfree-Gmax||figyberry|tintedlens|batonpass,doubleedge,gigadrain,protect|Gentle|248,8,,1,252,|||||,,,G]Gengar-Gmax||lifeorb|cursedbody|disable,explosion,focuspunch,haze|Jolly|,252,1,,4,252|||||" + } + ], "gen8ubers": [ { "showdown-file": "clefable dugtrio.showdown", diff --git a/src/poke_env/teambuilder/teambuilder.py b/src/poke_env/teambuilder/teambuilder.py index b5f6f91..19ecb33 100644 --- a/src/poke_env/teambuilder/teambuilder.py +++ b/src/poke_env/teambuilder/teambuilder.py @@ -77,6 +77,8 @@ class Teambuilder(ABC): current_mon.moves.append(line) elif line.startswith("Shiny"): current_mon.shiny = line.strip().endswith("Yes") + elif line.startswith("Gigantamax"): + current_mon.gmax = line.strip().endswith("Yes") elif line.strip().endswith(" Nature"): nature = line.strip().replace(" Nature", "") current_mon.nature = nature diff --git a/src/poke_env/teambuilder/teambuilder_pokemon.py b/src/poke_env/teambuilder/teambuilder_pokemon.py index 2cfa4e3..1466858 100644 --- a/src/poke_env/teambuilder/teambuilder_pokemon.py +++ b/src/poke_env/teambuilder/teambuilder_pokemon.py @@ -43,6 +43,7 @@ class TeambuilderPokemon: level=None, happiness=None, hiddenpowertype=None, + gmax=None, ): self.nickname = nickname self.species = species @@ -54,6 +55,7 @@ class TeambuilderPokemon: self.level = level self.happiness = happiness self.hiddenpowertype = hiddenpowertype + self.gmax = gmax if evs is not None: self.evs = evs @@ -96,8 +98,12 @@ class TeambuilderPokemon: @property def formatted_endstring(self) -> str: - if self.hiddenpowertype: + if self.hiddenpowertype and self.gmax: + return ",%s,,G" % self.hiddenpowertype + elif self.hiddenpowertype: return ",%s," % self.hiddenpowertype + elif self.gmax: + return ",,,G" return "" @property
hsahovic/poke-env
872e49883a144a1046124e7b1f263f2728430647
diff --git a/unit_tests/teambuilder/test_teambuilder_pokemon.py b/unit_tests/teambuilder/test_teambuilder_pokemon.py index 509f2a8..ec327d3 100644 --- a/unit_tests/teambuilder/test_teambuilder_pokemon.py +++ b/unit_tests/teambuilder/test_teambuilder_pokemon.py @@ -17,9 +17,10 @@ def test_teambuilder_pokemon_formatting(): level=84, happiness=134, hiddenpowertype="water", + gmax=True, ) assert ( tp.formatted == "testy|dragonair|choiceband|shedskin|tackle,watergun,hiddenpower|Adamant||M|\ -|S|84|134,water," +|S|84|134,water,,G" )
Showdown team parser doesn't support gmax syntax **Summary**: When using `Teambuilder#parse_showdown_team`, the nickname will be parsed incorrectly when parsing a gmax pokemon. **Actual outcome**: Nickname will be parsed as "Gigantamax: Yes". **Expected outcome** Nickname parsed as "Coalossal". Potentially a gmax flag set as True/False/None. **Example**: ``` Coalossal @ Weakness Policy Ability: Steam Engine Level: 50 Gigantamax: Yes EVs: 252 HP / 252 SpA / 4 SpD Modest Nature IVs: 0 Atk - Heat Wave - Meteor Beam - Protect - Solar Beam ```
0.0
872e49883a144a1046124e7b1f263f2728430647
[ "unit_tests/teambuilder/test_teambuilder_pokemon.py::test_teambuilder_pokemon_formatting" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-02-23 00:33:45+00:00
mit
2,748
hsahovic__poke-env-153
diff --git a/src/poke_env/data.py b/src/poke_env/data.py index e04eb89..950ee16 100644 --- a/src/poke_env/data.py +++ b/src/poke_env/data.py @@ -38,7 +38,7 @@ def _compute_type_chart(chart_path: str) -> Dict[str, Dict[str, float]]: return type_chart -@lru_cache(2 ** 13) # pyre-ignore +@lru_cache(2 ** 13) def to_id_str(name: str) -> str: """Converts a full-name to its corresponding id string. :param name: The name to convert. diff --git a/src/poke_env/environment/abstract_battle.py b/src/poke_env/environment/abstract_battle.py index de6a02c..5b37b8f 100644 --- a/src/poke_env/environment/abstract_battle.py +++ b/src/poke_env/environment/abstract_battle.py @@ -46,7 +46,6 @@ class AbstractBattle(ABC): "askreg", "debug", "c", - "cant", "crit", "deinit", "gametype", diff --git a/src/poke_env/environment/pokemon.py b/src/poke_env/environment/pokemon.py index 1ca9dfb..0cbc57d 100644 --- a/src/poke_env/environment/pokemon.py +++ b/src/poke_env/environment/pokemon.py @@ -304,6 +304,9 @@ class Pokemon: self._preparing = False self._protect_counter = 0 + if self._status == Status.TOX: + self._status_counter = 0 + def _transform(self, into): current_hp = self.current_hp self._update_from_pokedex(into.species, store_species=False)
hsahovic/poke-env
b83e29de2991846345f23c738a78fb7b5caf6911
diff --git a/unit_tests/environment/test_battle.py b/unit_tests/environment/test_battle.py index b8563bd..6ab90be 100644 --- a/unit_tests/environment/test_battle.py +++ b/unit_tests/environment/test_battle.py @@ -431,3 +431,82 @@ def test_end_illusion(): assert battle.opponent_active_pokemon.species == "kingdra" assert battle.get_pokemon("p2: Zoroark").boosts == non_empty_boosts assert battle.get_pokemon("p2: Celebi").boosts == empty_boosts + + +def test_toxic_counter(example_request): + logger = MagicMock() + battle = Battle("tag", "username", logger) + + battle._parse_request(example_request) + battle._parse_message(["", "-status", "p2a: Venusaur", "tox"]) + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 0 + + battle.end_turn(2) + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 1 + + battle.end_turn(3) + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 2 + + battle._switch("p2a: Unfezant", "Unfezant, L86, M", "100/100") + assert battle.active_pokemon.status is None + assert battle.active_pokemon.status_counter == 0 + + battle.end_turn(4) + assert battle.active_pokemon.status is None + assert battle.active_pokemon.status_counter == 0 + + battle._switch("p2a: Venusaur", "Venusaur, L82, M", "100/100 tox") + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 0 + + battle.end_turn(5) + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 1 + + battle.end_turn(6) + assert battle.active_pokemon.status == Status.TOX + assert battle.active_pokemon.status_counter == 2 + + +def test_sleep_counter(example_request): + logger = MagicMock() + battle = Battle("tag", "username", logger) + + battle._parse_request(example_request) + battle._parse_message(["", "-status", "p2a: Venusaur", "slp"]) + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 0 + + battle.end_turn(2) + battle._parse_message(["", "cant", "p2a: Venusaur", ""]) + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 1 + + battle.end_turn(3) + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 1 + + battle._switch("p2a: Unfezant", "Unfezant, L86, M", "100/100") + assert battle.active_pokemon.status is None + assert battle.active_pokemon.status_counter == 0 + + battle.end_turn(4) + assert battle.active_pokemon.status is None + assert battle.active_pokemon.status_counter == 0 + + battle._switch("p2a: Venusaur", "Venusaur, L82, M", "100/100 slp") + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 1 + + battle.end_turn(5) + battle._parse_message(["", "cant", "p2a: Venusaur", ""]) + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 2 + + battle.end_turn(6) + battle._parse_message(["", "cant", "p2a: Venusaur", ""]) + assert battle.active_pokemon.status == Status.SLP + assert battle.active_pokemon.status_counter == 3
toxic status counter Hey, It seems to me that the status counter for toxic was off, so I added a reset to the counter under def _switch_in(self, details=None) and I think solved the problem. Let me know if this is correct :)
0.0
b83e29de2991846345f23c738a78fb7b5caf6911
[ "unit_tests/environment/test_battle.py::test_toxic_counter", "unit_tests/environment/test_battle.py::test_sleep_counter" ]
[ "unit_tests/environment/test_battle.py::test_battle_get_pokemon", "unit_tests/environment/test_battle.py::test_battle_side_start_end", "unit_tests/environment/test_battle.py::test_battle_field_interactions", "unit_tests/environment/test_battle.py::test_battle_weather_interactions", "unit_tests/environment/test_battle.py::test_battle_player_role_interaction", "unit_tests/environment/test_battle.py::test_battle_tag", "unit_tests/environment/test_battle.py::test_battle_request_parsing", "unit_tests/environment/test_battle.py::test_battle_request_and_interactions", "unit_tests/environment/test_battle.py::test_end_illusion" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-05-08 17:15:52+00:00
mit
2,749
hsahovic__poke-env-158
diff --git a/src/poke_env/environment/abstract_battle.py b/src/poke_env/environment/abstract_battle.py index eb70606..ed07d0d 100644 --- a/src/poke_env/environment/abstract_battle.py +++ b/src/poke_env/environment/abstract_battle.py @@ -241,6 +241,14 @@ class AbstractBattle(ABC): def _field_start(self, field): field = Field.from_showdown_message(field) + + if field.is_terrain: + self._fields = { + field: turn + for field, turn in self._fields.items() + if not field.is_terrain + } + self._fields[field] = self.turn def _parse_message(self, split_message: List[str]) -> None: diff --git a/src/poke_env/environment/field.py b/src/poke_env/environment/field.py index 8822656..de213ff 100644 --- a/src/poke_env/environment/field.py +++ b/src/poke_env/environment/field.py @@ -54,3 +54,8 @@ class Field(Enum): message, ) return Field._UNKNOWN + + @property + def is_terrain(self) -> bool: + """Wheter this field is a terrain.""" + return self.name.endswith("_TERRAIN")
hsahovic/poke-env
ac8182abbcaf27c776916987382121605933ae23
diff --git a/unit_tests/environment/test_battle.py b/unit_tests/environment/test_battle.py index 4fc832b..2dbb7bc 100644 --- a/unit_tests/environment/test_battle.py +++ b/unit_tests/environment/test_battle.py @@ -524,3 +524,23 @@ def test_rules_are_tracked(): battle._parse_message(["", "rule", "this is a rule!"]) assert battle._rules == ["hello", "hi", "this is a rule!"] + + +def test_field_terrain_interactions(): + logger = MagicMock() + battle = Battle("tag", "username", logger) + + battle._field_start("electricterrain") + assert battle.fields == {Field.ELECTRIC_TERRAIN: 0} + battle.turn = battle.turn + 1 + + battle._field_start("mistyterrain") + assert battle.fields == {Field.MISTY_TERRAIN: 1} + battle.turn = battle.turn + 1 + + battle._field_start("gravity") + assert battle.fields == {Field.MISTY_TERRAIN: 1, Field.GRAVITY: 2} + battle.turn = battle.turn + 1 + + battle._field_start("psychicterrain") + assert battle.fields == {Field.GRAVITY: 2, Field.PSYCHIC_TERRAIN: 3} diff --git a/unit_tests/environment/test_enumerations.py b/unit_tests/environment/test_enumerations.py index 6d20556..5e700b4 100644 --- a/unit_tests/environment/test_enumerations.py +++ b/unit_tests/environment/test_enumerations.py @@ -26,6 +26,18 @@ def test_field_str(): assert str(Field["ELECTRIC_TERRAIN"]) +def test_field_is_terrain(): + terrains = { + Field.ELECTRIC_TERRAIN, + Field.MISTY_TERRAIN, + Field.PSYCHIC_TERRAIN, + Field.GRASSY_TERRAIN, + } + + for field in Field: + assert field.is_terrain == (field in terrains) + + def test_field_build(): assert Field["ELECTRIC_TERRAIN"] == Field.from_showdown_message("electric terrain") assert Field["ELECTRIC_TERRAIN"] == Field.from_showdown_message(
battle.fields Hi Haris, It seems to me like sometimes more than one terrain is returned by battle.fields Could you please look into it
0.0
ac8182abbcaf27c776916987382121605933ae23
[ "unit_tests/environment/test_battle.py::test_field_terrain_interactions", "unit_tests/environment/test_enumerations.py::test_field_is_terrain" ]
[ "unit_tests/environment/test_battle.py::test_battle_get_pokemon", "unit_tests/environment/test_battle.py::test_battle_side_start_end", "unit_tests/environment/test_battle.py::test_battle_field_interactions", "unit_tests/environment/test_battle.py::test_battle_weather_interactions", "unit_tests/environment/test_battle.py::test_battle_player_role_interaction", "unit_tests/environment/test_battle.py::test_battle_tag", "unit_tests/environment/test_battle.py::test_battle_request_parsing", "unit_tests/environment/test_battle.py::test_battle_request_and_interactions", "unit_tests/environment/test_battle.py::test_end_illusion", "unit_tests/environment/test_battle.py::test_toxic_counter", "unit_tests/environment/test_battle.py::test_sleep_counter", "unit_tests/environment/test_battle.py::test_rules_are_tracked", "unit_tests/environment/test_enumerations.py::test_effect_str", "unit_tests/environment/test_enumerations.py::test_effect_build", "unit_tests/environment/test_enumerations.py::test_field_str", "unit_tests/environment/test_enumerations.py::test_field_build", "unit_tests/environment/test_enumerations.py::test_move_category_str", "unit_tests/environment/test_enumerations.py::test_pokemon_gender_str", "unit_tests/environment/test_enumerations.py::test_pokemon_gender_build", "unit_tests/environment/test_enumerations.py::test_status_str", "unit_tests/environment/test_enumerations.py::test_side_condition_str", "unit_tests/environment/test_enumerations.py::test_side_condition_build", "unit_tests/environment/test_enumerations.py::test_weather_str" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-05-14 01:24:52+00:00
mit
2,750
hsahovic__poke-env-68
diff --git a/.circleci/config.yml b/.circleci/config.yml index 3349981..f40d161 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,7 +37,7 @@ jobs: # Download and cache dependencies - restore_cache: keys: - - requirements-{{ checksum "requirements.txt" }}-{{ checksum "requirements-dev.txt" }}-{{ checksum "python-version.txt" }}-v3 + - requirements-{{ checksum "requirements.txt" }}-{{ checksum "requirements-dev.txt" }}-{{ checksum "python-version.txt" }}-v4 - run: name: install dependencies @@ -134,13 +134,13 @@ jobs: - run: name: Uninstall poke-env before caching command: | - pip uninstall poke-env + pip uninstall poke-env --yes - save_cache: paths: - ./venv - ./Pokemon-Showdown - key: requirements-{{ checksum "requirements.txt" }}-{{ checksum "requirements-dev.txt" }}-{{ checksum "python-version.txt" }}-v3 + key: requirements-{{ checksum "requirements.txt" }}-{{ checksum "requirements-dev.txt" }}-{{ checksum "python-version.txt" }}-v4 - run: name: Start showdown server in the background diff --git a/src/poke_env/teambuilder/teambuilder.py b/src/poke_env/teambuilder/teambuilder.py index f1b2264..b5f6f91 100644 --- a/src/poke_env/teambuilder/teambuilder.py +++ b/src/poke_env/teambuilder/teambuilder.py @@ -88,6 +88,8 @@ class Teambuilder(ABC): if "@" in line: mon_info, item = line.split(" @ ") current_mon.item = item.strip() + else: + mon_info = line split_mon_info = mon_info.split(" ") if split_mon_info[-1] == "(M)":
hsahovic/poke-env
8c0fbbde4587fd8ff984bc64ac1baab9b102de51
diff --git a/unit_tests/teambuilder/test_constant_teambuilder.py b/unit_tests/teambuilder/test_constant_teambuilder.py index ccdb69a..c71e02c 100644 --- a/unit_tests/teambuilder/test_constant_teambuilder.py +++ b/unit_tests/teambuilder/test_constant_teambuilder.py @@ -20,3 +20,63 @@ def test_constant_teambuilder_yields_showdown( tb = ConstantTeambuilder(showdown_team) for _ in range(10): assert tb.yield_team() == packed_team + + +def test_showdown_team_parsing_works_without_items(): + team = """ +Flareon +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +Hardy Nature +- Flare Blitz +- Superpower +- Double-Edge +- Iron Tail + +Ninetales +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +IVs: 0 Atk +- Flamethrower +- Extrasensory +- Calm Mind +- Dark Pulse + +Arcanine +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +- Flare Blitz +- Wild Charge +- Facade +- Crunch + +Heatmor +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +- Flare Blitz +- Body Slam +- Night Slash +- Stomping Tantrum + +Typhlosion +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +- Flamethrower +- Extrasensory +- Flare Blitz +- Earthquake + +Rapidash +Ability: Flash Fire +EVs: 252 HP / 126 Def / 126 SpD / 4 Spe +- Flare Blitz +- Wild Charge +- Drill Run +- Poison Jab +""" + + packed_team = "Flareon|||flashfire|flareblitz,superpower,doubleedge,irontail|Hardy|252,,126,,126,4|||||]Ninetales|||flashfire|flamethrower,extrasensory,calmmind,darkpulse||252,,126,,126,4||,0,,,,|||]Arcanine|||flashfire|flareblitz,wildcharge,facade,crunch||252,,126,,126,4|||||]Heatmor|||flashfire|flareblitz,bodyslam,nightslash,stompingtantrum||252,,126,,126,4|||||]Typhlosion|||flashfire|flamethrower,extrasensory,flareblitz,earthquake||252,,126,,126,4|||||]Rapidash|||flashfire|flareblitz,wildcharge,drillrun,poisonjab||252,,126,,126,4|||||" # noqa: E501 + + print(ConstantTeambuilder(team).yield_team()) + + assert ConstantTeambuilder(team).yield_team() == packed_team
parsing error on showdown-format teams without items Teambuilder class doesn't work with showdown-format teams when a Pokémon doesn't have items. Same team functioned properly when adding an item to each Pokémon. Log: ``` --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-21-ae950723727d> in <module> 10 team=opponent_team, 11 max_concurrent_battles=20, ---> 12 log_level=40, 13 ) C:\ProgramData\Anaconda3\lib\site-packages\poke_env\player\player.py in __init__(self, player_configuration, avatar, battle_format, log_level, max_concurrent_battles, server_configuration, start_listening, team) 111 self._team = team 112 elif isinstance(team, str): --> 113 self._team = ConstantTeambuilder(team) 114 else: 115 self._team = None C:\ProgramData\Anaconda3\lib\site-packages\poke_env\teambuilder\constant_teambuilder.py in __init__(self, team) 11 self.converted_team = team 12 else: ---> 13 mons = self.parse_showdown_team(team) 14 self.converted_team = self.join_team(mons) 15 C:\ProgramData\Anaconda3\lib\site-packages\poke_env\teambuilder\teambuilder.py in parse_showdown_team(team) 89 mon_info, item = line.split(" @ ") 90 current_mon.item = item.strip() ---> 91 split_mon_info = mon_info.split(" ") 92 93 if split_mon_info[-1] == "(M)": UnboundLocalError: local variable 'mon_info' referenced before assignment ``` Code that generated error: ``` opponent_team=""" Flareon Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe Hardy Nature - Flare Blitz - Superpower - Double-Edge - Iron Tail Ninetales Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe IVs: 0 Atk - Flamethrower - Extrasensory - Calm Mind - Dark Pulse Arcanine Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe - Flare Blitz - Wild Charge - Facade - Crunch Heatmor Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe - Flare Blitz - Body Slam - Night Slash - Stomping Tantrum Typhlosion Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe - Flamethrower - Extrasensory - Flare Blitz - Earthquake Rapidash Ability: Flash Fire EVs: 252 HP / 126 Def / 126 SpD / 4 Spe - Flare Blitz - Wild Charge - Drill Run - Poison Jab """ p2 = SimpleHeuristicsPlayer( battle_format='gen8nationaldexag', team=opponent_team, max_concurrent_battles=20, log_level=40, ) ```
0.0
8c0fbbde4587fd8ff984bc64ac1baab9b102de51
[ "unit_tests/teambuilder/test_constant_teambuilder.py::test_showdown_team_parsing_works_without_items" ]
[ "unit_tests/teambuilder/test_constant_teambuilder.py::test_constant_teambuilder_yields_packed", "unit_tests/teambuilder/test_constant_teambuilder.py::test_constant_teambuilder_yields_showdown" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-09-16 00:09:01+00:00
mit
2,751
htcondor__htmap-200
diff --git a/.travis.yml b/.travis.yml index 4cb014c..7a891ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,7 +16,6 @@ jobs: fast_finish: true install: - - pip install codecov - travis_retry docker build -t htmap-test --file docker/Dockerfile --build-arg HTCONDOR_VERSION --build-arg PYTHON_VERSION=${TRAVIS_PYTHON_VERSION} . script: diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 7dfda05..acedcfd 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -9,6 +9,8 @@ mkdir -p "$_condor_local_dir/lock" "$_condor_local_dir/log" "$_condor_local_dir/ # start condor condor_master +condor_version + # once the shared port daemon wakes up, use condor_who to wait for condor to stand up while [[ ! -s "${_condor_local_dir}/log/SharedPortLog" ]] do diff --git a/docs/source/dependencies.rst b/docs/source/dependencies.rst index 369ad43..35525ea 100644 --- a/docs/source/dependencies.rst +++ b/docs/source/dependencies.rst @@ -29,8 +29,9 @@ The built-in delivery methods are * ``docker`` - runs in a (possibly user-supplied) Docker container. * ``singularity`` - runs in a (possibly user-supplied) Singularity container. +* ``shared`` - runs with the same Python installation used submit-side. * ``assume`` - assumes that the dependencies have already been installed at the execute location. -* ``transplant`` - copy the user's Python installation to the execute node. +* ``transplant`` - copy the submit-side Python installation to the execute location. More details on each of these methods can be found below. @@ -71,8 +72,8 @@ At runtime: .. code-block:: python - htmap.settings['DELIVERY_METHOD'] = 'docker' - htmap.settings['DOCKER.IMAGE'] = "<repository>/<image>:<tag>" + htmap.settings["DELIVERY_METHOD"] = "docker" + htmap.settings["DOCKER.IMAGE"] = "<repository>/<image>:<tag>" In this mode, HTMap will run inside a Docker image that you provide. Remember that this Docker image needs to have the ``htmap`` module installed. @@ -119,8 +120,8 @@ At runtime: .. code-block:: python - htmap.settings['DELIVERY_METHOD'] = 'singularity' - htmap.settings['SINGULARITY.IMAGE'] = "<image>" + htmap.settings["DELIVERY_METHOD"] = "singularity" + htmap.settings["SINGULARITY.IMAGE"] = "<image>" In this mode, HTMap will run inside a Singularity image that you provide. Remember that this Singularity image needs to have the ``cloudpickle`` module installed. @@ -149,6 +150,37 @@ If you want to use your own Singularity image, just change the ``'SINGULARITY.IM If you get a ``stderr`` message from Singularity about a bind mount directory not existing, that's the problem. +Run With a Shared Python Installation +------------------------------------- + +In your ``~/.htmaprc`` file: + +.. code-block:: bash + + DELIVERY_METHOD = "shared" + +At runtime: + +.. code-block:: python + + htmap.settings["DELIVERY_METHOD"] = "shared" + +In this mode, HTMap will run your components using the same interpreter being +used submit-side. +This requires that that the submit-side Python interpreter be +"visible" from the execute location, which is usually done in one of two ways: + +1. The execute location **is** the submit location + (i.e., they are the same physical computer). +2. The Python installation is stored on a shared filesystem, such that submit + and execute can both see the same file paths. + +Either way, the practical requirement to use this delivery method is that the +path to the Python interpreter +(i.e., ``python -c "import sys, print(sys.executable)"``) +is the same both submit-side and execute-side. + + Assume Dependencies are Present ------------------------------- @@ -162,7 +194,7 @@ At runtime: .. code-block:: python - htmap.settings['DELIVERY_METHOD'] = 'assume' + htmap.settings["DELIVERY_METHOD"] = 'assume' In this mode, HTMap assumes that a Python installation with all Python dependencies is already present. This will almost surely require some additional setup by your HTCondor pool's administrators. @@ -183,7 +215,7 @@ At runtime: .. code-block:: python - htmap.settings['DELIVERY_METHOD'] = 'transplant' + htmap.settings["DELIVERY_METHOD"] = 'transplant' If you are running HTMap from a standalone Python install (like an Anaconda installation), you can use this delivery mechanism to transfer a copy of your entire Python install. diff --git a/docs/source/versions/v0_6_0.rst b/docs/source/versions/v0_6_0.rst new file mode 100644 index 0000000..f09b410 --- /dev/null +++ b/docs/source/versions/v0_6_0.rst @@ -0,0 +1,29 @@ +v0.6.0 +====== + +New Features +------------ + +* Add the ``shared`` delivery method, which supports HTCondor pools that use + shared filesystems to make Python installations available universally. + Issues: https://github.com/htcondor/htmap/issues/195 and https://github.com/htcondor/htmap/issues/198 + + +Changed/Deprecated Features +--------------------------- + + +Bug Fixes +--------- + + +Known Issues +------------ + +* Execution errors that result in the job being terminated but no output being + produced are still not handled entirely gracefully. Right now, the component + state will just show as ``ERRORED``, but there won't be an actual error report. +* Map component state may become corrupted when a map is manually vacated. + Force-removal may be needed to clean up maps if HTCondor and HTMap disagree + about the state of their components. + Issue: https://github.com/htcondor/htmap/issues/129 diff --git a/htmap/__init__.py b/htmap/__init__.py index 22617f8..cdd6842 100644 --- a/htmap/__init__.py +++ b/htmap/__init__.py @@ -45,7 +45,7 @@ from .maps import ( from .holds import ComponentHold from .errors import ComponentError from .state import ComponentStatus -from .options import MapOptions, register_delivery_mechanism +from .options import MapOptions, register_delivery_method from .management import ( status, status_json, diff --git a/htmap/options.py b/htmap/options.py index 7e8df3f..83713d6 100644 --- a/htmap/options.py +++ b/htmap/options.py @@ -228,7 +228,7 @@ def create_submit_object_and_itemdata( return sub, itemdata -def register_delivery_mechanism( +def register_delivery_method( name: str, options_func: Callable[[str, Path], dict], setup_func: Optional[Callable[[str, Path], None]] = None, @@ -332,7 +332,7 @@ def _get_base_descriptors_for_assume( } -register_delivery_mechanism( +register_delivery_method( 'assume', options_func = _get_base_descriptors_for_assume, ) @@ -351,12 +351,33 @@ def _get_base_descriptors_for_docker( } -register_delivery_mechanism( +register_delivery_method( 'docker', options_func = _get_base_descriptors_for_docker, ) +def _get_base_descriptors_for_shared( + tag: str, + map_dir: Path, +) -> dict: + return { + 'universe': 'vanilla', + 'executable': Path(sys.executable).absolute().as_posix(), + 'transfer_executable': 'False', + 'arguments': f'{names.RUN_SCRIPT} $(component)', + 'transfer_input_files': [ + (map_dir / names.RUN_SCRIPT).as_posix(), + ], + } + + +register_delivery_method( + 'shared', + options_func = _get_base_descriptors_for_shared, +) + + def _get_base_descriptors_for_singularity( tag: str, map_dir: Path, @@ -373,7 +394,7 @@ def _get_base_descriptors_for_singularity( } -register_delivery_mechanism( +register_delivery_method( 'singularity', options_func = _get_base_descriptors_for_singularity, ) @@ -451,7 +472,7 @@ def _get_transplant_hash(pip_freeze_output: bytes) -> str: return h.hexdigest() -register_delivery_mechanism( +register_delivery_method( 'transplant', options_func = _get_base_descriptors_for_transplant, setup_func = _run_delivery_setup_for_transplant,
htcondor/htmap
ddba6dbdf6700eb7ab2c2b3bbf88ff4fe06171d7
diff --git a/tests/conftest.py b/tests/conftest.py index db9f9b8..16f377a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -26,8 +26,8 @@ from htmap._startup import ensure_htmap_dir_exists # start with base settings (ignore user settings for tests) htmap.settings.replace(BASE_SETTINGS) -htmap.settings['DELIVERY_METHOD'] = 'assume' # assume is the default for testing -htmap.settings['WAIT_TIME'] = 0.01 +htmap.settings['DELIVERY_METHOD'] = 'assume' # assume is the default for all tests that aren't parametric +htmap.settings['WAIT_TIME'] = 0.1 htmap.settings['MAP_OPTIONS.request_memory'] = '10MB' SETTINGS = copy(htmap.settings) @@ -49,18 +49,11 @@ def delivery_methods(delivery_method, reset_settings): htmap.settings['DELIVERY_METHOD'] = delivery_method [email protected](scope = 'function', autouse = True) -def set_htmap_dir(tmpdir_factory, reset_settings): - path = Path(tmpdir_factory.mktemp('htmap_dir')) - htmap.settings['HTMAP_DIR'] = path - ensure_htmap_dir_exists() - - def pytest_addoption(parser): parser.addoption( "--delivery", nargs = "+", - default = ['assume'], + default = ['assume'], # assume is the default for parametric delivery testing ) @@ -72,6 +65,24 @@ def pytest_generate_tests(metafunc): ) +MAP_DIRS = [] + + [email protected](scope = 'function', autouse = True) +def set_htmap_dir(tmpdir_factory): + map_dir = Path(tmpdir_factory.mktemp('htmap_dir')) + MAP_DIRS.append(map_dir) + htmap.settings['HTMAP_DIR'] = map_dir + ensure_htmap_dir_exists() + + [email protected](scope = 'session', autouse = True) +def cleanup(): + for map_dir in MAP_DIRS: + htmap.settings['HTMAP_DIR'] = map_dir + htmap.clean(all = True) + + @pytest.fixture(scope = 'session') def doubler(): def doubler(x): diff --git a/tests/integration/test_errors_and_holds.py b/tests/integration/test_errors_and_holds.py index 6064281..25f1507 100644 --- a/tests/integration/test_errors_and_holds.py +++ b/tests/integration/test_errors_and_holds.py @@ -34,7 +34,9 @@ def hold_before_error(): assert map.component_statuses == [htmap.ComponentStatus.HELD, htmap.ComponentStatus.ERRORED] - return map + yield map + + map.remove() @pytest.fixture(scope = 'function') @@ -49,7 +51,9 @@ def error_before_hold(): assert map.component_statuses == [htmap.ComponentStatus.ERRORED, htmap.ComponentStatus.HELD] - return map + yield map + + map.remove() def test_can_get_error_if_hold_in_front(hold_before_error): diff --git a/tests/integration/test_held_components.py b/tests/integration/test_held_components.py index 93d1cdb..94f0685 100644 --- a/tests/integration/test_held_components.py +++ b/tests/integration/test_held_components.py @@ -20,65 +20,47 @@ import pytest import htmap -def test_waiting_on_held_component_raises(mapped_doubler): [email protected](scope = 'function') +def map_with_held_component(mapped_doubler): m = mapped_doubler.map(range(1)) m.hold() m.wait(holds_ok = True) - with pytest.raises(htmap.exceptions.MapComponentHeld): - m.wait(timeout = 180) + yield m + m.remove() -def test_accessing_held_component_raises(mapped_doubler): - m = mapped_doubler.map(range(1)) - m.hold() - - m.wait(holds_ok = True) +def test_waiting_on_held_component_raises(map_with_held_component): with pytest.raises(htmap.exceptions.MapComponentHeld): - m[0] + map_with_held_component.wait(timeout = 180) -def test_getting_held_component_raises(mapped_doubler): - m = mapped_doubler.map(range(1)) - m.hold() - - m.wait(holds_ok = True) - +def test_accessing_held_component_raises(map_with_held_component): with pytest.raises(htmap.exceptions.MapComponentHeld): - m.get(0) + map_with_held_component[0] -def test_iterating_over_held_component_raises(mapped_doubler): - m = mapped_doubler.map(range(1)) - m.hold() - - m.wait(holds_ok = True) - +def test_getting_held_component_raises(map_with_held_component): with pytest.raises(htmap.exceptions.MapComponentHeld): - list(m) - - -def test_held_component_shows_up_in_hold_reasons(mapped_doubler): - m = mapped_doubler.map(range(1)) - m.hold() + map_with_held_component.get(0) - m.wait(holds_ok = True) - - assert isinstance(m.holds[0], htmap.ComponentHold) +def test_iterating_over_held_component_raises(map_with_held_component): + with pytest.raises(htmap.exceptions.MapComponentHeld): + list(map_with_held_component) -def test_held_then_released_component_not_in_hold_reasons(mapped_doubler): - m = mapped_doubler.map(range(1)) - m.hold() - m.wait(holds_ok = True) +def test_held_component_shows_up_in_hold_reasons(map_with_held_component): + assert isinstance(map_with_held_component.holds[0], htmap.ComponentHold) - assert isinstance(m.holds[0], htmap.ComponentHold) - m.release() [email protected](60) +def test_held_then_released_component_not_in_hold_reasons(map_with_held_component): + assert isinstance(map_with_held_component.holds[0], htmap.ComponentHold) - time.sleep(5) # wait for htcondor to write events + map_with_held_component.release() - assert len(m.holds) == 0 + while not len(map_with_held_component.holds) == 0: + time.sleep(.1) diff --git a/tests/unit/test_base_descriptors.py b/tests/unit/test_base_descriptors.py index bbdcc52..379b5a8 100644 --- a/tests/unit/test_base_descriptors.py +++ b/tests/unit/test_base_descriptors.py @@ -18,12 +18,12 @@ import pytest from pathlib import Path import htmap -from htmap.options import get_base_descriptors, register_delivery_mechanism, unregister_delivery_mechanism +from htmap.options import get_base_descriptors, register_delivery_method, unregister_delivery_mechanism @pytest.fixture(scope = 'module', autouse = True) def add_null_delivery(): - register_delivery_mechanism('null', lambda tag, map_dir: {}) + register_delivery_method('null', lambda tag, map_dir: {}) yield
htmap run.py uses wrong python interpreter on execute node **Describe the bug** The `run.py` script executes just using `python3` as the interpreter on the execute node. In most cases this will evaluate to `/usr/bin/python3`, which may not be the interpreter in which `htmap` was executed. The actual error ends up being ```pytb ModuleNotFoundError: No module named 'cloudpickle' ``` since `cloudpickle` isn't installed system wide. **To Reproduce** This can be reproduced by creating a conda environment that includes `htmap`, then executing the basic `double` example from the docs: ```console conda create --name htmap-test --yes --quiet python=3.8 htmap conda activate htmap python test_htmap.py ``` where `test_htmap.py` is : ```python #!/usr/bin/env python import htmap htmap.settings['DELIVERY_METHOD'] = 'assume' def double(x): return 2 * x doubled = list(htmap.map(double, range(10))) print(doubled) ``` **Expected behavior** The `run.py` script that runs on the execute node is executed using the same interpreter as was used to execute `htmap.map()` in the first place. **Software Versions:** ```console $ python -c "import htcondor, htmap; print(htcondor.version()); print(htmap.version())" $CondorVersion: 8.9.5 Feb 04 2020 $ HTMap version 0.5.0 $ condor_version $CondorVersion: 8.9.5 Feb 04 2020 $ $CondorPlatform: X86_64-CentOS_6.10 $ $ cat /etc/os-release NAME="Scientific Linux" VERSION="7.7 (Nitrogen)" ID="scientific" ID_LIKE="rhel centos fedora" VERSION_ID="7.7" PRETTY_NAME="Scientific Linux 7.7 (Nitrogen)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:scientificlinux:scientificlinux:7.7:GA" HOME_URL="http://www.scientificlinux.org//" BUG_REPORT_URL="mailto:[email protected]" REDHAT_BUGZILLA_PRODUCT="Scientific Linux 7" REDHAT_BUGZILLA_PRODUCT_VERSION=7.7 REDHAT_SUPPORT_PRODUCT="Scientific Linux" REDHAT_SUPPORT_PRODUCT_VERSION="7.7" $ cat /proc/version Linux version 3.10.0-1062.12.1.el7.x86_64 ([email protected]) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) ) #1 SMP Wed Feb 5 09:10:55 CST 2020 ``` **Screenshots** If applicable, add screenshots to help explain your problem. **Additional context** Problem exhibits using the `igwn-py37-testing` conda environment available on OASIS under `/cvmfs/oasis.opensciencegrid.org/ligo/sw/conda`
0.0
ddba6dbdf6700eb7ab2c2b3bbf88ff4fe06171d7
[ "tests/unit/test_base_descriptors.py::test_job_batch_name_is_tag" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-24 15:35:37+00:00
apache-2.0
2,752
html5lib__html5lib-python-259
diff --git a/html5lib/treebuilders/etree.py b/html5lib/treebuilders/etree.py index d394148..4d12bd4 100644 --- a/html5lib/treebuilders/etree.py +++ b/html5lib/treebuilders/etree.py @@ -100,6 +100,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False): node.parent = self def removeChild(self, node): + self._childNodes.remove(node) self._element.remove(node._element) node.parent = None
html5lib/html5lib-python
2d376737a6246ebb38a79600a7fe75abd923cf3e
diff --git a/html5lib/tests/test_parser2.py b/html5lib/tests/test_parser2.py index 0ec5b04..b7a92fd 100644 --- a/html5lib/tests/test_parser2.py +++ b/html5lib/tests/test_parser2.py @@ -7,7 +7,7 @@ import io from . import support # noqa from html5lib.constants import namespaces -from html5lib import parse, HTMLParser +from html5lib import parse, parseFragment, HTMLParser # tests that aren't autogenerated from text files @@ -88,3 +88,8 @@ def test_debug_log(): expected[i] = tuple(log) assert parser.log == expected + + +def test_no_duplicate_clone(): + frag = parseFragment("<b><em><foo><foob><fooc><aside></b></em>") + assert len(frag) == 2
etree treewalker infinite loop This goes into an infinite loop: ```python import html5lib frag = html5lib.parseFragment("<b><em><foo><foob><fooc><aside></b></em>") walker = html5lib.getTreeWalker("etree") print list(walker(frag)) ```
0.0
2d376737a6246ebb38a79600a7fe75abd923cf3e
[ "html5lib/tests/test_parser2.py::test_no_duplicate_clone" ]
[ "html5lib/tests/test_parser2.py::test_assertDoctypeCloneable", "html5lib/tests/test_parser2.py::test_line_counter", "html5lib/tests/test_parser2.py::test_namespace_html_elements_0_dom", "html5lib/tests/test_parser2.py::test_namespace_html_elements_1_dom", "html5lib/tests/test_parser2.py::test_namespace_html_elements_0_etree", "html5lib/tests/test_parser2.py::test_namespace_html_elements_1_etree", "html5lib/tests/test_parser2.py::test_unicode_file", "html5lib/tests/test_parser2.py::test_duplicate_attribute", "html5lib/tests/test_parser2.py::test_debug_log" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2016-05-28 21:05:44+00:00
mit
2,753
huggingface__transformers-30192
diff --git a/docs/source/en/perf_infer_gpu_one.md b/docs/source/en/perf_infer_gpu_one.md index 64583e4ba..de49d4427 100644 --- a/docs/source/en/perf_infer_gpu_one.md +++ b/docs/source/en/perf_infer_gpu_one.md @@ -194,6 +194,7 @@ For now, Transformers supports SDPA inference and training for the following arc * [Bert](https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertModel) * [Cohere](https://huggingface.co/docs/transformers/model_doc/cohere#transformers.CohereModel) * [Dbrx](https://huggingface.co/docs/transformers/model_doc/dbrx#transformers.DbrxModel) +* [Dpr](https://huggingface.co/docs/transformers/model_doc/dpr#transformers.DprReader) * [Falcon](https://huggingface.co/docs/transformers/model_doc/falcon#transformers.FalconModel) * [Gemma](https://huggingface.co/docs/transformers/model_doc/gemma#transformers.GemmaModel) * [GPTBigCode](https://huggingface.co/docs/transformers/model_doc/gpt_bigcode#transformers.GPTBigCodeModel) diff --git a/examples/pytorch/speech-recognition/README.md b/examples/pytorch/speech-recognition/README.md index b9cab9513..4990219f4 100644 --- a/examples/pytorch/speech-recognition/README.md +++ b/examples/pytorch/speech-recognition/README.md @@ -368,6 +368,7 @@ python run_speech_recognition_seq2seq.py \ --dataset_name="mozilla-foundation/common_voice_11_0" \ --dataset_config_name="hi" \ --language="hindi" \ + --task="transcribe" \ --train_split_name="train+validation" \ --eval_split_name="test" \ --max_steps="5000" \ @@ -384,12 +385,10 @@ python run_speech_recognition_seq2seq.py \ --save_steps="1000" \ --generation_max_length="225" \ --preprocessing_num_workers="16" \ - --length_column_name="input_length" \ --max_duration_in_seconds="30" \ --text_column_name="sentence" \ --freeze_feature_encoder="False" \ --gradient_checkpointing \ - --group_by_length \ --fp16 \ --overwrite_output_dir \ --do_train \ @@ -399,7 +398,8 @@ python run_speech_recognition_seq2seq.py \ ``` On a single V100, training should take approximately 8 hours, with a final cross-entropy loss of **1e-4** and word error rate of **32.6%**. -If training on a different language, you should be sure to change the `language` argument. The `language` argument should be omitted for English speech recognition. +If training on a different language, you should be sure to change the `language` argument. The `language` and `task` +arguments should be omitted for English speech recognition. #### Multi GPU Whisper Training The following example shows how to fine-tune the [Whisper small](https://huggingface.co/openai/whisper-small) checkpoint on the Hindi subset of [Common Voice 11](https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0) using 2 GPU devices in half-precision: @@ -410,6 +410,7 @@ torchrun \ --dataset_name="mozilla-foundation/common_voice_11_0" \ --dataset_config_name="hi" \ --language="hindi" \ + --task="transcribe" \ --train_split_name="train+validation" \ --eval_split_name="test" \ --max_steps="5000" \ @@ -425,12 +426,10 @@ torchrun \ --save_steps="1000" \ --generation_max_length="225" \ --preprocessing_num_workers="16" \ - --length_column_name="input_length" \ --max_duration_in_seconds="30" \ --text_column_name="sentence" \ --freeze_feature_encoder="False" \ --gradient_checkpointing \ - --group_by_length \ --fp16 \ --overwrite_output_dir \ --do_train \ diff --git a/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py b/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py index 3a596e2cb..f352954d8 100755 --- a/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py +++ b/examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py @@ -119,17 +119,16 @@ class ModelArguments: ) forced_decoder_ids: List[List[int]] = field( default=None, - metadata={ + metadata={"help": "Deprecated. Please use the `language` and `task` arguments instead."}, + ) + suppress_tokens: List[int] = field( + default=None, metadata={ "help": ( - "A list of pairs of integers which indicates a mapping from generation indices to token indices " - "that will be forced before sampling. For example, [[0, 123]] means the first generated token " - "will always be a token of index 123." + "Deprecated. The use of `suppress_tokens` should not be required for the majority of fine-tuning examples." + "Should you need to use `suppress_tokens`, please manually update them in the fine-tuning script directly." ) }, ) - suppress_tokens: List[int] = field( - default=None, metadata={"help": "A list of tokens that will be suppressed at generation."} - ) apply_spec_augment: bool = field( default=False, metadata={ @@ -400,8 +399,6 @@ def main(): trust_remote_code=model_args.trust_remote_code, ) - config.update({"forced_decoder_ids": model_args.forced_decoder_ids, "suppress_tokens": model_args.suppress_tokens}) - # SpecAugment for whisper models if getattr(config, "model_type", None) == "whisper": config.update({"apply_spec_augment": model_args.apply_spec_augment}) @@ -440,9 +437,35 @@ def main(): model.freeze_encoder() model.model.encoder.gradient_checkpointing = False - if data_args.language is not None: - # We only need to set the task id when the language is specified (i.e. in a multilingual setting) + if hasattr(model.generation_config, "is_multilingual") and model.generation_config.is_multilingual: + # We only need to set the language and task ids in a multilingual setting tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task) + model.generation_config.update( + **{ + "language": data_args.language, + "task": data_args.task, + } + ) + elif data_args.language is not None: + raise ValueError( + "Setting language token for an English-only checkpoint is not permitted. The language argument should " + "only be set for multilingual checkpoints." + ) + + # TODO (Sanchit): deprecate these arguments in v4.41 + if model_args.forced_decoder_ids is not None: + logger.warning( + "The use of `forced_decoder_ids` is deprecated and will be removed in v4.41." + "Please use the `language` and `task` arguments instead" + ) + model.generation_config.forced_decoder_ids = model_args.forced_decoder_ids + + if model_args.suppress_tokens is not None: + logger.warning( + "The use of `suppress_tokens` is deprecated and will be removed in v4.41." + "Should you need `suppress_tokens`, please manually set them in the fine-tuning script." + ) + model.generation_config.suppress_tokens = model_args.suppress_tokens # 6. Resample speech dataset if necessary dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate diff --git a/src/transformers/image_utils.py b/src/transformers/image_utils.py index e4a55b345..7d71fc982 100644 --- a/src/transformers/image_utils.py +++ b/src/transformers/image_utils.py @@ -320,7 +320,7 @@ def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = # Try to load as base64 try: - b64 = base64.b64decode(image, validate=True) + b64 = base64.decodebytes(image.encode()) image = PIL.Image.open(BytesIO(b64)) except Exception as e: raise ValueError( diff --git a/src/transformers/models/dpr/modeling_dpr.py b/src/transformers/models/dpr/modeling_dpr.py index 0a45ec752..928f2b931 100644 --- a/src/transformers/models/dpr/modeling_dpr.py +++ b/src/transformers/models/dpr/modeling_dpr.py @@ -142,6 +142,8 @@ class DPRReaderOutput(ModelOutput): class DPRPreTrainedModel(PreTrainedModel): + _supports_sdpa = True + def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): diff --git a/src/transformers/models/grounding_dino/modeling_grounding_dino.py b/src/transformers/models/grounding_dino/modeling_grounding_dino.py index 83009c925..da8dd29a5 100644 --- a/src/transformers/models/grounding_dino/modeling_grounding_dino.py +++ b/src/transformers/models/grounding_dino/modeling_grounding_dino.py @@ -2113,7 +2113,9 @@ class GroundingDinoModel(GroundingDinoPreTrainedModel): ) # Create text backbone - self.text_backbone = AutoModel.from_config(config.text_config, add_pooling_layer=False) + self.text_backbone = AutoModel.from_config( + config.text_config, add_pooling_layer=False, attn_implementation=config._attn_implementation + ) self.text_projection = nn.Linear(config.text_config.hidden_size, config.d_model) if config.embedding_init_target or not config.two_stage:
huggingface/transformers
aafa7ce72b65c730788c122a72a974e464409e9a
diff --git a/tests/utils/test_image_utils.py b/tests/utils/test_image_utils.py index d6bc9a375..f360c4bb8 100644 --- a/tests/utils/test_image_utils.py +++ b/tests/utils/test_image_utils.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import codecs import os import tempfile import unittest @@ -544,6 +545,23 @@ class LoadImageTester(unittest.TestCase): self.assertEqual(img_arr.shape, (64, 32, 3)) + def test_load_img_base64_encoded_bytes(self): + try: + tmp_file = tempfile.mktemp() + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_2.txt", f + ) + + with codecs.open(tmp_file, encoding="unicode_escape") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (256, 256, 3)) + def test_load_img_rgba(self): # we use revision="refs/pr/1" until the PR is merged # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1
Image classification pipeline fails with base64.encodebytes() input ### System Info transformers - 4.39.1 python 3.10.11 platform - ubuntu 22.04 ### Who can help? _No response_ ### Information - [ ] The official example scripts - [X] My own modified scripts ### Tasks - [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...) - [ ] My own task or dataset (give details below) ### Reproduction ``` python from PIL import Image import base64 from io import BytesIO from transformers import AutoModelForImageClassification, AutoFeatureExtractor model = AutoModelForImageClassification.from_pretrained("microsoft/resnet-18") tokenizer = AutoFeatureExtractor.from_pretrained("microsoft/resnet-18") tr_model = {"model": model, "image_processor": tokenizer} vision_model = transformers.pipeline( task="image-classification", model=model, image_processor=tokenizer ) buffered = BytesIO() im = torch.rand((256, 256,3)) image = Image.fromarray(im.numpy().astype('uint8'), 'RGB') image.save(buffered, format="JPEG") img_str1 = base64.b64encode(buffered.getvalue()).decode("utf-8") pred1 = vision_model.predict(img_str1) img_str2 = base64.encodebytes(buffered.getvalue()).decode("utf-8") pred2 = vision_model.predict(img_str2)` ``` results in this error: Traceback (most recent call last): File "/home/azureuser/workspace/AzureMlCli/test_oss.py", line 22, in <module> pred2 = vision_model.predict(img_str2) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/pipelines/base.py", line 921, in predict return self(X) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/pipelines/image_classification.py", line 158, in __call__ return super().__call__(images, **kwargs) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/pipelines/base.py", line 1162, in __call__ return self.run_single(inputs, preprocess_params, forward_params, postprocess_params) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/pipelines/base.py", line 1168, in run_single model_inputs = self.preprocess(inputs, **preprocess_params) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/pipelines/image_classification.py", line 161, in preprocess image = load_image(image, timeout=timeout) File "/anaconda/envs/vision_finetune/lib/python3.10/site-packages/transformers/image_utils.py", line 326, in load_image raise ValueError( ValueError: Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAEAAQADASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5/ooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAC iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKK KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooo oAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiig AooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//2Q== . Failed with Non-base64 digit found Image encoded with b64encode is successful, but encodebytes results in the above error. ### Expected behavior Image classification pipeline works well when input is given in base64.base64encode() format but fails with base64.encodebytes() format. Shouldn't the pipeline work on both the input formats?
0.0
aafa7ce72b65c730788c122a72a974e464409e9a
[ "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_base64_encoded_bytes" ]
[ "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_center_crop_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_center_crop_image", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_center_crop_tensor", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_array_to_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_array_to_image", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_image_to_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_image_to_image", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_tensor_to_image", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_conversion_torch_to_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_make_list_of_images_numpy", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_make_list_of_images_torch", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_normalize_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_normalize_image", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_normalize_tensor", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_resize_image_and_array", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_resize_image_and_array_non_default_to_square", "tests/utils/test_image_utils.py::ImageFeatureExtractionTester::test_resize_tensor", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_base64", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_base64_prefix", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_exif_transpose", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_l", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_la", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_local", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_rgba", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_url", "tests/utils/test_image_utils.py::LoadImageTester::test_load_img_url_timeout", "tests/utils/test_image_utils.py::UtilFunctionTester::test_get_channel_dimension_axis", "tests/utils/test_image_utils.py::UtilFunctionTester::test_get_image_size", "tests/utils/test_image_utils.py::UtilFunctionTester::test_infer_channel_dimension" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-11 16:30:34+00:00
apache-2.0
2,754
hugovk__pypistats-41
diff --git a/pypistats/cli.py b/pypistats/cli.py index 092f9b7..8eb62cd 100644 --- a/pypistats/cli.py +++ b/pypistats/cli.py @@ -243,7 +243,7 @@ def _month(yyyy_mm): """Helper to return start_date and end_date of a month as yyyy-mm-dd""" year, month = map(int, yyyy_mm.split("-")) first = date(year, month, 1) - last = date(year, month + 1, 1) - relativedelta(days=1) + last = first + relativedelta(months=1) - relativedelta(days=1) return str(first), str(last)
hugovk/pypistats
f6a9e33aaf41d1b08f6490febe1f542c1e093271
diff --git a/tests/test_cli.py b/tests/test_cli.py index 22308f6..f486b7c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -28,6 +28,17 @@ class TestCli(unittest.TestCase): self.assertEqual(first, "2018-07-01") self.assertEqual(last, "2018-07-31") + def test__month_12(self): + # Arrange + yyyy_mm = "2018-12" + + # Act + first, last = cli._month(yyyy_mm) + + # Assert + self.assertEqual(first, "2018-12-01") + self.assertEqual(last, "2018-12-31") + @freeze_time("2018-09-25") def test__last_month(self): # Arrange
ValueError: month must be in 1..12 ```console $ pypistats python_minor pylast -m 2018-11 | category | percent | downloads | |----------|--------:|----------:| | 2.7 | 48.62% | 2,307 | | 3.6 | 31.63% | 1,501 | | null | 7.31% | 347 | | 3.7 | 6.91% | 328 | | 3.5 | 4.85% | 230 | | 3.4 | 0.59% | 28 | | 3.3 | 0.08% | 4 | | Total | | 4,745 | $ pypistats python_minor pylast -m 2018-12 Traceback (most recent call last): File "/usr/local/bin/pypistats", line 11, in <module> load_entry_point('pypistats', 'console_scripts', 'pypistats')() File "/Users/hugo/github/pypistats/pypistats/cli.py", line 266, in main args.start_date, args.end_date = _month(args.month) File "/Users/hugo/github/pypistats/pypistats/cli.py", line 246, in _month last = date(year, month + 1, 1) - relativedelta(days=1) ValueError: month must be in 1..12 $ pypistats python_minor pylast -m 2017-12 Traceback (most recent call last): File "/usr/local/bin/pypistats", line 11, in <module> load_entry_point('pypistats', 'console_scripts', 'pypistats')() File "/Users/hugo/github/pypistats/pypistats/cli.py", line 266, in main args.start_date, args.end_date = _month(args.month) File "/Users/hugo/github/pypistats/pypistats/cli.py", line 246, in _month last = date(year, month + 1, 1) - relativedelta(days=1) ValueError: month must be in 1..12 ```
0.0
f6a9e33aaf41d1b08f6490febe1f542c1e093271
[ "tests/test_cli.py::TestCli::test__month_12" ]
[ "tests/test_cli.py::TestCli::test__valid_yyyy_mm_dd", "tests/test_cli.py::TestCli::test__month", "tests/test_cli.py::TestCli::test__define_format_json", "tests/test_cli.py::TestCli::test__define_format_markdown", "tests/test_cli.py::TestCli::test__valid_yyyy_mm_invalid2", "tests/test_cli.py::TestCli::test__valid_yyyy_mm", "tests/test_cli.py::TestCli::test__valid_yyyy_mm_invalid", "tests/test_cli.py::TestCli::test__valid_yyyy_mm_dd_invalid2", "tests/test_cli.py::TestCli::test__valid_yyyy_mm_dd_invalid", "tests/test_cli.py::TestCli::test__last_month", "tests/test_cli.py::TestCli::test__define_format_default", "tests/test_cli.py::TestCli::test__define_format_json_flag" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-12-30 12:50:57+00:00
mit
2,755
hydrosquall__tiingo-python-107
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 519b6b0..bff2266 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -117,3 +117,12 @@ To regenerate fixture remove it from tests/fixtures and run tests again:: $ rm tests/fixtures/NAME.yaml $ py.test + +In order for py.test to run, you will have had to create an environment variable containing a valid tiingo API key so that the test runner can make a valid api call. One way to do that is to:: + + $ export TIINGO_API_KEY='...insert api key here...' + +However, now this api key will become embedded in the test fixture file that is created per the prior procedure. In order to remove this api key from the new test fixtures, run the following from the top level directory:: + + $ ./tools/api_key_tool.py + diff --git a/tools/__init__.py b/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/api_key_tool.py b/tools/api_key_tool.py new file mode 100755 index 0000000..3d92246 --- /dev/null +++ b/tools/api_key_tool.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +from __future__ import print_function +import glob +import re +import argparse + +fixtures_directory = 'tests/fixtures/' +zero_api_regex = r'(\[Token )0{40}(\])' +real_api_regex = r'(\[Token ).{40}(\])' +zero_token_string = '[Token ' + 40 * '0' + ']' + + +def has_api_key(file): + """ + Detect whether the file contains an api key in the Token object that is not 40*'0'. + See issue #86. + :param file: path-to-file to check + :return: boolean + """ + f = open(file, 'r') + text = f.read() + if re.search(real_api_regex, text) is not None and \ + re.search(zero_api_regex, text) is None: + return True + return False + + +def remove_api_key(file): + """ + Change the api key in the Token object to 40*'0'. See issue #86. + :param file: path-to-file to change + """ + with open(file, 'r') as fp: + text = fp.read() + text = re.sub(real_api_regex, zero_token_string, text) + with open(file, 'w') as fp: + fp.write(text) + return + + +def main(path): + if path[-1] != '/': + raise ValueError('Final character in path must be /.') + n_files_changed = 0 + for filename in glob.glob(path+'*.yaml'): + if has_api_key(filename): + remove_api_key(filename) + n_files_changed += 1 + print("Changed {} files.".format(n_files_changed)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("path", help="path to test fixtures", + nargs='?', default=fixtures_directory) + args = parser.parse_args() + main(args.path)
hydrosquall/tiingo-python
2fb5a0d97711d8428cf475858513e741b11c6348
diff --git a/tests/test_api_key_tools.py b/tests/test_api_key_tools.py new file mode 100644 index 0000000..43223f9 --- /dev/null +++ b/tests/test_api_key_tools.py @@ -0,0 +1,51 @@ +# +# Test setup based on https://gist.github.com/odyniec/d4ea0959d4e0ba17a980 +# + +import shutil, tempfile +from os import path +from unittest import TestCase +from tools.api_key_tool import remove_api_key, has_api_key + + +class TestAPIKeyTools(TestCase): + + def setUp(self): + self.test_dir = tempfile.mkdtemp() + f = open(path.join(self.test_dir, 'test.yaml'), 'w') + txt = '''interactions: + - request: + body: null + headers: + Accept: ['*/*'] + Accept-Encoding: ['gzip, deflate'] + Authorization: [Token a00000000000000000000a00000000000000000a] + Connection: [keep-alive] + Content-Type: [application/json] + User-Agent: [tiingo-python-client 0.5.0] + method: GET + uri: https://api.tiingo.com/tiingo/daily/GOOGL/prices?format=json&resampleFreq=daily + response: + body: {string: '[{"adjClose":1037.29,"adjHigh":1044.65,"adjLow":1026.05,"adjOpen":1031.47,"adjVolume":1644794,"close":1037.29,"date":"2018-04-12T00:00:00+00:00","divCash":0.0,"high":1044.65,"low":1026.05,"open":1031.47,"splitFactor":1.0,"volume":1644794}]'} + headers: + Allow: ['GET, HEAD, OPTIONS'] + Content-Length: ['239'] + Content-Type: [application/json] + Date: ['Fri, 13 Apr 2018 02:42:05 GMT'] + Server: [nginx/1.10.1] + Vary: ['Accept, Cookie'] + X-Frame-Options: [SAMEORIGIN] + status: {code: 200, message: OK} + version: 1 + ''' + f.write(txt) + + def tearDown(self): + shutil.rmtree(self.test_dir) + + def test_key_detector(self): + assert has_api_key(path.join(self.test_dir, 'test.yaml')) is True + + def test_key_remover(self): + remove_api_key(path.join(self.test_dir, 'test.yaml')) + assert has_api_key(path.join(self.test_dir, 'test.yaml')) is False
Create Scripts to Detect/Remove API Keys from Fixtures @dcwtx carefully described the process of removing the user's API keys from generated test fixtures in the following comment: https://github.com/hydrosquall/tiingo-python/pull/84#issue-181374833 We should produce 2 scripts, and include them in a `tools/` folder under this repository. Feel free to tackle just 1 if you'd like to help with this issue. 1. a script (python or shell) that can search for API keys in the generated fixture files, and return false if any of those API keys are not (`30 * 0`)o 2. a script (python or shell) that can replace the users's API key in generated fixtures with `30 * 0`. 3. Some documentation in each script about how to use it In the absence of other names, something like `api_key_detector` and `api_key_remover` will do. Lastly, we should mention where to find / how to use these tools in `CONTRIBUTING.md`.
0.0
2fb5a0d97711d8428cf475858513e741b11c6348
[ "tests/test_api_key_tools.py::TestAPIKeyTools::test_key_detector", "tests/test_api_key_tools.py::TestAPIKeyTools::test_key_remover" ]
[]
{ "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false }
2018-04-25 02:42:47+00:00
mit
2,756
hylang__hy-2326
diff --git a/NEWS.rst b/NEWS.rst index 39fb71f6..d4d8f62b 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -10,6 +10,12 @@ Bug Fixes * Fixed a bug with `python -O` where assertions were still partly evaluated. +Misc. Improvements +------------------------------ +* `hyc` now requires a command-line argument. +* `hyc` prints each path it writes bytecode to, and its messages now + go to standard error instead of standard output. + 0.24.0 (released 2022-06-23) ============================== diff --git a/docs/cli.rst b/docs/cli.rst index 9ed1ab84..e1e34cfb 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -59,56 +59,24 @@ Command Line Options Print the Hy version number and exit. -.. _hyc: - -hyc ---- - -Command Line Options -^^^^^^^^^^^^^^^^^^^^ - -.. cmdoption:: file[, fileN] - - Compile Hy code to Python bytecode. For example, save the - following code as ``hyname.hy``: - - .. code-block:: hy - - (defn hy-hy [name] - (print (+ "Hy " name "!"))) - - (hy-hy "Afroman") - - Then run: - - .. code-block:: bash - - $ hyc hyname.hy - $ python hyname.pyc - Hy Afroman! - - .. _hy2py: hy2py ----- -.. versionadded:: 0.10.1 +``hy2py`` is a program to convert Hy source code into Python source code. Use ``hy2py --help`` for usage instructions. It can take its input from standard input or from a filename provided as a command-line argument. The result is written to standard output. -Command Line Options -^^^^^^^^^^^^^^^^^^^^ + .. warning:: + ``hy2py`` can execute arbitrary code. Don't give it untrusted input. -.. cmdoption:: -s - --with-source - Show the parsed source structure. -.. cmdoption:: -a - --with-ast +.. _hyc: - Show the generated AST. +hyc +--- -.. cmdoption:: -np - --without-python +``hyc`` is a program to compile files of Hy code into Python bytecode. Use ``hyc --help`` for usage instructions. The generated bytecode files are named and placed according to the usual scheme of your Python executable, as indicated by :py:func:`importlib.util.cache_from_source`. - Do not show the Python code generated from the AST. + .. warning:: + ``hyc`` can execute arbitrary code. Don't give it untrusted input. diff --git a/docs/tutorial.rst b/docs/tutorial.rst index 9294abf9..03f25c76 100644 --- a/docs/tutorial.rst +++ b/docs/tutorial.rst @@ -74,7 +74,7 @@ and return code to be executed at run-time. Comments start with a ``;`` character and continue till the end of the line. A comment is functionally equivalent to whitespace. :: - (print (** 2 64)) ; Max 64-bit unsigned integer value + (setv password "susan") ; My daughter's name Although ``#`` isn't a comment character in Hy, a Hy program can begin with a `shebang line <https://en.wikipedia.org/wiki/Shebang_(Unix)>`_, which Hy itself diff --git a/hy/cmdline.py b/hy/cmdline.py index 446bb1c1..76f905c4 100644 --- a/hy/cmdline.py +++ b/hy/cmdline.py @@ -721,44 +721,27 @@ def hy_main(): def hyc_main(): parser = argparse.ArgumentParser(prog="hyc") - parser.add_argument( - "files", - metavar="FILE", - nargs="*", - help=("File(s) to compile (use STDIN if only" ' "-" or nothing is provided)'), - ) + parser.add_argument("files", metavar="FILE", nargs="+", help="File(s) to compile") parser.add_argument("-v", action="version", version=VERSION) options = parser.parse_args(sys.argv[1:]) rv = 0 - if len(options.files) == 0 or (len(options.files) == 1 and options.files[0] == "-"): - while True: - filename = sys.stdin.readline() - if not filename: - break - filename = filename.rstrip("\n") - set_path(filename) - try: - py_compile.compile(filename, doraise=True) - except py_compile.PyCompileError as error: - rv = 1 - sys.stderr.write("%s\n" % error.msg) - except OSError as error: - rv = 1 - sys.stderr.write("%s\n" % error) - sys.path.pop(0) - else: - for filename in options.files: - set_path(filename) - try: - print("Compiling %s" % filename) - py_compile.compile(filename, doraise=True) - except py_compile.PyCompileError as error: - # return value to indicate at least one failure - rv = 1 - sys.stderr.write("%s\n" % error.msg) - sys.path.pop(0) + for filename in options.files: + set_path(filename) + try: + print( + "Compiling {!r} --> {!r}".format( + filename, importlib.util.cache_from_source(filename) + ), + file=sys.stderr, + ) + py_compile.compile(filename, doraise=True) + except py_compile.PyCompileError as error: + # return value to indicate at least one failure + rv = 1 + print(error.msg, file=sys.stderr) + sys.path.pop(0) return rv
hylang/hy
eae954508adeed1f3b0a8cff17e3bfb798cb468c
diff --git a/tests/test_bin.py b/tests/test_bin.py index 64b8adfa..45bae911 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -341,18 +341,12 @@ def test_file_with_args(): def test_hyc(): - _, err = run_cmd("hyc", expect=0) - assert err == "" - - _, err = run_cmd("hyc -", expect=0) - assert err == "" - output, _ = run_cmd("hyc -h") assert "usage" in output path = "tests/resources/argparse_ex.hy" - output, _ = run_cmd("hyc " + path) - assert "Compiling" in output + _, err = run_cmd("hyc " + path) + assert "Compiling" in err assert os.path.exists(cache_from_source(path)) rm(cache_from_source(path))
`hyc` doesn't require an argument Compiling from stdin results in a weird error which seems like hyc is trying to read the file from the disk. ``` % cat > tmp.hy (import os sys) % hy tmp.hy % hyc tmp.hy Compiling tmp.hy % hyc - < tmp.hy [Errno 2] No such file or directory: '(import os sys)' % hyc < tmp.hy [Errno 2] No such file or directory: '(import os sys)' ```
0.0
eae954508adeed1f3b0a8cff17e3bfb798cb468c
[ "tests/test_bin.py::test_hyc" ]
[ "tests/test_bin.py::test_simple", "tests/test_bin.py::test_stdin", "tests/test_bin.py::test_stdin_multiline", "tests/test_bin.py::test_history", "tests/test_bin.py::test_stdin_comments", "tests/test_bin.py::test_stdin_assignment", "tests/test_bin.py::test_multi_setv", "tests/test_bin.py::test_stdin_error_underline_alignment", "tests/test_bin.py::test_stdin_except_do", "tests/test_bin.py::test_stdin_unlocatable_hytypeerror", "tests/test_bin.py::test_error_parts_length", "tests/test_bin.py::test_syntax_errors", "tests/test_bin.py::test_stdin_bad_repr", "tests/test_bin.py::test_stdin_py_repr", "tests/test_bin.py::test_mangle_m", "tests/test_bin.py::test_ignore_python_env", "tests/test_bin.py::test_cmd", "tests/test_bin.py::test_icmd", "tests/test_bin.py::test_icmd_file", "tests/test_bin.py::test_icmd_and_spy", "tests/test_bin.py::test_missing_file", "tests/test_bin.py::test_file_with_args", "tests/test_bin.py::test_hyc_missing_file", "tests/test_bin.py::test_builtins", "tests/test_bin.py::test_no_main", "tests/test_bin.py::test_byte_compile[cmd_fmt0-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_option]", "tests/test_bin.py::test_module_main_file", "tests/test_bin.py::test_file_main_file", "tests/test_bin.py::test_file_sys_path", "tests/test_bin.py::test_module_no_main", "tests/test_bin.py::test_sys_executable", "tests/test_bin.py::test_file_no_extension", "tests/test_bin.py::test_circular_macro_require", "tests/test_bin.py::test_macro_require", "tests/test_bin.py::test_tracebacks", "tests/test_bin.py::test_hystartup", "tests/test_bin.py::test_output_buffering", "tests/test_bin.py::test_uufileuu", "tests/test_bin.py::test_assert" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-07-23 20:49:41+00:00
mit
2,757
hylang__hy-2353
diff --git a/NEWS.rst b/NEWS.rst index 73db0939..5f83fd54 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1,26 +1,27 @@ .. default-role:: code -Unreleased +0.25.0 (released 2022-11-08) ============================== -Other Breaking Changes +Breaking Changes ------------------------------ * `dfor` no longer requires brackets around its final arguments, so `(dfor x (range 5) [x (* 2 x)])` is now `(dfor x (range 5) x (* 2 x))`. - -New Features ------------------------------- -* Python 3.11 is now supported. -* `except*` (PEP 654) is now recognized in `try`. +* `except*` (PEP 654) is now recognized in `try`, and a placeholder + macro for `except*` has been added. Bug Fixes ------------------------------ -* Fixed `hy.repr` of `slice` objects with non-integer arguments. * `__file__` should now be set the same way as in Python. +* `\N{…}` escape sequences are now recognized in f-strings. * Fixed a bug with `python -O` where assertions were still partly evaluated. -* `\N{…}` escape sequences are now recognized in f-strings. +* Fixed `hy.repr` of `slice` objects with non-integer arguments. + +New Features +------------------------------ +* Python 3.11 is now supported. Misc. Improvements ------------------------------ diff --git a/docs/api.rst b/docs/api.rst index c19cc5da..942770ad 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1428,6 +1428,7 @@ expanded, is crash, regardless of their arguments: - ``else`` - ``except`` +- ``except*`` - ``finally`` - ``unpack-mapping`` - ``unquote`` diff --git a/hy/core/result_macros.py b/hy/core/result_macros.py index c3871139..8d5390e4 100644 --- a/hy/core/result_macros.py +++ b/hy/core/result_macros.py @@ -1895,7 +1895,8 @@ def compile_let(compiler, expr, root, bindings, body): @pattern_macro( - "unquote unquote-splice unpack-mapping except finally else".split(), [many(FORM)] + "unquote unquote-splice unpack-mapping except except* finally else".split(), + [many(FORM)], ) def compile_placeholder(compiler, expr, root, body): raise ValueError(f"`{root}` is not allowed here")
hylang/hy
b107100ca463aaf81e2d477347bbd2686e6ed0c8
diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 7083be6b..800c830c 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -579,14 +579,22 @@ def test_setv_builtins(): ) -def test_top_level_unquote(): +def placeholder_macro(x, ename=None): with pytest.raises(HyLanguageError) as e: - can_compile("(unquote)") - assert "`unquote` is not allowed here" in e.value.msg + can_compile(f"({x})") + assert f"`{ename or x}` is not allowed here" in e.value.msg - with pytest.raises(HyLanguageError) as e: - can_compile("(unquote-splice)") - assert "`unquote-splice` is not allowed here" in e.value.msg + +def test_top_level_unquote(): + placeholder_macro("unquote") + placeholder_macro("unquote-splice") + placeholder_macro("unquote_splice", "unquote-splice") + + +def test_bad_exception(): + placeholder_macro("except") + placeholder_macro("except*") + placeholder_macro(hy.mangle("except*"), "except*") def test_lots_of_comment_lines():
Make a new release You fixed the setup.py to support 3.11, please release that.
0.0
b107100ca463aaf81e2d477347bbd2686e6ed0c8
[ "tests/compilers/test_ast.py::test_bad_exception" ]
[ "tests/compilers/test_ast.py::test_ast_bad_type", "tests/compilers/test_ast.py::test_empty_expr", "tests/compilers/test_ast.py::test_dot_unpacking", "tests/compilers/test_ast.py::test_ast_bad_if", "tests/compilers/test_ast.py::test_ast_valid_if", "tests/compilers/test_ast.py::test_ast_valid_unary_op", "tests/compilers/test_ast.py::test_ast_invalid_unary_op", "tests/compilers/test_ast.py::test_ast_bad_while", "tests/compilers/test_ast.py::test_ast_good_do", "tests/compilers/test_ast.py::test_ast_good_raise", "tests/compilers/test_ast.py::test_ast_raise_from", "tests/compilers/test_ast.py::test_ast_bad_raise", "tests/compilers/test_ast.py::test_ast_good_try", "tests/compilers/test_ast.py::test_ast_bad_try", "tests/compilers/test_ast.py::test_ast_good_except", "tests/compilers/test_ast.py::test_ast_bad_except", "tests/compilers/test_ast.py::test_ast_good_assert", "tests/compilers/test_ast.py::test_ast_bad_assert", "tests/compilers/test_ast.py::test_ast_good_global", "tests/compilers/test_ast.py::test_ast_bad_global", "tests/compilers/test_ast.py::test_ast_good_nonlocal", "tests/compilers/test_ast.py::test_ast_bad_nonlocal", "tests/compilers/test_ast.py::test_ast_good_defclass", "tests/compilers/test_ast.py::test_ast_good_defclass_with_metaclass", "tests/compilers/test_ast.py::test_ast_bad_defclass", "tests/compilers/test_ast.py::test_ast_good_lambda", "tests/compilers/test_ast.py::test_ast_bad_lambda", "tests/compilers/test_ast.py::test_ast_good_yield", "tests/compilers/test_ast.py::test_ast_bad_yield", "tests/compilers/test_ast.py::test_ast_import_mangle_dotted", "tests/compilers/test_ast.py::test_ast_good_import_from", "tests/compilers/test_ast.py::test_ast_require", "tests/compilers/test_ast.py::test_ast_import_require_dotted", "tests/compilers/test_ast.py::test_ast_multi_require", "tests/compilers/test_ast.py::test_ast_good_get", "tests/compilers/test_ast.py::test_ast_bad_get", "tests/compilers/test_ast.py::test_ast_good_cut", "tests/compilers/test_ast.py::test_ast_bad_cut", "tests/compilers/test_ast.py::test_ast_bad_with", "tests/compilers/test_ast.py::test_ast_valid_while", "tests/compilers/test_ast.py::test_ast_valid_for", "tests/compilers/test_ast.py::test_nullary_break_continue", "tests/compilers/test_ast.py::test_ast_expression_basics", "tests/compilers/test_ast.py::test_ast_anon_fns_basics", "tests/compilers/test_ast.py::test_ast_lambda_lists", "tests/compilers/test_ast.py::test_ast_print", "tests/compilers/test_ast.py::test_ast_tuple", "tests/compilers/test_ast.py::test_lambda_list_keywords_rest", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwargs", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwonly", "tests/compilers/test_ast.py::test_lambda_list_keywords_mixed", "tests/compilers/test_ast.py::test_missing_keyword_argument_value", "tests/compilers/test_ast.py::test_ast_unicode_strings", "tests/compilers/test_ast.py::test_ast_unicode_vs_bytes", "tests/compilers/test_ast.py::test_format_string", "tests/compilers/test_ast.py::test_ast_bracket_string", "tests/compilers/test_ast.py::test_literal_newlines", "tests/compilers/test_ast.py::test_compile_error", "tests/compilers/test_ast.py::test_for_compile_error", "tests/compilers/test_ast.py::test_attribute_access", "tests/compilers/test_ast.py::test_attribute_empty", "tests/compilers/test_ast.py::test_bad_setv", "tests/compilers/test_ast.py::test_defn", "tests/compilers/test_ast.py::test_setv_builtins", "tests/compilers/test_ast.py::test_top_level_unquote", "tests/compilers/test_ast.py::test_lots_of_comment_lines", "tests/compilers/test_ast.py::test_compiler_macro_tag_try", "tests/compilers/test_ast.py::test_ast_good_yield_from", "tests/compilers/test_ast.py::test_ast_bad_yield_from", "tests/compilers/test_ast.py::test_eval_generator_with_return", "tests/compilers/test_ast.py::test_futures_imports", "tests/compilers/test_ast.py::test_inline_python", "tests/compilers/test_ast.py::test_models_accessible", "tests/compilers/test_ast.py::test_module_prelude" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-11-03 21:19:10+00:00
mit
2,758
hylang__hy-2389
diff --git a/AUTHORS b/AUTHORS index 194456f0..d28bcd1b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -109,3 +109,4 @@ * Dmitry Ivanov <[email protected]> * Andrey Vlasovskikh <[email protected]> * Joseph LaFreniere <[email protected]> +* Daniel Tan <[email protected]> diff --git a/NEWS.rst b/NEWS.rst index 4fa2722b..85058939 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -38,6 +38,7 @@ New Features remaining special rule that `...` compiles to `Ellipsis`) * On Pythons ≥ 3.7, Hy modules can now be imported from ZIP archives in the same way as Python modules, via `zipimport`_. +* `hy2py` now supports directory input, and will recursively convert hy source code into python source code. .. _zipimport: https://docs.python.org/3.11/library/zipimport.html diff --git a/docs/cli.rst b/docs/cli.rst index 374be98c..2390d44e 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -43,7 +43,7 @@ for a complete list of options and :py:ref:`Python's documentation hy2py ----- -``hy2py`` is a program to convert Hy source code into Python source code. Use ``hy2py --help`` for usage instructions. It can take its input from standard input or from a filename provided as a command-line argument. The result is written to standard output. +``hy2py`` is a program to convert Hy source code into Python source code. Use ``hy2py --help`` for usage instructions. It can take its input from standard input, from a filename, or folder name provided as a command-line argument. If it is a folder, the output parameter (--output/-o) must be provided. When the output parameter is provided, the output will be written into the folder or file, otherwise the result is written to standard output. .. warning:: ``hy2py`` can execute arbitrary code. Don't give it untrusted input. diff --git a/hy/cmdline.py b/hy/cmdline.py index f6093b2e..72d0bc22 100644 --- a/hy/cmdline.py +++ b/hy/cmdline.py @@ -7,6 +7,7 @@ import platform import py_compile import runpy import sys +from contextlib import nullcontext from pathlib import Path import hy @@ -330,6 +331,48 @@ def hyc_main(): return rv +def hy2py_worker(source, options, filename, output_filepath=None): + if isinstance(source, Path): + source = source.read_text(encoding="UTF-8") + + if not output_filepath and options.output: + output_filepath = options.output + + set_path(filename) + with ( + open(output_filepath, "w", encoding="utf-8") + if output_filepath + else nullcontext() + ) as output_file: + + def printing_source(hst): + for node in hst: + if options.with_source: + print(node, file=output_file) + yield node + + hst = hy.models.Lazy( + printing_source(read_many(source, filename, skip_shebang=True)) + ) + hst.source = source + hst.filename = filename + + with filtered_hy_exceptions(): + _ast = hy_compile(hst, "__main__", filename=filename, source=source) + + if options.with_source: + print() + print() + + if options.with_ast: + print(ast.dump(_ast, **(dict(indent=2) if PY3_9 else {})), file=output_file) + print() + print() + + if not options.without_python: + print(ast.unparse(_ast), file=output_file) + + # entry point for cmd line script "hy2py" def hy2py_main(): options = dict( @@ -342,7 +385,8 @@ def hy2py_main(): "FILE", type=str, nargs="?", - help='Input Hy code (use STDIN if "-" or ' "not provided)", + help='Input Hy code (can be file or directory) (use STDIN if "-" or ' + "not provided)", ) parser.add_argument( "--with-source", @@ -359,46 +403,51 @@ def hy2py_main(): action="store_true", help=("Do not show the Python code generated " "from the AST"), ) + parser.add_argument( + "--output", + "-o", + type=str, + nargs="?", + help="output file / directory", + ) options = parser.parse_args(sys.argv[1:]) if options.FILE is None or options.FILE == "-": sys.path.insert(0, "") filename = "<stdin>" - source = sys.stdin.read() + hy2py_worker(sys.stdin.read(), options, filename) else: filename = options.FILE - set_path(filename) - with open(options.FILE, "r", encoding="utf-8") as source_file: - source = source_file.read() - - def printing_source(hst): - for node in hst: - if options.with_source: - print(node) - yield node - - hst = hy.models.Lazy( - printing_source(read_many(source, filename, skip_shebang=True)) - ) - hst.source = source - hst.filename = filename - - with filtered_hy_exceptions(): - _ast = hy_compile(hst, "__main__", filename=filename, source=source) - - if options.with_source: - print() - print() - - if options.with_ast: - print(ast.dump(_ast, **(dict(indent=2) if PY3_9 else {}))) - print() - print() - - if not options.without_python: - print(ast.unparse(_ast)) + if os.path.isdir(filename): + # handle recursively if --output is specified + if not options.output: + raise ValueError( + f"{filename} is a directory but the output directory is not specified. Use --output or -o in command line arguments to specify the output directory." + ) + os.makedirs(options.output, exist_ok=True) + for path, subdirs, files in os.walk(filename): + for name in files: + filename_raw, filename_ext = os.path.splitext(name) + if filename_ext == ".hy": + filepath = os.path.join(path, name) + # make sure to follow original file structure + subdirectory = os.path.relpath(path, filename) + output_directory_path = os.path.join( + options.output if options.output else path, subdirectory + ) + os.makedirs(output_directory_path, exist_ok=True) + hy2py_worker( + Path(filepath), + options, + filename, + output_filepath=os.path.join( + output_directory_path, filename_raw + ".py" + ), + ) + else: + hy2py_worker(Path(options.FILE), options, filename) parser.exit(0)
hylang/hy
d72135ae894329fca8650487e1d179a9ec0e56f6
diff --git a/tests/test_bin.py b/tests/test_bin.py index 95899287..4319bce9 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -26,7 +26,7 @@ def pyr(s=""): def run_cmd( cmd, stdin_data=None, expect=0, dontwritebytecode=False, - stdout=subprocess.PIPE): + cwd=None, stdout=subprocess.PIPE): env = dict(os.environ) if dontwritebytecode: env["PYTHONDONTWRITEBYTECODE"] = "1" @@ -41,6 +41,7 @@ def run_cmd( universal_newlines=True, shell=False, env=env, + cwd=cwd, ) output = p.communicate(input=stdin_data) assert p.wait() == expect @@ -717,3 +718,28 @@ def test_assert(tmp_path, monkeypatch): show_msg = has_msg and not optim and not test assert ("msging" in out) == show_msg assert ("bye" in err) == show_msg + + +def test_hy2py_recursive(tmp_path): + (tmp_path / 'hy').mkdir() + (tmp_path / "hy/first.hy").write_text(""" + (import folder.second [a b]) + (print a) + (print b)""") + (tmp_path / "hy/folder").mkdir() + (tmp_path / "hy/folder/second.hy").write_text(""" + (setv a 1) + (setv b "hello world")""") + + _, err = run_cmd(f"hy2py {(tmp_path / 'hy').as_posix()}", expect=1) + assert "ValueError" in err + + run_cmd("hy2py " + + f"{(tmp_path / 'hy').as_posix()} " + + f"--output {(tmp_path / 'py').as_posix()}") + assert set((tmp_path / 'py').rglob('*')) == { + tmp_path / 'py' / p + for p in ('first.py', 'folder', 'folder/second.py')} + + output, _ = run_cmd(f"python3 first.py", cwd = tmp_path / 'py') + assert output == "1\nhello world\n" diff --git a/tests/test_hy2py.py b/tests/test_hy2py.py index d4c12950..c5743984 100644 --- a/tests/test_hy2py.py +++ b/tests/test_hy2py.py @@ -1,8 +1,6 @@ import asyncio import itertools import math -import os -import platform import pytest
Recursive `hy2py` We could give `hy2py` a recursive mode that goes through a source tree and saves a matching Python file for each Hy file, if an up-to-date one doesn't already exist. Optionally, it could delete all such Python files and bytecode first, in order to ensure all macro expansions are fully up to date. I'm not sure how often this would be useful in practice, but it seems like an obvious feature to have.
0.0
d72135ae894329fca8650487e1d179a9ec0e56f6
[ "tests/test_bin.py::test_hy2py_recursive" ]
[ "tests/test_bin.py::test_simple", "tests/test_bin.py::test_stdin", "tests/test_bin.py::test_stdin_multiline", "tests/test_bin.py::test_history", "tests/test_bin.py::test_stdin_comments", "tests/test_bin.py::test_stdin_assignment", "tests/test_bin.py::test_multi_setv", "tests/test_bin.py::test_stdin_error_underline_alignment", "tests/test_bin.py::test_stdin_except_do", "tests/test_bin.py::test_stdin_unlocatable_hytypeerror", "tests/test_bin.py::test_error_parts_length", "tests/test_bin.py::test_syntax_errors", "tests/test_bin.py::test_stdin_bad_repr", "tests/test_bin.py::test_stdin_py_repr", "tests/test_bin.py::test_mangle_m", "tests/test_bin.py::test_ignore_python_env", "tests/test_bin.py::test_cmd", "tests/test_bin.py::test_icmd", "tests/test_bin.py::test_icmd_file", "tests/test_bin.py::test_icmd_and_spy", "tests/test_bin.py::test_missing_file", "tests/test_bin.py::test_file_with_args", "tests/test_bin.py::test_hyc", "tests/test_bin.py::test_hyc_missing_file", "tests/test_bin.py::test_builtins", "tests/test_bin.py::test_no_main", "tests/test_bin.py::test_byte_compile[cmd_fmt0-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_option]", "tests/test_bin.py::test_module_main_file", "tests/test_bin.py::test_file_main_file", "tests/test_bin.py::test_file_sys_path", "tests/test_bin.py::test_module_no_main", "tests/test_bin.py::test_sys_executable", "tests/test_bin.py::test_file_no_extension", "tests/test_bin.py::test_circular_macro_require", "tests/test_bin.py::test_macro_require", "tests/test_bin.py::test_tracebacks", "tests/test_bin.py::test_hystartup", "tests/test_bin.py::test_output_buffering", "tests/test_bin.py::test_uufileuu", "tests/test_bin.py::test_assert", "tests/test_hy2py.py::test_direct_import", "tests/test_hy2py.py::test_hy2py_import" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-18 12:33:30+00:00
mit
2,759
hylang__hy-2412
diff --git a/NEWS.rst b/NEWS.rst index a7fcff32..53ff502d 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -11,6 +11,7 @@ Bug Fixes ------------------------------ * Fixed an installation failure in some situations when version lookup fails. +* Fixed traceback pointing in scripts with shebangs. New Features ------------------------------ diff --git a/hy/reader/__init__.py b/hy/reader/__init__.py index 54a85640..8744c715 100644 --- a/hy/reader/__init__.py +++ b/hy/reader/__init__.py @@ -30,16 +30,11 @@ def read_many(stream, filename="<string>", reader=None, skip_shebang=False): if isinstance(stream, str): stream = StringIO(stream) pos = stream.tell() - if skip_shebang: - if stream.read(2) == "#!": - stream.readline() - pos = stream.tell() - else: - stream.seek(pos) source = stream.read() stream.seek(pos) - m = hy.models.Lazy((reader or HyReader()).parse(stream, filename)) + m = hy.models.Lazy((reader or HyReader()).parse( + stream, filename, skip_shebang)) m.source = source m.filename = filename return m diff --git a/hy/reader/hy_reader.py b/hy/reader/hy_reader.py index 025adab7..3f558b2c 100644 --- a/hy/reader/hy_reader.py +++ b/hy/reader/hy_reader.py @@ -1,5 +1,7 @@ "Character reader for parsing Hy source." +from itertools import islice + import hy from hy.models import ( Bytes, @@ -140,7 +142,7 @@ class HyReader(Reader): return self.prefixed_string('"', ident) return as_identifier(ident, reader=self) - def parse(self, stream, filename=None): + def parse(self, stream, filename=None, skip_shebang=False): """Yields all `hy.models.Object`'s in `source` Additionally exposes `self` as ``hy.&reader`` during read/compile time. @@ -151,8 +153,16 @@ class HyReader(Reader): filename (str | None): Filename to use for error messages. If `None` then previously set filename is used. + skip_shebang: + Whether to detect a skip a shebang line at the start. """ self._set_source(stream, filename) + + if skip_shebang and "".join(islice(self.peeking(), len("#!"))) == "#!": + for c in self.chars(): + if c == "\n": + break + rname = mangle("&reader") old_reader = getattr(hy, rname, None) setattr(hy, rname, self)
hylang/hy
1cc9c8b1f291fd4792aca888f893b78bc218c2ef
diff --git a/tests/test_bin.py b/tests/test_bin.py index 4319bce9..04f4ac14 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -33,9 +33,9 @@ def run_cmd( else: env.pop("PYTHONDONTWRITEBYTECODE", None) - p = subprocess.Popen( - shlex.split(cmd), - stdin=subprocess.PIPE, + result = subprocess.run( + shlex.split(cmd) if isinstance(cmd, str) else cmd, + input=stdin_data, stdout=stdout, stderr=subprocess.PIPE, universal_newlines=True, @@ -43,9 +43,8 @@ def run_cmd( env=env, cwd=cwd, ) - output = p.communicate(input=stdin_data) - assert p.wait() == expect - return output + assert result.returncode == expect + return (result.stdout, result.stderr) def rm(fpath): try: @@ -351,7 +350,7 @@ def test_hyc(): assert "usage" in output path = "tests/resources/argparse_ex.hy" - _, err = run_cmd("hyc " + path) + _, err = run_cmd(["hyc", path]) assert "Compiling" in err assert os.path.exists(cache_from_source(path)) rm(cache_from_source(path)) @@ -472,7 +471,7 @@ def testc_file_sys_path(): rm(cache_from_source(test_file)) assert not os.path.exists(cache_from_source(file_relative_path)) - output, _ = run_cmd(f"{binary} {test_file}") + output, _ = run_cmd([binary, test_file]) assert repr(file_relative_path) in output @@ -500,12 +499,12 @@ def test_circular_macro_require(): test_file = "tests/resources/bin/circular_macro_require.hy" rm(cache_from_source(test_file)) assert not os.path.exists(cache_from_source(test_file)) - output, _ = run_cmd("hy {}".format(test_file)) + output, _ = run_cmd(["hy", test_file]) assert output.strip() == "WOWIE" # Now, with bytecode assert os.path.exists(cache_from_source(test_file)) - output, _ = run_cmd("hy {}".format(test_file)) + output, _ = run_cmd(["hy", test_file]) assert output.strip() == "WOWIE" @@ -519,12 +518,12 @@ def test_macro_require(): test_file = "tests/resources/bin/require_and_eval.hy" rm(cache_from_source(test_file)) assert not os.path.exists(cache_from_source(test_file)) - output, _ = run_cmd("hy {}".format(test_file)) + output, _ = run_cmd(["hy", test_file]) assert output.strip() == "abc" # Now, with bytecode assert os.path.exists(cache_from_source(test_file)) - output, _ = run_cmd("hy {}".format(test_file)) + output, _ = run_cmd(["hy", test_file]) assert output.strip() == "abc" @@ -611,6 +610,15 @@ def test_tracebacks(): assert error_lines[-1].startswith("TypeError") +def test_traceback_shebang(tmp_path): + # https://github.com/hylang/hy/issues/2405 + (tmp_path / 'ex.hy').write_text('#!my cool shebang\n(/ 1 0)') + _, error = run_cmd(['hy', tmp_path / 'ex.hy'], expect = 1) + assert 'ZeroDivisionError' + assert 'my cool shebang' not in error + assert '(/ 1 0)' in error + + def test_hystartup(): # spy == True and custom repl-output-fn os.environ["HYSTARTUP"] = "tests/resources/hystartup.hy" @@ -651,11 +659,10 @@ def test_output_buffering(tmp_path): (import sys pathlib [Path]) (print :file sys.stderr (.strip (.read-text (Path #[=[{tf}]=])))) (print "line 2")''') - pf = shlex.quote(str(pf)) - for flag, expected in ("", ""), ("--unbuffered", "line 1"): + for flags, expected in ([], ""), (["--unbuffered"], "line 1"): with open(tf, "wb") as o: - _, stderr = run_cmd(f"hy {flag} {pf}", stdout=o) + _, stderr = run_cmd(["hy", *flags, pf], stdout=o) assert stderr.strip() == expected assert tf.read_text().splitlines() == ["line 1", "line 2"] @@ -671,9 +678,9 @@ def test_uufileuu(tmp_path, monkeypatch): def file_is(arg, expected_py3_9): expected = expected_py3_9 if PY3_9 and not PYPY else Path(arg) - output, _ = run_cmd("python3 " + shlex.quote(arg + "pyex.py")) + output, _ = run_cmd(["python3", arg + "pyex.py"]) assert output.rstrip() == str(expected / "pyex.py") - output, _ = run_cmd("hy " + shlex.quote(arg + "hyex.hy")) + output, _ = run_cmd(["hy", arg + "hyex.hy"]) assert output.rstrip() == str(expected / "hyex.hy") monkeypatch.chdir(tmp_path) @@ -731,15 +738,15 @@ def test_hy2py_recursive(tmp_path): (setv a 1) (setv b "hello world")""") - _, err = run_cmd(f"hy2py {(tmp_path / 'hy').as_posix()}", expect=1) + _, err = run_cmd(["hy2py", (tmp_path / 'hy')], expect=1) assert "ValueError" in err - run_cmd("hy2py " + - f"{(tmp_path / 'hy').as_posix()} " + - f"--output {(tmp_path / 'py').as_posix()}") + run_cmd(["hy2py", + (tmp_path / 'hy'), + "--output", (tmp_path / 'py')]) assert set((tmp_path / 'py').rglob('*')) == { tmp_path / 'py' / p for p in ('first.py', 'folder', 'folder/second.py')} - output, _ = run_cmd(f"python3 first.py", cwd = tmp_path / 'py') + output, _ = run_cmd("python3 first.py", cwd = tmp_path / 'py') assert output == "1\nhello world\n" diff --git a/tests/test_reader.py b/tests/test_reader.py index 0465bc00..89a7fc7a 100644 --- a/tests/test_reader.py +++ b/tests/test_reader.py @@ -23,8 +23,8 @@ from hy.reader import read_many from hy.reader.exceptions import LexException, PrematureEndOfInput -def tokenize(s): - return list(read_many(s)) +def tokenize(*args, **kwargs): + return list(read_many(*args, **kwargs)) def peoi(): @@ -675,3 +675,13 @@ def test_read_error(): assert "".join(traceback.format_exception_only(e.type, e.value)).startswith( ' File "<string>", line 1\n (do (defn))\n ^\n' ) + + +def test_shebang(): + from hy.errors import HySyntaxError + + with pytest.raises(HySyntaxError): + # By default, `read_many` doesn't allow a shebang. + assert tokenize('#!/usr/bin/env hy\n5') + assert (tokenize('#!/usr/bin/env hy\n5', skip_shebang = True) == + [Integer(5)])
Tracebacks in a file with a shebang point to the wrong line ```hy #!/usr/bin/env hy ;; wow (raise Exception) ;; nothing ``` ``` $ hy test.hy Traceback (most recent call last): File "/home/lyh/.local/bin/hy", line 8, in <module> sys.exit(hy_main()) File "/usr/lib/python3.10/runpy.py", line 289, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/lib/python3.10/runpy.py", line 96, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/tmp/a.hy", line 2, in <module> ;; wow Exception ```
0.0
1cc9c8b1f291fd4792aca888f893b78bc218c2ef
[ "tests/test_bin.py::test_traceback_shebang" ]
[ "tests/test_bin.py::test_simple", "tests/test_bin.py::test_stdin", "tests/test_bin.py::test_stdin_multiline", "tests/test_bin.py::test_history", "tests/test_bin.py::test_stdin_comments", "tests/test_bin.py::test_stdin_assignment", "tests/test_bin.py::test_multi_setv", "tests/test_bin.py::test_stdin_error_underline_alignment", "tests/test_bin.py::test_stdin_except_do", "tests/test_bin.py::test_stdin_unlocatable_hytypeerror", "tests/test_bin.py::test_error_parts_length", "tests/test_bin.py::test_syntax_errors", "tests/test_bin.py::test_stdin_bad_repr", "tests/test_bin.py::test_stdin_py_repr", "tests/test_bin.py::test_mangle_m", "tests/test_bin.py::test_ignore_python_env", "tests/test_bin.py::test_cmd", "tests/test_bin.py::test_icmd", "tests/test_bin.py::test_icmd_file", "tests/test_bin.py::test_icmd_and_spy", "tests/test_bin.py::test_missing_file", "tests/test_bin.py::test_file_with_args", "tests/test_bin.py::test_hyc", "tests/test_bin.py::test_hyc_missing_file", "tests/test_bin.py::test_builtins", "tests/test_bin.py::test_no_main", "tests/test_bin.py::test_byte_compile[cmd_fmt0-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_option]", "tests/test_bin.py::test_module_main_file", "tests/test_bin.py::test_file_main_file", "tests/test_bin.py::test_file_sys_path", "tests/test_bin.py::test_module_no_main", "tests/test_bin.py::test_sys_executable", "tests/test_bin.py::test_file_no_extension", "tests/test_bin.py::test_circular_macro_require", "tests/test_bin.py::test_macro_require", "tests/test_bin.py::test_tracebacks", "tests/test_bin.py::test_hystartup", "tests/test_bin.py::test_output_buffering", "tests/test_bin.py::test_uufileuu", "tests/test_bin.py::test_assert", "tests/test_bin.py::test_hy2py_recursive", "tests/test_reader.py::test_lex_exception", "tests/test_reader.py::test_unbalanced_exception", "tests/test_reader.py::test_lex_single_quote_err", "tests/test_reader.py::test_lex_expression_symbols", "tests/test_reader.py::test_symbol_and_sugar", "tests/test_reader.py::test_lex_expression_strings", "tests/test_reader.py::test_lex_expression_integer", "tests/test_reader.py::test_lex_symbols", "tests/test_reader.py::test_lex_strings", "tests/test_reader.py::test_lex_strings_exception", "tests/test_reader.py::test_lex_bracket_strings", "tests/test_reader.py::test_lex_integers", "tests/test_reader.py::test_lex_expression_float", "tests/test_reader.py::test_lex_big_float", "tests/test_reader.py::test_lex_nan_and_inf", "tests/test_reader.py::test_lex_expression_complex", "tests/test_reader.py::test_lex_digit_separators", "tests/test_reader.py::test_leading_zero", "tests/test_reader.py::test_dotted_identifiers", "tests/test_reader.py::test_lex_bad_attrs", "tests/test_reader.py::test_lists", "tests/test_reader.py::test_dicts", "tests/test_reader.py::test_lex_column_counting", "tests/test_reader.py::test_lex_column_counting_with_literal_newline", "tests/test_reader.py::test_lex_line_counting_multi", "tests/test_reader.py::test_lex_line_counting_multi_inner", "tests/test_reader.py::test_sets", "tests/test_reader.py::test_nospace", "tests/test_reader.py::test_string_prefixes", "tests/test_reader.py::test_escapes", "tests/test_reader.py::test_unicode_escapes", "tests/test_reader.py::test_complex", "tests/test_reader.py::test_lex_comment_382", "tests/test_reader.py::test_discard", "tests/test_reader.py::test_lex_exception_filtering", "tests/test_reader.py::test_read_error", "tests/test_reader.py::test_shebang" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-18 19:41:34+00:00
mit
2,760
hylang__hy-2423
diff --git a/NEWS.rst b/NEWS.rst index a0b30a20..6c8cb58f 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -7,7 +7,7 @@ Bug Fixes ------------------------------ * Fixed an installation failure in some situations when version lookup fails. -* Fixed traceback pointing in scripts with shebangs. +* Fixed some bugs with traceback pointing. * Fixed some bugs with escaping in bracket f-strings New Features diff --git a/hy/reader/hy_reader.py b/hy/reader/hy_reader.py index 4483db6d..985baaa5 100644 --- a/hy/reader/hy_reader.py +++ b/hy/reader/hy_reader.py @@ -128,7 +128,9 @@ class HyReader(Reader): """ model.start_line, model.start_column = start model.end_line, model.end_column = self.pos - return model + return model.replace(model) + # `replace` will recurse into submodels and set any model + # positions that are still unset the same way. def read_default(self, key): """Default reader handler when nothing in the table matches.
hylang/hy
a03febe1c8f81583bcc22a977986aaa5acf4048a
diff --git a/tests/test_reader.py b/tests/test_reader.py index 89a7fc7a..3ef6e38c 100644 --- a/tests/test_reader.py +++ b/tests/test_reader.py @@ -410,6 +410,13 @@ def test_lex_line_counting_multi_inner(): assert inner.start_column == 5 +def test_line_counting_dotted(): + # https://github.com/hylang/hy/issues/2422 + x, = tokenize(";;;;;\na.b") + for e in (x, *x): + assert e.start_line == 2 + + def test_dicts(): """Ensure that we can tokenize a dict.""" objs = tokenize("{foo bar bar baz}")
Misplaced tracebacks from some models created in the reader ``` $ echo ';;;;;;\na.b' >ex.hy $ hy ex.hy Traceback (most recent call last): … File "/tmp/ex.hy", line 1, in <module> ;;;;;; NameError: name 'a' is not defined ``` The error is wrongly attributed to line 1 because the reader fails to set position information for a model created during the expansion of `a.b` into `(. a b)`. Contrast with this case, which is correct: ``` $ echo ';;;;;;\n(. a b)' >ex.hy $ hy ex.hy Traceback (most recent call last): … File "/tmp/ex.hy", line 2, in <module> (. a b) NameError: name 'a' is not defined ``` I believe it suffices to call `model.replace(model)` in `HyReader.fill_pos`, so that positions are fixed recursively. I just need to write a test. This bug is more consequential than it sounds because it can crash pytest internally, when non-existent columns of the source are retrieved for a traceback. Hy's own error reporting doesn't fail so badly in such a case.
0.0
a03febe1c8f81583bcc22a977986aaa5acf4048a
[ "tests/test_reader.py::test_line_counting_dotted" ]
[ "tests/test_reader.py::test_lex_exception", "tests/test_reader.py::test_unbalanced_exception", "tests/test_reader.py::test_lex_single_quote_err", "tests/test_reader.py::test_lex_expression_symbols", "tests/test_reader.py::test_symbol_and_sugar", "tests/test_reader.py::test_lex_expression_strings", "tests/test_reader.py::test_lex_expression_integer", "tests/test_reader.py::test_lex_symbols", "tests/test_reader.py::test_lex_strings", "tests/test_reader.py::test_lex_strings_exception", "tests/test_reader.py::test_lex_bracket_strings", "tests/test_reader.py::test_lex_integers", "tests/test_reader.py::test_lex_expression_float", "tests/test_reader.py::test_lex_big_float", "tests/test_reader.py::test_lex_nan_and_inf", "tests/test_reader.py::test_lex_expression_complex", "tests/test_reader.py::test_lex_digit_separators", "tests/test_reader.py::test_leading_zero", "tests/test_reader.py::test_dotted_identifiers", "tests/test_reader.py::test_lex_bad_attrs", "tests/test_reader.py::test_lists", "tests/test_reader.py::test_dicts", "tests/test_reader.py::test_lex_column_counting", "tests/test_reader.py::test_lex_column_counting_with_literal_newline", "tests/test_reader.py::test_lex_line_counting_multi", "tests/test_reader.py::test_lex_line_counting_multi_inner", "tests/test_reader.py::test_sets", "tests/test_reader.py::test_nospace", "tests/test_reader.py::test_string_prefixes", "tests/test_reader.py::test_escapes", "tests/test_reader.py::test_unicode_escapes", "tests/test_reader.py::test_complex", "tests/test_reader.py::test_lex_comment_382", "tests/test_reader.py::test_discard", "tests/test_reader.py::test_lex_exception_filtering", "tests/test_reader.py::test_read_error", "tests/test_reader.py::test_shebang" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-03-25 16:17:39+00:00
mit
2,761
hylang__hy-2449
diff --git a/NEWS.rst b/NEWS.rst index eb5c3b3f..1136f216 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -14,6 +14,9 @@ Breaking Changes Forms like `#*word` will attempt to dispatch a macro named `*word`; to unpack a symbol named `word`, write `#* word` (note the space). * Reader macro names are no longer mangled. +* `hy2py`'s recursive mode now expects a module name as input, not any + old directory. You must be in the parent directory of the module + directory. Bug Fixes ------------------------------ @@ -22,6 +25,8 @@ Bug Fixes * Fixed some bugs with traceback pointing. * Fixed some bugs with escaping in bracket f-strings * The parser no longer looks for shebangs in the REPL or `hy -c`. +* `require` with relative module names should now work correctly with + `hy -m`, as well as `hy2py`'s recursive mode. New Features ------------------------------ diff --git a/docs/cli.rst b/docs/cli.rst index f40c18f5..0f8227a0 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -44,7 +44,7 @@ for a complete list of options and :py:ref:`Python's documentation hy2py ----- -``hy2py`` is a program to convert Hy source code into Python source code. Use ``hy2py --help`` for usage instructions. It can take its input from standard input, from a filename, or folder name provided as a command-line argument. If it is a folder, the output parameter (--output/-o) must be provided. When the output parameter is provided, the output will be written into the folder or file, otherwise the result is written to standard output. +``hy2py`` is a program to convert Hy source code into Python source code. Use ``hy2py --help`` for usage instructions. It can take its input from standard input, or from a file or module name provided as a command-line argument. In the case of a module name, the current working directory should be the parent directory of that module, and the output parameter (``--output/-o``) is required. When the output parameter is provided, the output will be written into the folder or file. Otherwise, the result is written to standard output. .. warning:: ``hy2py`` can execute arbitrary code. Don't give it untrusted input. diff --git a/hy/cmdline.py b/hy/cmdline.py index dca3febb..73e02eac 100644 --- a/hy/cmdline.py +++ b/hy/cmdline.py @@ -5,6 +5,7 @@ import io import os import platform import py_compile +import re import runpy import sys from contextlib import nullcontext @@ -332,7 +333,9 @@ def hyc_main(): def hy2py_worker(source, options, filename, output_filepath=None): + source_path = None if isinstance(source, Path): + source_path = source source = source.read_text(encoding="UTF-8") if not output_filepath and options.output: @@ -358,7 +361,13 @@ def hy2py_worker(source, options, filename, output_filepath=None): hst.filename = filename with filtered_hy_exceptions(): - _ast = hy_compile(hst, "__main__", filename=filename, source=source) + _ast = hy_compile( + hst, + re.sub(r'\.hy$', '', '.'.join(source_path.parts)) + if source_path + else '__main__', + filename=filename, + source=source) if options.with_source: print() @@ -385,7 +394,7 @@ def hy2py_main(): "FILE", type=str, nargs="?", - help='Input Hy code (can be file or directory) (use STDIN if "-" or ' + help='Input Hy code (can be file or module) (use STDIN if "-" or ' "not provided)", ) parser.add_argument( diff --git a/hy/core/result_macros.py b/hy/core/result_macros.py index eb296ffd..4d42a003 100644 --- a/hy/core/result_macros.py +++ b/hy/core/result_macros.py @@ -1783,6 +1783,8 @@ def compile_require(compiler, expr, root, entries): dotted("hy.macros.require"), String(module_name), Symbol("None"), + Keyword("target_module_name"), + String(compiler.module.__name__), Keyword("assignments"), ( String("EXPORTS") diff --git a/hy/macros.py b/hy/macros.py index 3f159a21..d684310f 100644 --- a/hy/macros.py +++ b/hy/macros.py @@ -197,7 +197,7 @@ def enable_readers(module, reader, names): reader.reader_macros[name] = namespace["_hy_reader_macros"][name] -def require(source_module, target_module, assignments, prefix=""): +def require(source_module, target_module, assignments, prefix="", target_module_name=None): """Load macros from one module into the namespace of another. This function is called from the macro also named `require`. @@ -213,6 +213,7 @@ def require(source_module, target_module, assignments, prefix=""): prefix (str): If nonempty, its value is prepended to the name of each imported macro. This allows one to emulate namespaced macros, like "mymacromodule.mymacro", which looks like an attribute of a module. Defaults to "" + target_module_name: If true, overrides the apparent name of `target_module`. Returns: bool: Whether or not macros were actually transferred. @@ -230,7 +231,8 @@ def require(source_module, target_module, assignments, prefix=""): return False if not inspect.ismodule(source_module): - source_module = import_module_from_string(source_module, target_module) + source_module = import_module_from_string(source_module, + target_module_name or target_module) source_macros = source_module.__dict__.setdefault("_hy_macros", {}) source_exports = getattr(
hylang/hy
961e9439156660a8303cac34f46f09e7f30cadeb
diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 6cb4c421..4a743e23 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -1,5 +1,3 @@ -# fmt: off - import ast from textwrap import dedent diff --git a/tests/test_bin.py b/tests/test_bin.py index 32e3c84f..b3168243 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# fmt: off import builtins import os @@ -742,26 +741,53 @@ def test_assert(tmp_path, monkeypatch): assert ("bye" in err) == show_msg -def test_hy2py_recursive(tmp_path): - (tmp_path / 'hy').mkdir() - (tmp_path / "hy/first.hy").write_text(""" - (import folder.second [a b]) +def test_hy2py_recursive(monkeypatch, tmp_path): + (tmp_path / 'foo').mkdir() + (tmp_path / 'foo/__init__.py').touch() + (tmp_path / "foo/first.hy").write_text(""" + (import foo.folder.second [a b]) (print a) (print b)""") - (tmp_path / "hy/folder").mkdir() - (tmp_path / "hy/folder/second.hy").write_text(""" + (tmp_path / "foo/folder").mkdir() + (tmp_path / "foo/folder/__init__.py").touch() + (tmp_path / "foo/folder/second.hy").write_text(""" (setv a 1) (setv b "hello world")""") - _, err = run_cmd(["hy2py", (tmp_path / 'hy')], expect=1) + monkeypatch.chdir(tmp_path) + + _, err = run_cmd("hy2py foo", expect=1) assert "ValueError" in err - run_cmd(["hy2py", - (tmp_path / 'hy'), - "--output", (tmp_path / 'py')]) - assert set((tmp_path / 'py').rglob('*')) == { - tmp_path / 'py' / p + run_cmd("hy2py foo --output bar") + assert set((tmp_path / 'bar').rglob('*')) == { + tmp_path / 'bar' / p for p in ('first.py', 'folder', 'folder/second.py')} - output, _ = run_cmd("python3 first.py", cwd = tmp_path / 'py') + output, _ = run_cmd("python3 first.py", cwd = tmp_path / 'bar') assert output == "1\nhello world\n" + + [email protected]('case', ['hy -m', 'hy2py']) +def test_relative_require(case, monkeypatch, tmp_path): + # https://github.com/hylang/hy/issues/2204 + + (tmp_path / 'pkg').mkdir() + (tmp_path / 'pkg' / '__init__.py').touch() + (tmp_path / 'pkg' / 'a.hy').write_text(''' + (defmacro m [] + '(setv x (.upper "hello")))''') + (tmp_path / 'pkg' / 'b.hy').write_text(''' + (require .a [m]) + (m) + (print x)''') + monkeypatch.chdir(tmp_path) + + if case == 'hy -m': + output, _ = run_cmd('hy -m pkg.b') + elif case == 'hy2py': + run_cmd('hy2py pkg -o out') + (tmp_path / 'out' / '__init__.py').touch() + output, _ = run_cmd('python3 -m out.b') + + assert 'HELLO' in output
`hy2py` and relative require here is my module ``` . ├── __init__.py ├── args.hy ├── config.hy ├── log.hy ├── macros.hy ├── main.hy ├── type_helpers.hy └── utils.hy ``` when i try to compile `hy2py args.hy` it raises: ``` hy.errors.HyMacroExpansionError: File "args.hy", line 10 (require .macros *) ^-----------------^ expanding macro require TypeError: the 'package' argument is required to perform a relative import for '.macros' ``` if i remove dot ```hy (require macros *) ``` then it works with `hy2py` but breaks running module with entry point
0.0
961e9439156660a8303cac34f46f09e7f30cadeb
[ "tests/test_bin.py::test_relative_require[hy", "tests/test_bin.py::test_relative_require[hy2py]" ]
[ "tests/compilers/test_ast.py::test_ast_bad_type", "tests/compilers/test_ast.py::test_empty_expr", "tests/compilers/test_ast.py::test_dot_unpacking", "tests/compilers/test_ast.py::test_ast_bad_if", "tests/compilers/test_ast.py::test_ast_valid_if", "tests/compilers/test_ast.py::test_ast_bad_while", "tests/compilers/test_ast.py::test_ast_good_do", "tests/compilers/test_ast.py::test_ast_good_raise", "tests/compilers/test_ast.py::test_ast_raise_from", "tests/compilers/test_ast.py::test_ast_bad_raise", "tests/compilers/test_ast.py::test_ast_good_try", "tests/compilers/test_ast.py::test_ast_bad_try", "tests/compilers/test_ast.py::test_ast_good_except", "tests/compilers/test_ast.py::test_ast_bad_except", "tests/compilers/test_ast.py::test_ast_good_assert", "tests/compilers/test_ast.py::test_ast_bad_assert", "tests/compilers/test_ast.py::test_ast_good_global", "tests/compilers/test_ast.py::test_ast_bad_global", "tests/compilers/test_ast.py::test_ast_good_nonlocal", "tests/compilers/test_ast.py::test_ast_bad_nonlocal", "tests/compilers/test_ast.py::test_ast_good_defclass", "tests/compilers/test_ast.py::test_ast_good_defclass_with_metaclass", "tests/compilers/test_ast.py::test_ast_bad_defclass", "tests/compilers/test_ast.py::test_ast_good_lambda", "tests/compilers/test_ast.py::test_ast_bad_lambda", "tests/compilers/test_ast.py::test_ast_good_yield", "tests/compilers/test_ast.py::test_ast_bad_yield", "tests/compilers/test_ast.py::test_ast_import_mangle_dotted", "tests/compilers/test_ast.py::test_ast_good_import_from", "tests/compilers/test_ast.py::test_ast_require", "tests/compilers/test_ast.py::test_ast_import_require_dotted", "tests/compilers/test_ast.py::test_ast_multi_require", "tests/compilers/test_ast.py::test_ast_good_get", "tests/compilers/test_ast.py::test_ast_bad_get", "tests/compilers/test_ast.py::test_ast_good_cut", "tests/compilers/test_ast.py::test_ast_bad_cut", "tests/compilers/test_ast.py::test_ast_bad_with", "tests/compilers/test_ast.py::test_ast_valid_while", "tests/compilers/test_ast.py::test_ast_valid_for", "tests/compilers/test_ast.py::test_nullary_break_continue", "tests/compilers/test_ast.py::test_ast_expression_basics", "tests/compilers/test_ast.py::test_ast_anon_fns_basics", "tests/compilers/test_ast.py::test_ast_lambda_lists", "tests/compilers/test_ast.py::test_ast_print", "tests/compilers/test_ast.py::test_ast_tuple", "tests/compilers/test_ast.py::test_lambda_list_keywords_rest", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwargs", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwonly", "tests/compilers/test_ast.py::test_lambda_list_keywords_mixed", "tests/compilers/test_ast.py::test_missing_keyword_argument_value", "tests/compilers/test_ast.py::test_ast_unicode_strings", "tests/compilers/test_ast.py::test_ast_unicode_vs_bytes", "tests/compilers/test_ast.py::test_format_string", "tests/compilers/test_ast.py::test_ast_bracket_string", "tests/compilers/test_ast.py::test_literal_newlines", "tests/compilers/test_ast.py::test_compile_error", "tests/compilers/test_ast.py::test_for_compile_error", "tests/compilers/test_ast.py::test_attribute_access", "tests/compilers/test_ast.py::test_misplaced_dots", "tests/compilers/test_ast.py::test_bad_setv", "tests/compilers/test_ast.py::test_defn", "tests/compilers/test_ast.py::test_setv_builtins", "tests/compilers/test_ast.py::test_top_level_unquote", "tests/compilers/test_ast.py::test_bad_exception", "tests/compilers/test_ast.py::test_lots_of_comment_lines", "tests/compilers/test_ast.py::test_compiler_macro_tag_try", "tests/compilers/test_ast.py::test_ast_good_yield_from", "tests/compilers/test_ast.py::test_ast_bad_yield_from", "tests/compilers/test_ast.py::test_eval_generator_with_return", "tests/compilers/test_ast.py::test_futures_imports", "tests/compilers/test_ast.py::test_py", "tests/compilers/test_ast.py::test_pys", "tests/compilers/test_ast.py::test_models_accessible", "tests/compilers/test_ast.py::test_module_prelude", "tests/compilers/test_ast.py::test_pragma", "tests/test_bin.py::test_simple", "tests/test_bin.py::test_stdin", "tests/test_bin.py::test_stdin_multiline", "tests/test_bin.py::test_history", "tests/test_bin.py::test_stdin_comments", "tests/test_bin.py::test_stdin_assignment", "tests/test_bin.py::test_multi_setv", "tests/test_bin.py::test_stdin_error_underline_alignment", "tests/test_bin.py::test_stdin_except_do", "tests/test_bin.py::test_stdin_unlocatable_hytypeerror", "tests/test_bin.py::test_error_parts_length", "tests/test_bin.py::test_syntax_errors", "tests/test_bin.py::test_stdin_bad_repr", "tests/test_bin.py::test_stdin_py_repr", "tests/test_bin.py::test_mangle_m", "tests/test_bin.py::test_ignore_python_env", "tests/test_bin.py::test_cmd", "tests/test_bin.py::test_icmd", "tests/test_bin.py::test_icmd_file", "tests/test_bin.py::test_icmd_and_spy", "tests/test_bin.py::test_empty_file", "tests/test_bin.py::test_missing_file", "tests/test_bin.py::test_file_with_args", "tests/test_bin.py::test_hyc", "tests/test_bin.py::test_hyc_missing_file", "tests/test_bin.py::test_builtins", "tests/test_bin.py::test_no_main", "tests/test_bin.py::test_byte_compile[cmd_fmt0-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt0-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt1-prevent_by_option]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-normal]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_force]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_env]", "tests/test_bin.py::test_byte_compile[cmd_fmt2-prevent_by_option]", "tests/test_bin.py::test_module_main_file", "tests/test_bin.py::test_file_main_file", "tests/test_bin.py::test_file_sys_path", "tests/test_bin.py::test_module_no_main", "tests/test_bin.py::test_sys_executable", "tests/test_bin.py::test_file_no_extension", "tests/test_bin.py::test_circular_macro_require", "tests/test_bin.py::test_macro_require", "tests/test_bin.py::test_tracebacks", "tests/test_bin.py::test_traceback_shebang", "tests/test_bin.py::test_hystartup", "tests/test_bin.py::test_output_buffering", "tests/test_bin.py::test_uufileuu", "tests/test_bin.py::test_assert", "tests/test_bin.py::test_hy2py_recursive" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-03 14:33:54+00:00
mit
2,762
hylang__hy-2454
diff --git a/NEWS.rst b/NEWS.rst index cbd90377..d4765e98 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -29,6 +29,8 @@ Bug Fixes * The parser no longer looks for shebangs in the REPL or `hy -c`. * `require` with relative module names should now work correctly with `hy -m`, as well as `hy2py`'s recursive mode. +* `hy.models.Symbol` no longer allows constructing a symbol beginning + with `#`. New Features ------------------------------ diff --git a/hy/reader/hy_reader.py b/hy/reader/hy_reader.py index 016b94e5..923b820e 100644 --- a/hy/reader/hy_reader.py +++ b/hy/reader/hy_reader.py @@ -98,7 +98,7 @@ def as_identifier(ident, reader=None): if reader is None: if ( not ident - or ident[:1] == ":" + or ident[0] in ":#" or any(isnormalizedspace(c) for c in ident) or HyReader.NON_IDENT.intersection(ident) ):
hylang/hy
6bb0ee93ac88a40d44d14dae267b7476ffd7a265
diff --git a/tests/macros/test_macro_processor.py b/tests/macros/test_macro_processor.py index 5fb31791..464dcca8 100644 --- a/tests/macros/test_macro_processor.py +++ b/tests/macros/test_macro_processor.py @@ -55,7 +55,7 @@ def test_macroexpand_nan(): def test_macroexpand_source_data(): # https://github.com/hylang/hy/issues/1944 - ast = Expression([Symbol("#@"), String("a")]) + ast = Expression([Symbol("when"), String("a")]) ast.start_line = 3 ast.start_column = 5 bad = macroexpand_1(ast, "hy.core.macros") diff --git a/tests/test_models.py b/tests/test_models.py index c000e8bd..9ad85154 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -28,7 +28,8 @@ def test_symbol_or_keyword(): for x in ("foo", "foo-bar", "foo_bar", "✈é😂⁂"): assert str(Symbol(x)) == x assert Keyword(x).name == x - for x in ("", ":foo", "5"): + for x in ("", ":foo", "5", "#foo"): + # https://github.com/hylang/hy/issues/2383 with pytest.raises(ValueError): Symbol(x) assert Keyword(x).name == x
`(hy.models.Symbol "#foo")` should be an error for the same reason as `(hy.models.Symbol "5")`: `#foo` doesn't parse as a symbol. It parses as a reader-macro call.
0.0
6bb0ee93ac88a40d44d14dae267b7476ffd7a265
[ "tests/test_models.py::test_symbol_or_keyword" ]
[ "tests/macros/test_macro_processor.py::test_preprocessor_simple", "tests/macros/test_macro_processor.py::test_preprocessor_expression", "tests/macros/test_macro_processor.py::test_preprocessor_exceptions", "tests/macros/test_macro_processor.py::test_macroexpand_nan", "tests/macros/test_macro_processor.py::test_macroexpand_source_data", "tests/test_models.py::test_wrap_int", "tests/test_models.py::test_wrap_tuple", "tests/test_models.py::test_wrap_nested_expr", "tests/test_models.py::test_replace_int", "tests/test_models.py::test_invalid_bracket_strings", "tests/test_models.py::test_replace_str", "tests/test_models.py::test_replace_tuple", "tests/test_models.py::test_list_add", "tests/test_models.py::test_list_slice", "tests/test_models.py::test_hydict_methods", "tests/test_models.py::test_set", "tests/test_models.py::test_equality", "tests/test_models.py::test_number_model_copy", "tests/test_models.py::test_compound_model_repr", "tests/test_models.py::test_recursive_model_detection" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-06-07 17:51:27+00:00
mit
2,763
hylang__hy-2471
diff --git a/NEWS.rst b/NEWS.rst index 345094bb..f9acfdcc 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -16,6 +16,11 @@ New Features ------------------------------ * `defn`, `defn/a`, and `defclass` now support type parameters. +Misc. Improvements +------------------------------ +* Some syntax errors raised by core macros now have more informative + messages. + 0.27.0 (released 2023-07-06) ============================= diff --git a/hy/core/result_macros.py b/hy/core/result_macros.py index 1fad8e85..2db198d5 100644 --- a/hy/core/result_macros.py +++ b/hy/core/result_macros.py @@ -72,7 +72,9 @@ def pvalue(root, wanted): def maybe_annotated(target): - return pexpr(sym("annotate") + target + FORM) | target >> (lambda x: (x, None)) + return ( + pexpr(sym("annotate") + target + FORM).named('`annotate` form') | + (target >> (lambda x: (x, None)))) def dotted(name): @@ -727,9 +729,9 @@ loopers = many( ) -@pattern_macro( - ["for"], [brackets(loopers), many(notpexpr("else")) + maybe(dolike("else"))] -) +@pattern_macro(["for"], [ + brackets(loopers, name = 'square-bracketed loop clauses'), + many(notpexpr("else")) + maybe(dolike("else"))]) @pattern_macro(["lfor", "sfor", "gfor"], [loopers, FORM]) @pattern_macro(["dfor"], [loopers, finished]) # Here `finished` is a hack replacement for FORM + FORM: diff --git a/hy/macros.py b/hy/macros.py index d684310f..c1ee5604 100644 --- a/hy/macros.py +++ b/hy/macros.py @@ -68,7 +68,7 @@ def pattern_macro(names, pattern, shadow=None): raise hy_compiler._syntax_error( expr[min(e.state.pos + 1, len(expr) - 1)], "parse error for pattern macro '{}': {}".format( - root, e.msg.replace("<EOF>", "end of form") + root, e.msg.replace("end of input", "end of macro call") ), ) return fn(hy_compiler, expr, root, *parse_tree) diff --git a/hy/model_patterns.py b/hy/model_patterns.py index 14d06a33..1d703395 100644 --- a/hy/model_patterns.py +++ b/hy/model_patterns.py @@ -31,11 +31,11 @@ from hy.models import ( Tuple, ) -FORM = some(lambda _: True) -SYM = some(lambda x: isinstance(x, Symbol)) -KEYWORD = some(lambda x: isinstance(x, Keyword)) -STR = some(lambda x: isinstance(x, String)) # matches literal strings only! -LITERAL = some(lambda x: isinstance(x, (String, Integer, Float, Complex, Bytes))) +FORM = some(lambda _: True).named('form') +SYM = some(lambda x: isinstance(x, Symbol)).named('Symbol') +KEYWORD = some(lambda x: isinstance(x, Keyword)).named('Keyword') +STR = some(lambda x: isinstance(x, String)).named('String') # matches literal strings only! +LITERAL = some(lambda x: isinstance(x, (String, Integer, Float, Complex, Bytes))).named('literal') def sym(wanted): @@ -49,9 +49,10 @@ def keepsym(wanted): def _sym(wanted, f=lambda x: x): + name = '`' + wanted + '`' if wanted.startswith(":"): - return f(a(Keyword(wanted[1:]))) - return f(some(lambda x: x == Symbol(wanted))) + return f(a(Keyword(wanted[1:]))).named(name) + return f(some(lambda x: x == Symbol(wanted))).named(name) def whole(parsers): @@ -64,29 +65,23 @@ def whole(parsers): return reduce(add, parsers) + skip(finished) -def _grouped(group_type, parsers): - return some(lambda x: isinstance(x, group_type)) >> ( - lambda x: group_type(whole(parsers).parse(x)).replace(x, recursive=False) +def _grouped(group_type, syntax_example, name, parsers): + return ( + some(lambda x: isinstance(x, group_type)).named(name or + f'{group_type.__name__} (i.e., `{syntax_example}`)') >> + (lambda x: group_type(whole(parsers).parse(x)).replace(x, recursive=False)) ) - - -def brackets(*parsers): +def brackets(*parsers, name = None): "Parse the given parsers inside square brackets." - return _grouped(List, parsers) - - -def in_tuple(*parsers): - return _grouped(Tuple, parsers) - - -def braces(*parsers): + return _grouped(List, '[ … ]', name, parsers) +def in_tuple(*parsers, name = None): + return _grouped(Tuple, '#( … )', name, parsers) +def braces(*parsers, name = None): "Parse the given parsers inside curly braces" - return _grouped(Dict, parsers) - - -def pexpr(*parsers): + return _grouped(Dict, '{ … }', name, parsers) +def pexpr(*parsers, name = None): "Parse the given parsers inside a parenthesized expression." - return _grouped(Expression, parsers) + return _grouped(Expression, '( … )', name, parsers) def dolike(head):
hylang/hy
39be258387c3ced1ee0ca5b1376917d078970f6a
diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index d3d91a5d..56e90389 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -628,3 +628,15 @@ def test_module_prelude(): def test_pragma(): cant_compile("(pragma)") cant_compile("(pragma :native-code :namespaced-symbols :give-user-a-pony)") + + +def test_error_with_expectation(): + def check(code, expected): + assert cant_compile(code).msg.endswith("expected: " + expected) + + check("(defmacro)", "Symbol") + check("(quote)", "form") + check("(py)", "String") + check("(py a)", "String") + check('(py "foo" a)', "end of macro call") + check('(for a)', "square-bracketed loop clauses")
Improvement of error messages for pattern macros Advancements to `funcpaserlib` such as https://github.com/vlasovskikh/funcparserlib/issues/52 should allow improving error messages produced while parsing calls to Hy's core pattern macros. In an error like the below example, `expected: some(...)` could probably be changed to `expected symbol`. ``` Traceback (most recent call last): File "<string>", line 1 (defmacro 1) ^ hy.errors.HySyntaxError: parse error for pattern macro 'defmacro': got unexpected token: hy.models.Integer(1), expected: some(...) ``` It's conceivable that most of the patterns for Hy's core macros are too complex to admit useful automatic descriptions of the kind of form that's expected. If so, it's probably better to forget about this than to hand-write descriptions for lots of patterns. Manually writing lots of error messages like that is the sort of thing I intended to avoid by using `funcparserlib` in the first place. A simpler sort of improvement would be rewording "unexpected end of input", as provoked by e.g. `(defmacro)`, to something that makes it clearer that the form, as opposed to the entire file, ended prematurely.
0.0
39be258387c3ced1ee0ca5b1376917d078970f6a
[ "tests/compilers/test_ast.py::test_error_with_expectation" ]
[ "tests/compilers/test_ast.py::test_ast_bad_type", "tests/compilers/test_ast.py::test_empty_expr", "tests/compilers/test_ast.py::test_dot_unpacking", "tests/compilers/test_ast.py::test_ast_bad_if", "tests/compilers/test_ast.py::test_ast_valid_if", "tests/compilers/test_ast.py::test_ast_bad_while", "tests/compilers/test_ast.py::test_ast_good_do", "tests/compilers/test_ast.py::test_ast_good_raise", "tests/compilers/test_ast.py::test_ast_raise_from", "tests/compilers/test_ast.py::test_ast_bad_raise", "tests/compilers/test_ast.py::test_ast_good_try", "tests/compilers/test_ast.py::test_ast_bad_try", "tests/compilers/test_ast.py::test_ast_good_except", "tests/compilers/test_ast.py::test_ast_bad_except", "tests/compilers/test_ast.py::test_ast_good_assert", "tests/compilers/test_ast.py::test_ast_bad_assert", "tests/compilers/test_ast.py::test_ast_good_global", "tests/compilers/test_ast.py::test_ast_bad_global", "tests/compilers/test_ast.py::test_ast_good_nonlocal", "tests/compilers/test_ast.py::test_ast_bad_nonlocal", "tests/compilers/test_ast.py::test_ast_good_defclass", "tests/compilers/test_ast.py::test_ast_good_defclass_with_metaclass", "tests/compilers/test_ast.py::test_ast_bad_defclass", "tests/compilers/test_ast.py::test_ast_good_lambda", "tests/compilers/test_ast.py::test_ast_bad_lambda", "tests/compilers/test_ast.py::test_ast_good_yield", "tests/compilers/test_ast.py::test_ast_bad_yield", "tests/compilers/test_ast.py::test_ast_import_mangle_dotted", "tests/compilers/test_ast.py::test_ast_good_import_from", "tests/compilers/test_ast.py::test_ast_require", "tests/compilers/test_ast.py::test_ast_import_require_dotted", "tests/compilers/test_ast.py::test_ast_multi_require", "tests/compilers/test_ast.py::test_ast_good_get", "tests/compilers/test_ast.py::test_ast_bad_get", "tests/compilers/test_ast.py::test_ast_good_cut", "tests/compilers/test_ast.py::test_ast_bad_cut", "tests/compilers/test_ast.py::test_ast_bad_with", "tests/compilers/test_ast.py::test_ast_valid_while", "tests/compilers/test_ast.py::test_ast_valid_for", "tests/compilers/test_ast.py::test_nullary_break_continue", "tests/compilers/test_ast.py::test_ast_expression_basics", "tests/compilers/test_ast.py::test_ast_anon_fns_basics", "tests/compilers/test_ast.py::test_ast_lambda_lists", "tests/compilers/test_ast.py::test_ast_print", "tests/compilers/test_ast.py::test_ast_tuple", "tests/compilers/test_ast.py::test_lambda_list_keywords_rest", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwargs", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwonly", "tests/compilers/test_ast.py::test_lambda_list_keywords_mixed", "tests/compilers/test_ast.py::test_missing_keyword_argument_value", "tests/compilers/test_ast.py::test_ast_unicode_strings", "tests/compilers/test_ast.py::test_ast_unicode_vs_bytes", "tests/compilers/test_ast.py::test_format_string", "tests/compilers/test_ast.py::test_ast_bracket_string", "tests/compilers/test_ast.py::test_literal_newlines", "tests/compilers/test_ast.py::test_compile_error", "tests/compilers/test_ast.py::test_for_compile_error", "tests/compilers/test_ast.py::test_attribute_access", "tests/compilers/test_ast.py::test_misplaced_dots", "tests/compilers/test_ast.py::test_bad_setv", "tests/compilers/test_ast.py::test_defn", "tests/compilers/test_ast.py::test_setv_builtins", "tests/compilers/test_ast.py::test_top_level_unquote", "tests/compilers/test_ast.py::test_bad_exception", "tests/compilers/test_ast.py::test_lots_of_comment_lines", "tests/compilers/test_ast.py::test_compiler_macro_tag_try", "tests/compilers/test_ast.py::test_ast_good_yield_from", "tests/compilers/test_ast.py::test_ast_bad_yield_from", "tests/compilers/test_ast.py::test_eval_generator_with_return", "tests/compilers/test_ast.py::test_futures_imports", "tests/compilers/test_ast.py::test_py", "tests/compilers/test_ast.py::test_pys", "tests/compilers/test_ast.py::test_models_accessible", "tests/compilers/test_ast.py::test_module_prelude", "tests/compilers/test_ast.py::test_pragma" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-25 19:51:58+00:00
mit
2,764
hylang__hy-2514
diff --git a/NEWS.rst b/NEWS.rst index 4b3e7082..969f8aad 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -34,6 +34,7 @@ Misc. Improvements ------------------------------ * Some syntax errors raised by core macros now have more informative messages. +* Logical operators now compile to simpler Python code in some cases. Bug Fixes ------------------------------ diff --git a/hy/core/result_macros.py b/hy/core/result_macros.py index 81c24ffe..9ed6c65e 100644 --- a/hy/core/result_macros.py +++ b/hy/core/result_macros.py @@ -256,48 +256,66 @@ def compile_unary_operator(compiler, expr, root, arg): def compile_logical_or_and_and_operator(compiler, expr, operator, args): ops = {"and": (ast.And, True), "or": (ast.Or, None)} opnode, default = ops[operator] - osym = expr[0] if len(args) == 0: - return asty.Constant(osym, value=default) - elif len(args) == 1: - return compiler.compile(args[0]) - ret = Result() - values = list(map(compiler.compile, args)) - if any(value.stmts for value in values): - # Compile it to an if...else sequence - var = compiler.get_anon_var() - name = asty.Name(osym, id=var, ctx=ast.Store()) - expr_name = asty.Name(osym, id=var, ctx=ast.Load()) - temp_variables = [name, expr_name] - - def make_assign(value, node=None): - positioned_name = asty.Name(node or osym, id=var, ctx=ast.Store()) - temp_variables.append(positioned_name) - return asty.Assign(node or osym, targets=[positioned_name], value=value) - - current = root = [] - for i, value in enumerate(values): - if value.stmts: - node = value.stmts[0] - current.extend(value.stmts) + return asty.Constant(expr[0], value=default) + + ret = None + var = None # A temporary variable for assigning results to + assignment = None # The current assignment to `var` + stmts = None # The current statement list + + def put(node, value): + # Save the result of the operation so far to `var`. + nonlocal var, assignment + if var is None: + var = compiler.get_anon_var() + name = asty.Name(node, id=var, ctx=ast.Store()) + ret.temp_variables.append(name) + return (assignment := asty.Assign(node, targets=[name], value=value)) + + def get(node): + # Get the value of `var`, creating it if necessary. + if var is None: + stmts.append(put(node, ret.force_expr)) + name = asty.Name(node, id=var, ctx=ast.Load()) + ret.temp_variables.append(name) + return name + + for value in map(compiler.compile, args): + if ret is None: + # This is the first iteration. Don't actually introduce a + # `BoolOp` yet; the unary case doesn't need it. + ret = value + stmts = ret.stmts + elif value.stmts: + # Save the result of the statements to the temporary + # variable. Use an `if` statement to implement + # short-circuiting from this point. + node = value.stmts[0] + cond = get(node) + if operator == "or": + # Negate the conditional. + cond = asty.UnaryOp(node, op=ast.Not(), operand=cond) + branch = asty.If(node, test=cond, body=value.stmts, orelse=[]) + stmts.append(branch) + stmts = branch.body + stmts.append(put(node, value.force_expr)) + else: + # Add this value to the current `BoolOp`, or create a new + # one if we don't have one. + value = value.force_expr + def enbool(expr): + if isinstance(expr, ast.BoolOp): + expr.values.append(value) + return expr + return asty.BoolOp(expr, op=opnode(), values=[expr, value]) + if assignment: + assignment.value = enbool(assignment.value) else: - node = value.expr - current.append(make_assign(value.force_expr, value.force_expr)) - if i == len(values) - 1: - # Skip a redundant 'if'. - break - if operator == "and": - cond = expr_name - elif operator == "or": - cond = asty.UnaryOp(node, op=ast.Not(), operand=expr_name) - current.append(asty.If(node, test=cond, body=[], orelse=[])) - current = current[-1].body - ret = sum(root, ret) - ret += Result(expr=expr_name, temp_variables=temp_variables) - else: - ret += asty.BoolOp( - osym, op=opnode(), values=[value.force_expr for value in values] - ) + ret.expr = enbool(ret.expr) + + if var: + ret.expr = get(expr) return ret
hylang/hy
902233d854d765058927402d60f1ee8bef02daf8
diff --git a/tests/compilers/test_ast.py b/tests/compilers/test_ast.py index 27cf3505..001c2e55 100644 --- a/tests/compilers/test_ast.py +++ b/tests/compilers/test_ast.py @@ -449,6 +449,15 @@ def test_literal_newlines(): assert s("#[[\rhello\rworld]]") == "hello\nworld" +def test_linear_boolop(): + """Operations like `(and 1 2 3)` should use only one `BoolOp`, + instead of an equivalent nested sequence of `BoolOp`s.""" + for op in ("and", "or"): + node = can_compile(f'({op} 1 2.0 True "hi" 5)').body[0].value + assert len(node.values) == 5 + assert all(isinstance(v, ast.Constant) for v in node.values) + + def test_compile_error(): """Ensure we get compile error in tricky cases""" with pytest.raises(HyLanguageError) as excinfo: diff --git a/tests/compilers/test_compiler.py b/tests/compilers/test_compiler.py index 64fd2a01..4269fe0d 100644 --- a/tests/compilers/test_compiler.py +++ b/tests/compilers/test_compiler.py @@ -3,6 +3,8 @@ import types from hy import compiler from hy.models import Expression, Integer, List, Symbol +from hy.reader import read_many +from hy.compiler import hy_compile def make_expression(*args): @@ -14,6 +16,10 @@ def make_expression(*args): return h.replace(h) +def hy2py(s): + return ast.unparse(hy_compile(read_many(s), "test", import_stdlib=False)) + + def test_compiler_bare_names(): """ Check that the compiler doesn't drop bare names from code branches @@ -58,3 +64,15 @@ def test_compiler_yield_return(): assert isinstance(body[0].value, ast.Yield) assert isinstance(body[1], ast.Return) assert isinstance(body[1].value, ast.BinOp) + + +# https://github.com/hylang/hy/issues/854 +def test_compact_logic(): + """ + Check that we don't generate multiple unnecessary if-statements + when compiling the short-circuiting operators. + """ + py = hy2py("(and 1 2 3 (do (setv x 4) x) 5 6)") + assert py.count("if") == 1 + py = hy2py("(or 1 2 3 (do (setv x 4) x) 5 6 (do (setv y 7)))") + assert py.count("if") == 2
Optimize and/or Depends on #824. Related #842. Even in the case that `and`/`or` contains a statement, it may have several expressions in a row that don't need to be converted to `if` branches. Hy could avoid redundant assignments by keeping those runs as expressions and only assigning the result to an anonymous variable. For example: ``` Python => (print (and 1 2 3 (setv x 1) 4 5 6)) _hy_anon_var_1 = 1 and 2 and 3 if _hy_anon_var_1: x = 1 _hy_anon_var_1 = x and 4 and 5 and 6 print(_hy_anon_var_1) 6 ```
0.0
902233d854d765058927402d60f1ee8bef02daf8
[ "tests/compilers/test_compiler.py::test_compact_logic" ]
[ "tests/compilers/test_ast.py::test_ast_bad_type", "tests/compilers/test_ast.py::test_empty_expr", "tests/compilers/test_ast.py::test_dot_unpacking", "tests/compilers/test_ast.py::test_ast_bad_if", "tests/compilers/test_ast.py::test_ast_valid_if", "tests/compilers/test_ast.py::test_ast_bad_while", "tests/compilers/test_ast.py::test_ast_good_do", "tests/compilers/test_ast.py::test_ast_good_raise", "tests/compilers/test_ast.py::test_ast_raise_from", "tests/compilers/test_ast.py::test_ast_bad_raise", "tests/compilers/test_ast.py::test_ast_good_try", "tests/compilers/test_ast.py::test_ast_bad_try", "tests/compilers/test_ast.py::test_ast_good_except", "tests/compilers/test_ast.py::test_ast_bad_except", "tests/compilers/test_ast.py::test_ast_good_assert", "tests/compilers/test_ast.py::test_ast_bad_assert", "tests/compilers/test_ast.py::test_ast_good_global", "tests/compilers/test_ast.py::test_ast_bad_global", "tests/compilers/test_ast.py::test_ast_good_nonlocal", "tests/compilers/test_ast.py::test_ast_bad_nonlocal", "tests/compilers/test_ast.py::test_ast_good_defclass", "tests/compilers/test_ast.py::test_ast_good_defclass_with_metaclass", "tests/compilers/test_ast.py::test_ast_bad_defclass", "tests/compilers/test_ast.py::test_ast_good_lambda", "tests/compilers/test_ast.py::test_ast_bad_lambda", "tests/compilers/test_ast.py::test_ast_good_yield", "tests/compilers/test_ast.py::test_ast_bad_yield", "tests/compilers/test_ast.py::test_ast_import_mangle_dotted", "tests/compilers/test_ast.py::test_ast_good_import_from", "tests/compilers/test_ast.py::test_ast_require", "tests/compilers/test_ast.py::test_ast_import_require_dotted", "tests/compilers/test_ast.py::test_ast_multi_require", "tests/compilers/test_ast.py::test_ast_good_get", "tests/compilers/test_ast.py::test_ast_bad_get", "tests/compilers/test_ast.py::test_ast_good_cut", "tests/compilers/test_ast.py::test_ast_bad_cut", "tests/compilers/test_ast.py::test_ast_bad_with", "tests/compilers/test_ast.py::test_ast_valid_while", "tests/compilers/test_ast.py::test_ast_valid_for", "tests/compilers/test_ast.py::test_nullary_break_continue", "tests/compilers/test_ast.py::test_ast_expression_basics", "tests/compilers/test_ast.py::test_ast_anon_fns_basics", "tests/compilers/test_ast.py::test_ast_lambda_lists", "tests/compilers/test_ast.py::test_ast_print", "tests/compilers/test_ast.py::test_ast_tuple", "tests/compilers/test_ast.py::test_lambda_list_keywords_rest", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwargs", "tests/compilers/test_ast.py::test_lambda_list_keywords_kwonly", "tests/compilers/test_ast.py::test_lambda_list_keywords_mixed", "tests/compilers/test_ast.py::test_missing_keyword_argument_value", "tests/compilers/test_ast.py::test_ast_unicode_strings", "tests/compilers/test_ast.py::test_ast_unicode_vs_bytes", "tests/compilers/test_ast.py::test_format_string", "tests/compilers/test_ast.py::test_ast_bracket_string", "tests/compilers/test_ast.py::test_literal_newlines", "tests/compilers/test_ast.py::test_linear_boolop", "tests/compilers/test_ast.py::test_compile_error", "tests/compilers/test_ast.py::test_for_compile_error", "tests/compilers/test_ast.py::test_attribute_access", "tests/compilers/test_ast.py::test_misplaced_dots", "tests/compilers/test_ast.py::test_bad_setv", "tests/compilers/test_ast.py::test_defn", "tests/compilers/test_ast.py::test_setv_builtins", "tests/compilers/test_ast.py::test_top_level_unquote", "tests/compilers/test_ast.py::test_bad_exception", "tests/compilers/test_ast.py::test_lots_of_comment_lines", "tests/compilers/test_ast.py::test_compiler_macro_tag_try", "tests/compilers/test_ast.py::test_ast_good_yield_from", "tests/compilers/test_ast.py::test_ast_bad_yield_from", "tests/compilers/test_ast.py::test_eval_generator_with_return", "tests/compilers/test_ast.py::test_futures_imports", "tests/compilers/test_ast.py::test_py", "tests/compilers/test_ast.py::test_pys", "tests/compilers/test_ast.py::test_models_accessible", "tests/compilers/test_ast.py::test_module_prelude", "tests/compilers/test_ast.py::test_pragma", "tests/compilers/test_ast.py::test_error_with_expectation", "tests/compilers/test_compiler.py::test_compiler_bare_names", "tests/compilers/test_compiler.py::test_compiler_yield_return" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-09-30 20:44:01+00:00
mit
2,765
hylang__hy-2522
diff --git a/NEWS.rst b/NEWS.rst index 61d9a3fb..d167fe40 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -50,6 +50,8 @@ Bug Fixes * Fixed incomplete recognition of macro calls with a unary dotted head like `((. defn) f [])`. * `~@ #*` now produces a syntax error instead of a nonsensical result. +* Fixed parsing of infinite and NaN imaginary literals with an + uppercase "J". * Fixed `hy.eval` failing on `defreader` or `require` forms that install a new reader. * `require` now warns when you shadow a core macro, like `defmacro` diff --git a/docs/syntax.rst b/docs/syntax.rst index 1a55eb7a..54188fda 100644 --- a/docs/syntax.rst +++ b/docs/syntax.rst @@ -152,7 +152,8 @@ few extensions: interpreted in octal like they do in C. For octal, use the prefix ``0o``, as in Python. - ``NaN``, ``Inf``, and ``-Inf`` are understood as literals. Each produces a - :class:`Float <hy.models.Float>`. + :class:`Float <hy.models.Float>`. These are case-sensitive, unlike other uses + of letters in numeric literals (``1E2``, ``0XFF``, ``5J``, etc.). - Hy allows complex literals as understood by the constructor for :class:`complex`, such as ``5+4j``. (This is also legal Python, but Hy reads it as a single :class:`Complex <hy.models.Complex>`, and doesn't otherwise diff --git a/hy/models.py b/hy/models.py index 3ce3a74e..23ccb6c5 100644 --- a/hy/models.py +++ b/hy/models.py @@ -361,7 +361,7 @@ class Complex(Object, complex): if isinstance(real, str): value = super().__new__(cls, strip_digit_separators(real)) p1, _, p2 = real.lstrip("+-").replace("-", "+").partition("+") - check_inf_nan_cap(p1, value.imag if "j" in p1 else value.real) + check_inf_nan_cap(p1, value.imag if "j" in p1.lower() else value.real) if p2: check_inf_nan_cap(p2, value.imag) return value
hylang/hy
fa639893e5b56e3f3cc9f6ed46fd654dfaf35754
diff --git a/tests/test_reader.py b/tests/test_reader.py index 6127a11c..3ae60daf 100644 --- a/tests/test_reader.py +++ b/tests/test_reader.py @@ -225,9 +225,13 @@ def test_lex_expression_complex(): def f(x): return [Expression([Symbol("foo"), x])] + assert t("2j") == f(Complex(2.0j)) + assert t("2J") == f(Complex(2.0j)) assert t("2.j") == f(Complex(2.0j)) + assert t("2.J") == f(Complex(2.0j)) assert t("-0.5j") == f(Complex(-0.5j)) assert t("1.e7j") == f(Complex(1e7j)) + assert t("1.e7J") == f(Complex(1e7j)) assert t("j") == f(Symbol("j")) assert t("J") == f(Symbol("J")) assert isnan(t("NaNj")[0][1].imag) @@ -236,6 +240,13 @@ def test_lex_expression_complex(): assert t("Inf-Infj") == f(Complex(complex(float("inf"), float("-inf")))) assert t("Inf-INFj") == f(Symbol("Inf-INFj")) + # https://github.com/hylang/hy/issues/2521 + assert isnan(t("NaNJ")[0][1].imag) + assert t("nanJ") == f(Symbol("nanJ")) + assert t("InfJ") == f(Complex(complex(0, float("inf")))) + assert t("iNfJ") == f(Symbol("iNfJ")) + assert t("Inf-INFJ") == f(Symbol("Inf-INFJ")) + def test_lex_digit_separators():
Any capitalization of `NaN` and `Inf` are parsed as imaginary numbers with uppercase suffix `J` This issue seems related to #1288 and #1294. Floating-point special values such as `NaN` and `Inf` are required to be capitalized exactly as such, but when used in imaginary number literals with _uppercase_ `J` suffix, any capitalization is allowed. In the same spirit as #1288, I believe this is unintended/undesired behavior. ```hy NaNj ; valid (good) NANj ; invalid (good) Infj ; valid (good) iNfj ; invalid (good) NaNJ ; valid (good) NANJ ; valid (should not be!) InfJ ; valid (good) iNfJ ; valid (should not be!) ``` Interestingly enough, this behavior only occurs in pure-imaginary literals; it doesn't surface in "compound" complex literals, which seem to have the correct behavior: ```hy 1+NaNj ; valid (good) 1+NANJ ; invalid (good) ```
0.0
fa639893e5b56e3f3cc9f6ed46fd654dfaf35754
[ "tests/test_reader.py::test_lex_expression_complex" ]
[ "tests/test_reader.py::test_lex_exception", "tests/test_reader.py::test_unbalanced_exception", "tests/test_reader.py::test_lex_single_quote_err", "tests/test_reader.py::test_lex_expression_symbols", "tests/test_reader.py::test_symbol_and_sugar", "tests/test_reader.py::test_lex_expression_strings", "tests/test_reader.py::test_lex_expression_integer", "tests/test_reader.py::test_lex_symbols", "tests/test_reader.py::test_lex_strings", "tests/test_reader.py::test_lex_strings_exception", "tests/test_reader.py::test_lex_bracket_strings", "tests/test_reader.py::test_lex_integers", "tests/test_reader.py::test_lex_expression_float", "tests/test_reader.py::test_lex_big_float", "tests/test_reader.py::test_lex_nan_and_inf", "tests/test_reader.py::test_lex_digit_separators", "tests/test_reader.py::test_leading_zero", "tests/test_reader.py::test_dotted_identifiers", "tests/test_reader.py::test_lex_bad_attrs", "tests/test_reader.py::test_lists", "tests/test_reader.py::test_dicts", "tests/test_reader.py::test_lex_column_counting", "tests/test_reader.py::test_lex_column_counting_with_literal_newline", "tests/test_reader.py::test_lex_line_counting_multi", "tests/test_reader.py::test_lex_line_counting_multi_inner", "tests/test_reader.py::test_line_counting_dotted", "tests/test_reader.py::test_sets", "tests/test_reader.py::test_nospace", "tests/test_reader.py::test_string_prefixes", "tests/test_reader.py::test_escapes", "tests/test_reader.py::test_unicode_escapes", "tests/test_reader.py::test_complex", "tests/test_reader.py::test_lex_comment_382", "tests/test_reader.py::test_discard", "tests/test_reader.py::test_lex_exception_filtering", "tests/test_reader.py::test_read_error", "tests/test_reader.py::test_shebang" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-10-16 14:36:34+00:00
mit
2,766
hylang__hy-2556
diff --git a/NEWS.rst b/NEWS.rst index ac9068e1..2b48f0ae 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -20,6 +20,10 @@ New Features * You can now set `repl-ps1` and `repl-ps2` in your `HYSTARTUP` to customize `sys.ps1` and `sys.ps2` for the Hy REPL. +Bug Fixes +------------------------------ +* Tracebacks now point to the correct code in more cases. + 0.28.0 (released 2024-01-05) ============================= diff --git a/docs/semantics.rst b/docs/semantics.rst index 626c091d..1dcd5b36 100644 --- a/docs/semantics.rst +++ b/docs/semantics.rst @@ -3,7 +3,8 @@ Semantics ============== This chapter describes features of Hy semantics that differ from Python's and -aren't better categorized elsewhere, such as in the chapter :doc:`macros`. +aren't better categorized elsewhere, such as in the chapter :doc:`macros`. Each +is a potential trap for the unwary. .. _implicit-names: @@ -71,3 +72,28 @@ following: Why didn't the second run of ``b.hy`` print ``2``? Because ``b.hy`` was unchanged, so it didn't get recompiled, so its bytecode still had the old expansion of the macro ``m``. + +Traceback positioning +--------------------- + +When an exception results in a traceback, Python uses line and column numbers +associated with AST nodes to point to the source code associated with the +exception: + +.. code-block:: text + + Traceback (most recent call last): + File "cinco.py", line 4, in <module> + find() + File "cinco.py", line 2, in find + print(chippy) + ^^^^^^ + NameError: name 'chippy' is not defined + +This position information is stored as attributes of the AST nodes. Hy tries to +set these attributes appropriately so that it can also produce correctly +targeted tracebacks, but there are cases where it can't, such as when +evaluating code that was built at runtime out of explicit calls to :ref:`model +constructors <models>`. Python still requires line and column numbers, so Hy +sets these to 1 as a fallback; consequently, tracebacks can point to the +beginning of a file even though the relevant code isn't there. diff --git a/hy/compiler.py b/hy/compiler.py index a72af420..5aaa4b1a 100755 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -422,7 +422,7 @@ class HyASTCompiler: # These are unexpected errors that will--hopefully--never be seen # by the user. f_exc = traceback.format_exc() - exc_msg = "Internal Compiler Bug 😱\n⤷ {}".format(f_exc) + exc_msg = "Internal Compiler Bug\n {}".format(f_exc) raise HyCompileError(exc_msg) def _syntax_error(self, expr, message): diff --git a/hy/core/result_macros.py b/hy/core/result_macros.py index c4676f79..f43bdabb 100644 --- a/hy/core/result_macros.py +++ b/hy/core/result_macros.py @@ -135,7 +135,7 @@ def compile_eval_foo_compile(compiler, expr, root, body): raise HyEvalError(str(e), compiler.filename, body, compiler.source) return ( - compiler.compile(as_model(value)) + compiler.compile(as_model(value).replace(expr)) if root == "do-mac" else compiler._compile_branch(body) if root == "eval-and-compile" diff --git a/hy/models.py b/hy/models.py index 23ccb6c5..ad370d3f 100644 --- a/hy/models.py +++ b/hy/models.py @@ -385,12 +385,19 @@ class Sequence(Object, tuple): for this purpose. """ + _extra_kwargs = () + def replace(self, other, recursive=True): - if recursive: - for x in self: - replace_hy_obj(x, other) - Object.replace(self, other) - return self + return ( + Object.replace( + Object.replace( + type(self)( + (replace_hy_obj(x, other) for x in self), + **{k: getattr(self, k) for k in self._extra_kwargs}), + self), + other) + if recursive + else Object.replace(self, other)) def __add__(self, other): return self.__class__( @@ -431,6 +438,8 @@ class FComponent(Sequence): format spec (if any). """ + _extra_kwargs = ("conversion",) + def __new__(cls, s=None, conversion=None): value = super().__new__(cls, s) value.conversion = conversion @@ -465,6 +474,8 @@ class FString(Sequence): :ivar brackets: As in :class:`hy.models.String`. """ + _extra_kwargs = ("brackets",) + def __new__(cls, s=None, brackets=None): value = super().__new__( cls,
hylang/hy
f6f00bfade9e1629de1bbfa601204c700b3ec3b7
diff --git a/tests/test_positions.py b/tests/test_positions.py new file mode 100644 index 00000000..c3fc8f39 --- /dev/null +++ b/tests/test_positions.py @@ -0,0 +1,27 @@ +'''Check that positioning attributes for AST nodes (which Python +ultimately uses for tracebacks) are set correctly.''' + +import ast +from hy import read_many +from hy.compiler import hy_compile + + +def cpl(string): + '''Compile the Hy `string` and get its final body element. A + newline is prepended so that line 1 is guaranteed to be the wrong + position for generated nodes.''' + return hy_compile(read_many('\n' + string), __name__).body[-1] + + +def test_do_mac(): + # https://github.com/hylang/hy/issues/2424 + x = cpl("(do-mac '9)") + assert isinstance(x, ast.Expr) + assert x.lineno == 2 + + +def test_defmacro_raise(): + # https://github.com/hylang/hy/issues/2424 + x = cpl("(defmacro m [] '(do (raise)))\n(m)") + assert isinstance(x, ast.Raise) + assert x.lineno == 3
More misplaced tracebacks There are cases not fixed by #2423 in which position information is still set incorrectly: ``` $ echo ';;;;;;\n(do-mac (quote (raise (ValueError))))' >ex.hy $ hy ex.hy Traceback (most recent call last): … File "/tmp/ex.hy", line 1, in <module> ;;;;;; ValueError ``` ``` $ echo ';;;;;\n(defmacro m [] (quote (do (raise (ValueError)))))\n(m)' >ex.hy $ hy ex.hy Traceback (most recent call last): … File "/tmp/ex.hy", line 1, in <module> ;;;;; ValueError ``` (Note that the `do` is necessary to reproduce the bug in the second case.) These don't look so easy to fix. I think #1951 may have been ill-advised: producing bogus default positions for models without positions leads to bugs that are harder to track down than crashes that occur immediately upon constructing the AST. But ultimately there may be no reasonable positions to assign to some dynamically generated models, in which case Python still needs something. I'm not sure. I've opened https://github.com/pytest-dev/pytest/pull/10840 to prevent pytest from crashing on this and any other cases. (Edit: This was merged, and indeed pytest no longer seems to have those crashes.)
0.0
f6f00bfade9e1629de1bbfa601204c700b3ec3b7
[ "tests/test_positions.py::test_do_mac", "tests/test_positions.py::test_defmacro_raise" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-03-06 19:57:35+00:00
mit
2,767
hynek__argon2-cffi-174
diff --git a/CHANGELOG.md b/CHANGELOG.md index e3fe7fb..46c0765 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,12 @@ What explicitly *may* change over time are the default hashing parameters and th ## [Unreleased](https://github.com/hynek/argon2-cffi/compare/23.1.0...HEAD) +### Changed + +- `argon2.PasswordHasher.check_needs_rehash()` now also accepts bytes like the rest of the API. + [#174](https://github.com/hynek/argon2-cffi/pull/174) + + ## [23.1.0](https://github.com/hynek/argon2-cffi/compare/21.3.0...23.1.0) - 2023-08-15 ### Removed diff --git a/src/argon2/_password_hasher.py b/src/argon2/_password_hasher.py index 125149b..ef940b3 100644 --- a/src/argon2/_password_hasher.py +++ b/src/argon2/_password_hasher.py @@ -244,7 +244,7 @@ class PasswordHasher: hash, _ensure_bytes(password, self.encoding), hash_type ) - def check_needs_rehash(self, hash: str) -> bool: + def check_needs_rehash(self, hash: str | bytes) -> bool: """ Check whether *hash* was created using the instance's parameters. @@ -264,5 +264,9 @@ class PasswordHasher: Whether *hash* was created using the instance's parameters. .. versionadded:: 18.2.0 + .. versionchanged:: 24.1.0 Accepts bytes for *hash*. """ + if isinstance(hash, bytes): + hash = hash.decode("ascii") + return self._parameters != extract_parameters(hash)
hynek/argon2-cffi
abd0cf90d665f0b709ecccefe4b6187d14d60ffa
diff --git a/tests/test_password_hasher.py b/tests/test_password_hasher.py index d6fa626..17f9410 100644 --- a/tests/test_password_hasher.py +++ b/tests/test_password_hasher.py @@ -109,22 +109,32 @@ class TestPasswordHasher: with pytest.raises(InvalidHash): PasswordHasher().verify("tiger", "does not matter") - def test_check_needs_rehash_no(self): + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_no(self, use_bytes): """ Return False if the hash has the correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16) - assert not ph.check_needs_rehash(ph.hash("foo")) + hash = ph.hash("foo") + if use_bytes: + hash = hash.encode() - def test_check_needs_rehash_yes(self): + assert not ph.check_needs_rehash(hash) + + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_yes(self, use_bytes): """ Return True if any of the parameters changes. """ ph = PasswordHasher(1, 8, 1, 16, 16) ph_old = PasswordHasher(1, 8, 1, 8, 8) - assert ph.check_needs_rehash(ph_old.hash("foo")) + hash = ph_old.hash("foo") + if use_bytes: + hash = hash.encode() + + assert ph.check_needs_rehash(hash) def test_type_is_configurable(self): """
Make PasswordHasher.check_needs_rehash() accept bytes hash `PasswordHasher.check_needs_rehash()` should also accept bytes hashes to be consistent with the rest of the API.
0.0
abd0cf90d665f0b709ecccefe4b6187d14d60ffa
[ "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_no[True]", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_yes[True]" ]
[ "tests/test_password_hasher.py::TestEnsureBytes::test_is_bytes", "tests/test_password_hasher.py::TestEnsureBytes::test_is_str", "tests/test_password_hasher.py::TestPasswordHasher::test_hash[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_custom_salt", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_agility[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_agility[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash_verify[p\\xe4ssword0]", "tests/test_password_hasher.py::TestPasswordHasher::test_hash_verify[p\\xe4ssword1]", "tests/test_password_hasher.py::TestPasswordHasher::test_check", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_invalid_hash_error", "tests/test_password_hasher.py::TestPasswordHasher::test_verify_invalid_hash", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_no[False]", "tests/test_password_hasher.py::TestPasswordHasher::test_check_needs_rehash_yes[False]", "tests/test_password_hasher.py::TestPasswordHasher::test_type_is_configurable" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-04-16 06:36:03+00:00
mit
2,768
hynek__doc2dash-200
diff --git a/CHANGELOG.md b/CHANGELOG.md index b92576f..aa5dda5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased](https://github.com/hynek/doc2dash/compare/3.0.0...HEAD) +### Added + +- Support for 2x icons using the `--icon-2x` option. + [#200](https://github.com/hynek/doc2dash/pull/200) + + ### Fixed -- The table of contents-generation for *pydoctor*-based documentation has been restored. [#133](https://github.com/hynek/doc2dash/pull/133) +- The table of contents-generation for *pydoctor*-based documentation has been restored. + [#133](https://github.com/hynek/doc2dash/pull/133) ## [3.0.0](https://github.com/hynek/doc2dash/compare/2.4.1...3.0.0) - 2022-09-13 diff --git a/docs/how-to.md b/docs/how-to.md index f8064ae..3d3f209 100644 --- a/docs/how-to.md +++ b/docs/how-to.md @@ -82,21 +82,25 @@ Confusingly, the file name of the index is `genindex.html` and the file name of Therefore, we'll add `--index-page index.html` to the command line. -### Add an Icon +### Add Icons Documentation sets can have icons that are shown throughout Dash next to the docsets's names and symbols. -That's pretty but also helpful to recognize docsets faster and if you're searching across multiple docsets, where a symbol is coming from. +That's pretty, but also helpful to recognize where a symbol is coming from when searching across multiple docsets -*structlog* has a cool beaver logo, so let's use [ImageMagick](https://imagemagick.org/) to resize the logo to 16x16 pixels: +*structlog* has a cool beaver logo, so let's use [ImageMagick](https://imagemagick.org/) to resize the logo to 16x16 and 32x32 pixels: ```console $ magick \ docs/_static/structlog_logo_transparent.png \ -resize 16x16 \ docs/_static/docset-icon.png +$ magick \ + docs/_static/structlog_logo_transparent.png \ + -resize 32x32 \ + docs/_static/[email protected] ``` -Now we can add it to the docset using the `--icon docset-icon.png` option. +Now we can add it to the docset using the `--icon` and `--icon-2x` options. ### Support Online Redirection @@ -125,6 +129,7 @@ Let's run the whole command line and see how it looks in Dash: $ doc2dash \ --index-page index.html \ --icon docs/_static/docset-icon.png \ + --icon-2x docs/_static/[email protected] \ --online-redirect-url https://www.structlog.org/en/latest/ \ docs/_build/html Converting intersphinx docs from '/Users/hynek/FOSS/structlog/docs/_build/html' to 'structlog.docset'. @@ -163,13 +168,11 @@ allowlist_externals = commands = rm -rf structlog.docset docs/_build sphinx-build -n -T -W -b html -d {envtmpdir}/doctrees docs docs/_build/html - doc2dash --index-page index.html --icon docs/_static/docset-icon.png --online-redirect-url https://www.structlog.org/en/latest/ docs/_build/html - cp docs/_static/[email protected] structlog.docset/[email protected] + doc2dash --index-page index.html --icon docs/_static/docset-icon.png --icon-2x docs/_static/[email protected] --online-redirect-url https://www.structlog.org/en/latest/ docs/_build/html tar --exclude='.DS_Store' -cvzf structlog.tgz structlog.docset ``` Now I can build a docset just by calling `tox run -e docset`. -[Until *doc2dash* supports hi-res icons](https://github.com/hynek/doc2dash/issues/130), it also copies a 32x32 pixels big version of the logo directly into the docset. Doing that in CI is trivial, but entails tons of boilerplate, so I'll just [link to the workflow](https://github.com/hynek/structlog/blob/main/.github/workflows/build-docset.yml). Note the `upload-artifact` action at the end that allows me to download the built docsets from the run summaries. diff --git a/src/doc2dash/__main__.py b/src/doc2dash/__main__.py index 4e0320b..39d0eb6 100644 --- a/src/doc2dash/__main__.py +++ b/src/doc2dash/__main__.py @@ -95,6 +95,11 @@ IMPORTABLE = ImportableType() type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Add PNG icon to docset.", ) [email protected]( + "--icon-2x", + type=click.Path(exists=True, dir_okay=False, path_type=Path), + help="Add a 2x-sized PNG icon for hires displays to docset.", +) @click.option( "--index-page", "-I", @@ -150,6 +155,7 @@ def main( add_to_dash: bool, add_to_global: bool, icon: Path | None, + icon_2x: Path | None, index_page: Path | None, enable_js: bool, online_redirect_url: str | None, @@ -210,7 +216,14 @@ def main( force=force, ) docset = docsets.prepare_docset( - source, dest, name, index_page, enable_js, online_redirect_url, icon + source, + dest, + name, + index_page, + enable_js, + online_redirect_url, + icon, + icon_2x, ) parser = parser_type(docset.docs) diff --git a/src/doc2dash/docsets.py b/src/doc2dash/docsets.py index 0a8d634..c10d24e 100644 --- a/src/doc2dash/docsets.py +++ b/src/doc2dash/docsets.py @@ -38,6 +38,7 @@ def prepare_docset( enable_js: bool, online_redirect_url: str | None, icon: Path | None, + icon_2x: Path | None, ) -> DocSet: """ Create boilerplate files & directories and copy vanilla docs inside. @@ -78,6 +79,9 @@ def prepare_docset( if icon: shutil.copy2(icon, dest / "icon.png") + if icon_2x: + shutil.copy2(icon_2x, dest / "[email protected]") + return DocSet(path=dest, plist=plist_path, db_conn=db_conn)
hynek/doc2dash
4daa9acb4fdcb585025cdac1d0add2f34bf65881
diff --git a/tests/test_docsets.py b/tests/test_docsets.py index 5e96162..edbcae1 100644 --- a/tests/test_docsets.py +++ b/tests/test_docsets.py @@ -29,6 +29,7 @@ class TestPrepareDocset: enable_js=False, online_redirect_url=None, icon=None, + icon_2x=None, ) m_ct.assert_called_once_with( @@ -72,6 +73,7 @@ class TestPrepareDocset: enable_js=False, online_redirect_url=None, icon=None, + icon_2x=None, ) p = docsets.read_plist(docset.plist) @@ -104,6 +106,7 @@ class TestPrepareDocset: enable_js=True, online_redirect_url=None, icon=None, + icon_2x=None, ) p = docsets.read_plist(docset.plist) @@ -136,6 +139,7 @@ class TestPrepareDocset: enable_js=False, online_redirect_url="https://domain.com", icon=None, + icon_2x=None, ) p = docsets.read_plist(docset.plist) @@ -167,6 +171,27 @@ class TestPrepareDocset: enable_js=False, online_redirect_url=None, icon=icon, + icon_2x=None, ) assert (Path(dest) / "icon.png").exists() + + def test_with_icon_2x(self, tmp_path, sphinx_built): + """ + If an icon is passed, it's copied to the root of the docset. + """ + icon = Path("tests") / "logo.png" + dest = tmp_path / "bar" + + docsets.prepare_docset( + sphinx_built, + dest, + name="foo", + index_page=None, + enable_js=False, + online_redirect_url=None, + icon=None, + icon_2x=icon, + ) + + assert (Path(dest) / "[email protected]").exists() diff --git a/tests/test_main.py b/tests/test_main.py index 5cac026..6897951 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -192,7 +192,14 @@ def test_normal_flow(monkeypatch, tmp_path, runner): """ def fake_prepare( - source, dest, name, index_page, enable_js, online_redirect_url, icon + source, + dest, + name, + index_page, + enable_js, + online_redirect_url, + icon, + icon_2x, ): os.mkdir(dest) db_conn = sqlite3.connect(":memory:")
Add support for 2x icons https://kapeli.com/docsets#addingicon
0.0
4daa9acb4fdcb585025cdac1d0add2f34bf65881
[ "tests/test_docsets.py::TestPrepareDocset::test_plist_creation", "tests/test_docsets.py::TestPrepareDocset::test_with_index_page", "tests/test_docsets.py::TestPrepareDocset::test_with_javascript_enabled", "tests/test_docsets.py::TestPrepareDocset::test_with_online_redirect_url", "tests/test_docsets.py::TestPrepareDocset::test_with_icon", "tests/test_docsets.py::TestPrepareDocset::test_with_icon_2x", "tests/test_main.py::test_normal_flow" ]
[ "tests/test_main.py::test_intersphinx", "tests/test_main.py::TestArguments::test_fails_with_unknown_icon", "tests/test_main.py::TestArguments::test_fails_with_missing_index_page", "tests/test_main.py::TestArguments::test_handles_unknown_doc_types", "tests/test_main.py::TestArguments::test_quiet_and_verbose_conflict", "tests/test_main.py::TestArguments::test_fails_if_supplied_parser_fails", "tests/test_main.py::TestSetupPaths::test_works", "tests/test_main.py::TestSetupPaths::test_add_to_global_overrides_destination", "tests/test_main.py::TestSetupPaths::test_detects_existing_dest" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-14 12:31:24+00:00
mit
2,769
hynek__doc2dash-201
diff --git a/CHANGELOG.md b/CHANGELOG.md index aa5dda5..12fe351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Support for 2x icons using the `--icon-2x` option. [#200](https://github.com/hynek/doc2dash/pull/200) +- Support for linking to [docset playgrounds](https://kapeli.com/docsets#docsetPlaygrounds) using the `--playground-url` option. + [#201](https://github.com/hynek/doc2dash/pull/201) + ### Fixed diff --git a/docs/usage.md b/docs/usage.md index 5bae7d0..c50e7fc 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -18,3 +18,5 @@ Basic usage is as simple as: :prog_name: doc2dash :style: table :depth: 1 + +Refer to our [how-to](how-to.md) and the official [*Docset Generation Guide*](https://kapeli.com/docsets) to learn what those options are good for. diff --git a/src/doc2dash/__main__.py b/src/doc2dash/__main__.py index 39d0eb6..e457c6a 100644 --- a/src/doc2dash/__main__.py +++ b/src/doc2dash/__main__.py @@ -136,6 +136,7 @@ IMPORTABLE = ImportableType() "-u", help="The base URL of the online documentation.", ) [email protected]("--playground-url", help="The URL to a docset playground.") @click.option( "--parser", "parser_type", @@ -160,6 +161,7 @@ def main( enable_js: bool, online_redirect_url: str | None, parser_type: type[Parser] | None, + playground_url: str | None, ) -> None: """ Convert docs from SOURCE to Dash's docset format. @@ -222,6 +224,7 @@ def main( index_page, enable_js, online_redirect_url, + playground_url, icon, icon_2x, ) diff --git a/src/doc2dash/docsets.py b/src/doc2dash/docsets.py index 1a4146e..5763dbc 100644 --- a/src/doc2dash/docsets.py +++ b/src/doc2dash/docsets.py @@ -37,6 +37,7 @@ def prepare_docset( index_page: Path | None, enable_js: bool, online_redirect_url: str | None, + playground_url: str | None, icon: Path | None, icon_2x: Path | None, ) -> DocSet: @@ -71,6 +72,8 @@ def prepare_docset( plist_cfg["dashIndexFilePath"] = str(index_page) if online_redirect_url is not None: plist_cfg["DashDocSetFallbackURL"] = online_redirect_url + if playground_url is not None: + plist_cfg["DashDocSetPlayURL"] = playground_url write_plist(plist_cfg, plist_path)
hynek/doc2dash
e8a4f374588dfb054cb1d984c9c5e72821588528
diff --git a/tests/test_docsets.py b/tests/test_docsets.py index edbcae1..572419e 100644 --- a/tests/test_docsets.py +++ b/tests/test_docsets.py @@ -28,6 +28,7 @@ class TestPrepareDocset: index_page=None, enable_js=False, online_redirect_url=None, + playground_url=None, icon=None, icon_2x=None, ) @@ -72,6 +73,7 @@ class TestPrepareDocset: index_page="foo.html", enable_js=False, online_redirect_url=None, + playground_url=None, icon=None, icon_2x=None, ) @@ -105,6 +107,7 @@ class TestPrepareDocset: index_page="foo.html", enable_js=True, online_redirect_url=None, + playground_url=None, icon=None, icon_2x=None, ) @@ -138,6 +141,7 @@ class TestPrepareDocset: index_page="foo.html", enable_js=False, online_redirect_url="https://domain.com", + playground_url=None, icon=None, icon_2x=None, ) @@ -156,6 +160,41 @@ class TestPrepareDocset: "DashDocSetFallbackURL": "https://domain.com", } + def test_with_playground_url(self, monkeypatch, tmp_path): + """ + If a playground URL is passed, it is added to the plist. + """ + monkeypatch.chdir(tmp_path) + m_ct = Mock() + monkeypatch.setattr(shutil, "copytree", m_ct) + (tmp_path / "bar").mkdir() + + docset = docsets.prepare_docset( + Path("some/path/foo"), + Path("bar"), + name="foo", + index_page="foo.html", + enable_js=False, + online_redirect_url=None, + playground_url="https://repl.it/F9J7/1", + icon=None, + icon_2x=None, + ) + + p = docsets.read_plist(docset.plist) + + assert p == { + "CFBundleIdentifier": "foo", + "CFBundleName": "foo", + "DocSetPlatformFamily": "foo", + "DashDocSetFamily": "python", + "DashDocSetDeclaredInStyle": "originalName", + "isDashDocset": True, + "dashIndexFilePath": "foo.html", + "isJavaScriptEnabled": False, + "DashDocSetPlayURL": "https://repl.it/F9J7/1", + } + def test_with_icon(self, tmp_path, sphinx_built): """ If an icon is passed, it's copied to the root of the docset. @@ -170,6 +209,7 @@ class TestPrepareDocset: index_page=None, enable_js=False, online_redirect_url=None, + playground_url=None, icon=icon, icon_2x=None, ) @@ -190,6 +230,7 @@ class TestPrepareDocset: index_page=None, enable_js=False, online_redirect_url=None, + playground_url=None, icon=None, icon_2x=icon, ) diff --git a/tests/test_main.py b/tests/test_main.py index 6897951..783f0e7 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -198,6 +198,7 @@ def test_normal_flow(monkeypatch, tmp_path, runner): index_page, enable_js, online_redirect_url, + playground_url, icon, icon_2x, ):
Add support for Docset Playgrounds https://kapeli.com/docsets#docsetPlaygrounds
0.0
e8a4f374588dfb054cb1d984c9c5e72821588528
[ "tests/test_docsets.py::TestPrepareDocset::test_plist_creation", "tests/test_docsets.py::TestPrepareDocset::test_with_index_page", "tests/test_docsets.py::TestPrepareDocset::test_with_javascript_enabled", "tests/test_docsets.py::TestPrepareDocset::test_with_online_redirect_url", "tests/test_docsets.py::TestPrepareDocset::test_with_playground_url", "tests/test_docsets.py::TestPrepareDocset::test_with_icon", "tests/test_docsets.py::TestPrepareDocset::test_with_icon_2x", "tests/test_main.py::test_normal_flow" ]
[ "tests/test_main.py::test_intersphinx", "tests/test_main.py::TestArguments::test_fails_with_unknown_icon", "tests/test_main.py::TestArguments::test_fails_with_missing_index_page", "tests/test_main.py::TestArguments::test_handles_unknown_doc_types", "tests/test_main.py::TestArguments::test_quiet_and_verbose_conflict", "tests/test_main.py::TestArguments::test_fails_if_supplied_parser_fails", "tests/test_main.py::TestSetupPaths::test_works", "tests/test_main.py::TestSetupPaths::test_add_to_global_overrides_destination", "tests/test_main.py::TestSetupPaths::test_detects_existing_dest" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-01-14 13:01:38+00:00
mit
2,770
hynek__pem-34
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 4735f42..779f442 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -26,7 +26,7 @@ Deprecations: Changes: ^^^^^^^^ -*none* +- You can now load encrypted PKCS#8 PEM key as ``pem.Key``. ---- diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index dcabac2..57802b5 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -18,6 +18,8 @@ Workflow Whether you prefer to rebase on master or merge master into your branch, do whatever is more comfortable for you. - *Always* add tests and docs for your code. This is a hard rule; patches with missing tests or documentation can't be merged. +- Consider updating CHANGELOG.rst to reflect the changes as observed by people + using this library. - Make sure your changes pass our CI_. You won't get any feedback until it's green unless you ask for it. - Once you've addressed review feedback, make sure to bump the pull request with a short note, so we know you're done. diff --git a/setup.cfg b/setup.cfg index b0a9418..8aac42a 100644 --- a/setup.cfg +++ b/setup.cfg @@ -24,4 +24,4 @@ multi_line_output=3 not_skip=__init__.py known_first_party=pem -known_third_party=OpenSSL,certifi,pem,pretend,pytest,setuptools,sphinx_rtd_theme,twisted +known_third_party=OpenSSL,certifi,pem,pretend,pytest,setuptools,sphinx_rtd_theme,twisted,typing diff --git a/src/pem/_core.py b/src/pem/_core.py index 0acdce6..b3998d3 100644 --- a/src/pem/_core.py +++ b/src/pem/_core.py @@ -141,6 +141,7 @@ class DHParameters(AbstractPEMObject): _PEM_TO_CLASS = { b"CERTIFICATE": Certificate, b"PRIVATE KEY": Key, + b"ENCRYPTED PRIVATE KEY": Key, b"RSA PRIVATE KEY": RSAPrivateKey, b"DH PARAMETERS": DHParameters, b"NEW CERTIFICATE REQUEST": CertificateRequest,
hynek/pem
9f3bc654d17503a18ace83329f4724a4c0271e10
diff --git a/tests/data.py b/tests/data.py index 81f9b0f..5c82cc2 100644 --- a/tests/data.py +++ b/tests/data.py @@ -54,6 +54,75 @@ kjBF/mzooA== -----END RSA PRIVATE KEY----- """ +# KEY_PEM_PKCS8_* and KEY_PEM_PKCS5_* contain the same private key, but in +# different formats. + +# PKCS#5 RSA unencrypted. +# Generated with: +# openssl genrsa -out private.pem 512 +KEY_PEM_PKCS5_UNENCRYPTED = b"""-----BEGIN RSA PRIVATE KEY----- +MIIBOwIBAAJBAKX6cRhPHvdyoftEHGiRje3tTLRDnddg01AvgsJJcCFoIjwdgfa9 +aKFdzCcgD/htjvfRZl24M7E89sMUBMNHk8ECAwEAAQJABcBi8OO1AAAh6tIWZe09 +TNRfRxPcwVzilbG/xznCP/YMf72E8hsZazu+HGMKITg9dFeJOyjXZ4e8sD/pL/I6 +0QIhANzULu4JjJxpoTK8NnF/CemF7neLROA18NDB/mao5ZZtAiEAwGnYobinxuHS +UQh8cT3w7aLsVlarZmCtoapxjW+ObiUCIQCcAltVV/G63vU/PrDH5hQ+opwiYIW8 +UN9c3HC6XkA00QIhAJ8YpfwKgAfNfyZrmuHTspv7Q+mb3jtXoxnyodOtsxpVAiBC +a4FDqkr+bDwV4SwaGdG/AC40fR3P8hhOADAhtFDwlw== +-----END RSA PRIVATE KEY----- +""" + +# PKCS#5 RSA encrypted with `test` as password. +# Generated with: +# openssl genrsa -des3 -out private.pem 512 +KEY_PEM_PKCS5_ENCRYPTED = b"""-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,8A72BD2DC1C9092F + +6LgvCNeXdcuTayEOKhQo2N4IveCP0S3t8xJCeihW9yizLeQFzSjqSfKtmRyImjfg +fMl8IMDFozR+xVE9uWaIo98wKWpjyu6cytYyjL/8SP3jswBoSP5P9OekUSLifPWM +ghUEu6tGissqSs/8i2wzLIdho3DdUnUMPZIprENmK6HrYmdRtJT3qMgkFTCtCS9Q +r9oPm7xKPsfKBhaUHK51JcsPkPjrny8Dl56W0IYf/dfvRPwSr5yFQFLk6Nbgnx0N +32aT3ZMRCEvOTxhX1cO3f5JqYLxFAGKBFwvsulTisJ6rGYOEDSMBDwZc3sqLvt5g +h0vKRPqSkylQ0W5shNg0bwbxySiRxJPBL8kWDAbJVfauArabLPuNkUNwmYhIjy7j +lY0oYw2xeJ9hTUly/Zg3+DI8oYYY3z7WaxPHXEoicCE= +-----END RSA PRIVATE KEY----- +""" + +# PKCS#8 RSA encrypted with `test` as password. +# Generated with pkc5 as intermediate file: +# openssl genrsa -des3 -out private.pem 512 +# openssl pkcs8 -topk8 -in private.pem +KEY_PEM_PKCS8_ENCRYPTED = b"""-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIBvTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIyqwWErm7rlcCAggA +MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBAkVu+KRbmcfWIGKzgnjjBMBIIB +YI3aRS0ebuzb1Tq26/HAq8pplPu+96dM1SnRNXwH0ijmP3fLBjEDH4hB/X9H8arT +xWSfKQ80+FKI07DsLQKmO+cuB12MAWPSoCNBRtLwGUiwYvlMcBp6XR4NQQ+YG/Nw +OgZ1InH2w7uSnDPdxV9dZculYWzJE82IohnFVZokO2nYSEfIqr1xVQZht6lfzpx2 +aRje42fpYfgkEm13w4oJKIlekzA9M4CeYku7Q4l9GDSHRmoeypMSHPI8RFV9pxub +ME3AMXGcRioJ0Ic/cpmwqFaJbTVRPsqFVEsMCz1T/CQ4oLjPTWg+zkxfsPIyGj7L +K3yLZmTA6IxSu+wuO/bsbqiM3x718AW6U0FHXd4zk+llu3mUfhTiMYPvN/cedv/M +wsT85CHM6reIBopGMqeZD965tNEcWPGMEvXXnG71dxxgrfHFv7l/o8+moVRNIQCh +EArlaXgT3MlI1jb9HoNvVNg= +-----END ENCRYPTED PRIVATE KEY----- +""" + +# RSA unencrypted +# Generated with pkc5 as intermediate file: +# openssl genrsa -des3 -out private.pem 512 +# openssl pkcs8 -topk8 -in private.pem -nocrypt +KEY_PEM_PKCS8_UNENCRYPTED = b"""-----BEGIN PRIVATE KEY----- +MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEApfpxGE8e93Kh+0Qc +aJGN7e1MtEOd12DTUC+CwklwIWgiPB2B9r1ooV3MJyAP+G2O99FmXbgzsTz2wxQE +w0eTwQIDAQABAkAFwGLw47UAACHq0hZl7T1M1F9HE9zBXOKVsb/HOcI/9gx/vYTy +GxlrO74cYwohOD10V4k7KNdnh7ywP+kv8jrRAiEA3NQu7gmMnGmhMrw2cX8J6YXu +d4tE4DXw0MH+Zqjllm0CIQDAadihuKfG4dJRCHxxPfDtouxWVqtmYK2hqnGNb45u +JQIhAJwCW1VX8bre9T8+sMfmFD6inCJghbxQ31zccLpeQDTRAiEAnxil/AqAB81/ +Jmua4dOym/tD6ZveO1ejGfKh062zGlUCIEJrgUOqSv5sPBXhLBoZ0b8ALjR9Hc/y +GE4AMCG0UPCX +-----END PRIVATE KEY----- +""" + + DH_PEM = b"""-----BEGIN DH PARAMETERS----- MIICCAKCAgEAj9/hwPNNKlQEANXqFBXViNy9nVpYlqIIHaLhoKdwAFzgYM+9hNSz FM/k+K5FS5dXrM63Zh9NgTI1M+ZRHJAxM2hhsG8AA333PN+c3exTRGwjQhU16XJg diff --git a/tests/test_core.py b/tests/test_core.py index 6e4349f..a9d5f17 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -6,6 +6,8 @@ from itertools import combinations import certifi +from OpenSSL import crypto + import pem from pem._compat import text_type @@ -16,7 +18,10 @@ from .data import ( CERT_PEMS_NO_NEW_LINE, CRL_PEMS, DH_PEM, - KEY_PEM, + KEY_PEM_PKCS5_ENCRYPTED, + KEY_PEM_PKCS5_UNENCRYPTED, + KEY_PEM_PKCS8_ENCRYPTED, + KEY_PEM_PKCS8_UNENCRYPTED, ) @@ -339,15 +344,76 @@ class TestPEMObjects(object): class TestParse(object): - def test_key(self): + """ + Tests for parsing input with one or multiple PEM objects. + """ + + def test_key_pkcs5_unencrypted(self): """ - Parses a PEM string with a key into an RSAPrivateKey. + It can load an unencrypted PKCS#5 RSA key as PEM string + as an RSAPrivateKey. """ - rv = pem.parse(KEY_PEM) + rv = pem.parse(KEY_PEM_PKCS5_UNENCRYPTED) key, = rv assert isinstance(key, pem.RSAPrivateKey) - assert KEY_PEM == key.as_bytes() + assert KEY_PEM_PKCS5_UNENCRYPTED == key.as_bytes() + + crypto_key = crypto.load_privatekey( + crypto.FILETYPE_PEM, key.as_bytes() + ) + assert crypto.TYPE_RSA, crypto_key.type() + assert 512, crypto_key.bits() + + def test_key_pkcs5_encrypted(self): + """ + It can load an encrypted PKCS#5 RSA key as PEM string + as an RSAPrivateKey. + """ + rv = pem.parse(KEY_PEM_PKCS5_ENCRYPTED) + key, = rv + + assert isinstance(key, pem.RSAPrivateKey) + assert KEY_PEM_PKCS5_ENCRYPTED == key.as_bytes() + + crypto_key = crypto.load_privatekey( + crypto.FILETYPE_PEM, key.as_bytes(), b"test" + ) + assert crypto.TYPE_RSA, crypto_key.type() + assert 512, crypto_key.bits() + + def test_key_pkcs8_unencrypted(self): + """ + It can load an unencrypted PKCS#8 RSA key as PEM string + as an RSAPrivateKey. + """ + rv = pem.parse(KEY_PEM_PKCS8_UNENCRYPTED) + key, = rv + + assert isinstance(key, pem.Key) + assert KEY_PEM_PKCS8_UNENCRYPTED == key.as_bytes() + + crypto_key = crypto.load_privatekey( + crypto.FILETYPE_PEM, key.as_bytes() + ) + assert crypto.TYPE_RSA, crypto_key.type() + assert 512, crypto_key.bits() + + def test_key_pkcs8_encrypted(self): + """ + It can load an encrypted PKCS#8 RSA key as PEM string + as an RSAPrivateKey. + """ + rv = pem.parse(KEY_PEM_PKCS8_ENCRYPTED) + key, = rv + + assert isinstance(key, pem.Key) + assert KEY_PEM_PKCS8_ENCRYPTED == key.as_bytes() + + crypto_key = crypto.load_privatekey( + crypto.FILETYPE_PEM, key.as_bytes(), b"test" + ) + assert crypto.TYPE_RSA, crypto_key def test_certificates(self): """ @@ -423,7 +489,7 @@ class TestParse(object): """ \n and \r\n are treated equal. """ - lf_pem = KEY_PEM.replace(b"\n", b"\r\n") + lf_pem = KEY_PEM_PKCS5_UNENCRYPTED.replace(b"\n", b"\r\n") rv, = pem.parse(lf_pem) assert rv.as_bytes() == lf_pem
Add support for PCKS#8 encrypted `BEGIN ENCRYPTED PRIVATE KEY` It looks like for now only `RSA PRIVATE KEY` is supported. OpenSSL docs https://www.openssl.org/docs/man1.0.2/apps/openssl-pkcs8.html A comparison https://github.com/kjur/jsrsasign/wiki/Tutorial-for-PKCS5-and-PKCS8-PEM-private-key-formats-differences -------- I will try to add a patch, but for now I have created this issue for reference
0.0
9f3bc654d17503a18ace83329f4724a4c0271e10
[ "tests/test_core.py::TestParse::test_key_pkcs8_encrypted" ]
[ "tests/test_core.py::TestPEMObjects::test_cert_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_cert_has_correct_str", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_sha1_hexdigest", "tests/test_core.py::TestPEMObjects::test_as_text", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_str", "tests/test_core.py::TestPEMObjects::test_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_rsa_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_rsa_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_str", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_str", "tests/test_core.py::TestPEMObjects::test_certificate_unicode", "tests/test_core.py::TestPEMObjects::test_certificate_request_unicode", "tests/test_core.py::TestPEMObjects::test_key_unicode", "tests/test_core.py::TestPEMObjects::test_rsa_key_unicode", "tests/test_core.py::TestPEMObjects::test_dhparams_unicode_deprecated", "tests/test_core.py::TestPEMObjects::test_crl_unicode", "tests/test_core.py::TestPEMObjects::test_certs_equal", "tests/test_core.py::TestPEMObjects::test_cert_reqs_equal", "tests/test_core.py::TestPEMObjects::test_keys_equal", "tests/test_core.py::TestPEMObjects::test_rsa_keys_equal", "tests/test_core.py::TestPEMObjects::test_dh_params_equal", "tests/test_core.py::TestPEMObjects::test_crl_equal", "tests/test_core.py::TestPEMObjects::test_cert_contents_unequal", "tests/test_core.py::TestPEMObjects::test_cert_req_contents_unequal", "tests/test_core.py::TestPEMObjects::test_crl_unequal", "tests/test_core.py::TestPEMObjects::test_different_objects_unequal", "tests/test_core.py::TestPEMObjects::test_incompatible_types", "tests/test_core.py::TestParse::test_key_pkcs5_unencrypted", "tests/test_core.py::TestParse::test_key_pkcs5_encrypted", "tests/test_core.py::TestParse::test_key_pkcs8_unencrypted", "tests/test_core.py::TestParse::test_certificates", "tests/test_core.py::TestParse::test_certificate_no_new_line", "tests/test_core.py::TestParse::test_certificates_no_new_line", "tests/test_core.py::TestParse::test_dh", "tests/test_core.py::TestParse::test_crl", "tests/test_core.py::TestParse::test_file", "tests/test_core.py::TestParse::test_loads_certifi", "tests/test_core.py::TestParse::test_allows_lf" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-18 11:14:53+00:00
mit
2,771
hynek__pem-46
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index dc0e516..d6e191c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -29,6 +29,14 @@ Changes: - Added support for DSA private keys (``BEGIN DSA PRIVATE``). This is also the OpenSSH legacy PEM format. `#49 <https://github.com/hynek/pem/issues/49>`_ +- Added support for ``pem.SSHPublicKey`` + (``---- BEGIN SSH2 PUBLIC KEY ----``). + as defined in `RFC4716 <https://tools.ietf.org/html/rfc4716>`_. + `#46 <https://github.com/hynek/pem/pull/46>`_ +- Added support for ``pem.SSHCOMPrivateKey`` + (``---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----``). + which is the SSH.com / Tectia private key format (plain or encrypted). + `#46 <https://github.com/hynek/pem/pull/46>`_ ---- diff --git a/docs/api.rst b/docs/api.rst index a5b5271..15bd5b0 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -35,6 +35,8 @@ The following objects can be returned by the parsing functions. .. autoclass:: ECPrivateKey(PrivateKey) .. autoclass:: DSAPrivateKey(PrivateKey) .. autoclass:: OpenSSHPrivateKey(PrivateKey) +.. autoclass:: SSHPublicKey(Key) +.. autoclass:: SSHCOMPrivateKey(PrivateKey) .. autoclass:: DHParameters(AbstractPEMObject) .. autoclass:: CertificateRequest(AbstractPEMObject) .. autoclass:: CertificateRevocationList(AbstractPEMObject) diff --git a/setup.py b/setup.py index 7ac45ec..978f42a 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,6 @@ from setuptools import find_packages, setup ############################################################################### - NAME = "pem" KEYWORDS = ["pyopenssl", "ssl", "tls", "pem", "cryptography", "twisted"] PROJECT_URLS = { diff --git a/src/pem/__init__.py b/src/pem/__init__.py index 4e91e5e..9e98a7e 100644 --- a/src/pem/__init__.py +++ b/src/pem/__init__.py @@ -14,6 +14,8 @@ from ._core import ( PublicKey, RSAPrivateKey, RSAPublicKey, + SSHCOMPrivateKey, + SSHPublicKey, parse, parse_file, ) @@ -50,5 +52,7 @@ __all__ = [ "RSAPublicKey", "parse", "parse_file", + "SSHCOMPrivateKey", + "SSHPublicKey", "twisted", ] diff --git a/src/pem/_core.py b/src/pem/_core.py index 7238c0d..ce57807 100644 --- a/src/pem/_core.py +++ b/src/pem/_core.py @@ -194,6 +194,25 @@ class OpenSSHPrivateKey(PrivateKey): """ +class SSHPublicKey(PublicKey): + """ + A public key in SSH + `RFC 4716 <https://tools.ietf.org/html/rfc4716>`_ format. + + The Secure Shell (SSH) Public Key File Format. + + .. versionadded:: 21.1.0 + """ + + +class SSHCOMPrivateKey(PrivateKey): + """ + A private key in SSH.COM / Tectia format. + + .. versionadded:: 21.1.0 + """ + + _PEM_TO_CLASS = { b"CERTIFICATE": Certificate, b"PRIVATE KEY": PrivateKey, @@ -207,15 +226,19 @@ _PEM_TO_CLASS = { b"DH PARAMETERS": DHParameters, b"NEW CERTIFICATE REQUEST": CertificateRequest, b"CERTIFICATE REQUEST": CertificateRequest, + b"SSH2 PUBLIC KEY": SSHPublicKey, + b"SSH2 ENCRYPTED PRIVATE KEY": SSHCOMPrivateKey, b"X509 CRL": CertificateRevocationList, } # type: Dict[bytes, Type[AbstractPEMObject]] +# See https://tools.ietf.org/html/rfc1421 +# and https://tools.ietf.org/html/rfc4716 for space instead of fifth dash. _PEM_RE = re.compile( - b"-----BEGIN (" + b"----[- ]BEGIN (" + b"|".join(_PEM_TO_CLASS.keys()) - + b""")-----\r? + + b""")[- ]----\r? .+?\r? ------END \\1-----\r?\n?""", +----[- ]END \\1[- ]----\r?\n?""", re.DOTALL, ) @@ -223,7 +246,7 @@ _PEM_RE = re.compile( def parse(pem_str): # type: (bytes) -> List[AbstractPEMObject] """ - Extract PEM objects from *pem_str*. + Extract PEM-like objects from *pem_str*. :param pem_str: String to parse. :type pem_str: bytes
hynek/pem
129e3059d5339cd49e51c8a2464b931a6f2ed6a7
diff --git a/tests/data.py b/tests/data.py index bdc1bb5..92498b7 100644 --- a/tests/data.py +++ b/tests/data.py @@ -264,3 +264,30 @@ Qrb0riZLOXc966m9uXkBJE+Eimh+Jed/qfbwNuTZbxVz9rmsnbGHj8kvJT4c3J27 NRrjPxY+c3X65vSaThscOQ0SHm5bRhX2YNRhgnZPznUnMXfE8yRLdgIUUS6kFIid HhSy7IHLTHWGoNdmwLo= -----END DSA PRIVATE KEY-----""" + +# Taken from https://tools.ietf.org/html/rfc4716#section-3.6. +KEY_PEM_RFC4716_PUBLIC = br"""---- BEGIN SSH2 PUBLIC KEY ---- +Subject: me +Comment: 1024-bit rsa, created by [email protected] Mon Jan 15 \ +08:31:24 2001 +AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt4 +596k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9wa++Oi7Qkr8prgHc4 +soW6NUlfDzpvZK2H5E7eQaSeP3SAwGmQKUFHCddNaP0L+hM7zhFNzjFvpaMgJw0= +---- END SSH2 PUBLIC KEY ---- +""" + +# SSH.COM / Tectia private (encrypted or plain) key. +# The non-encrypted key has the same armor. +# puttygen -t rsa -O private-sshcom +KEY_PEM_SSHCOM_PRIVATE = b"""\ +---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ---- +Comment: "rsa-key-20210120" +P2/56wAAAUwAAAA3aWYtbW9kbntzaWdue3JzYS1wa2NzMS1zaGExfSxlbmNyeXB0e3JzYS +1wa2NzMXYyLW9hZXB9fQAAAARub25lAAAA/QAAAPkAAAAGJQAAAf0VIAK0MvdpUXEG6obL +3F5n0UimJWvwhJIb5AGyd++EdYvimCOg9iM2E75dDj89Ap7S5l4IS40fZO/5UjzYQxitAA +ACAMNoGQLXcI4xVX/5Xt22aUBP4ADaJnDKR4H9D7LVZ4lBDUP8RBTmowCv9p3Hz7KvVw3R +TX8BNF72gEuSOvruUAUAAAD9Hs7Zn1KbFR29ujFEv+d50/7rjMU7Ox4tzDeTSE6PBhsAAA +EA3m/0JWkf61807iZ7AV8umYJMmNQ35HadG53n9nitpFEAAAEA4OQI1Rrh8e1EZ5qJBV8o +gGyxzt4OdoXzuOtxkbHUB3U= +---- END SSH2 ENCRYPTED PRIVATE KEY ---- +""" diff --git a/tests/test_core.py b/tests/test_core.py index 6dfa848..e76aef1 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -29,7 +29,9 @@ from .data import ( KEY_PEM_PKCS8_ENCRYPTED, KEY_PEM_PKCS8_UNENCRYPTED, KEY_PEM_PUBLIC, + KEY_PEM_RFC4716_PUBLIC, KEY_PEM_RSA_PUBLIC, + KEY_PEM_SSHCOM_PRIVATE, ) @@ -525,6 +527,7 @@ class TestParse(object): assert isinstance(key, pem.PublicKey) assert isinstance(key, pem.RSAPublicKey) + assert KEY_PEM_RSA_PUBLIC == key.as_bytes() def test_generic_public_key(self): """ @@ -533,6 +536,7 @@ class TestParse(object): key = pem.parse(KEY_PEM_PUBLIC)[0] assert isinstance(key, pem.PublicKey) + assert KEY_PEM_PUBLIC == key.as_bytes() def test_ec_private_key(self): """ @@ -541,6 +545,7 @@ class TestParse(object): key = pem.parse(KEY_PEM_EC_PRIVATE)[0] assert isinstance(key, pem.ECPrivateKey) + assert KEY_PEM_EC_PRIVATE == key.as_bytes() def test_openshh_private_key(self): """ @@ -549,6 +554,7 @@ class TestParse(object): (key,) = pem.parse(KEY_PEM_OPENSSH) assert isinstance(key, pem.OpenSSHPrivateKey) + assert KEY_PEM_OPENSSH == key.as_bytes() def test_dsa_private_key(self): """ @@ -558,3 +564,26 @@ class TestParse(object): (key,) = pem.parse(KEY_PEM_DSA_PRIVATE) assert isinstance(key, pem.DSAPrivateKey) + assert KEY_PEM_DSA_PRIVATE == key.as_bytes() + + def test_rfc4716_public_key_(self): + """ + Detects and loads public SSH keys in RFC4716 format. + """ + (key,) = pem.parse( + b"PREAMBLE \n" + KEY_PEM_RFC4716_PUBLIC + b"\n TRAILING" + ) + + assert isinstance(key, pem.SSHPublicKey) + assert KEY_PEM_RFC4716_PUBLIC == key.as_bytes() + + def test_sshcom_private(self): + """ + Detects and loads public SSH keys in RFC4716 format. + """ + (key,) = pem.parse( + b"PREAMBLE \n" + KEY_PEM_SSHCOM_PRIVATE + b"\n TRAILING" + ) + + assert isinstance(key, pem.SSHCOMPrivateKey) + assert KEY_PEM_SSHCOM_PRIVATE == key.as_bytes()
Add support for RFC 4716 public and private keys https://tools.ietf.org/html/rfc4716 Not sure if this is the right place to have this kind of support.... but since I saw support for OpenSSH. Feel free to close this. This is the SSH.com (Tectia) marker ``` —- BEGIN SSH2 PUBLIC KEY —- Comment: "rsa-key-20160402" AAAAB3NzaC1yc2EAAAABJQAAAgEAiL0jjDdFqK/kYThqKt7THrjABTPWvXmB3URI pGKCP/jZlSuCUP3Oc+IxuFeXSIMvVIYeW2PZAjXQGTn60XzPHr+M0NoGcPAvzZf2 u57aX3YKaL93cZSBHR97H+XhcYdrm7ATwfjMDgfgj7+VTvW4nI46Z+qjxmYifc8u VELolg1TDHWY789ggcdvy92oGjB0VUgMEywrOP+LS0DgG4dmkoUBWGP9dvYcPZDU F4q0XY9ZHhvyPWEZ3o2vETTrEJr9QHYwgjmFfJn2VFNnD/4qeDDHOmSlDgEOfQcZ Im+XUOn9eVsv//dAPSY/yMJXf8d0ZSm+VS29QShMjA4R+7yh5WhsIhouBRno2PpE VVb37Xwe3V6U3o9UnQ3ADtL75DbrZ5beNWcmKzlJ7jVX5QzHSBAnePbBx/fyeP/f 144xPtJWB3jW/kXjtPyWjpzGndaPQ0WgXkbf8fvIuB3NJTTcZ7PeIKnLaMIzT5XN CR+xobvdC8J9d6k84/q/laJKF3G8KbRGPNwnoVg1cwWFez+dzqo2ypcTtv/20yAm z86EvuohZoWrtoWvkZLCoyxdqO93ymEjgHAn2bsIWyOODtXovxAJqPgk3dxM1f9P AEQwc1bG+Z/Gc1Fd8DncgxyhKSQzLsfWroTnIn8wsnmhPJtaZWNuT5BJa8GhnzX0 9g6nhbk= ---- END SSH2 PUBLIC KEY ---- ``` The marker for private keys is `---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ---`
0.0
129e3059d5339cd49e51c8a2464b931a6f2ed6a7
[ "tests/test_core.py::TestParse::test_rfc4716_public_key_", "tests/test_core.py::TestParse::test_sshcom_private" ]
[ "tests/test_core.py::TestPEMObjects::test_cert_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_cert_has_correct_str", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_sha1_hexdigest[test]", "tests/test_core.py::TestPEMObjects::test_sha1_hexdigest[test\\r]", "tests/test_core.py::TestPEMObjects::test_as_text", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_str", "tests/test_core.py::TestPEMObjects::test_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_rsa_private_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_rsa_public_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_rsa_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_str", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_str", "tests/test_core.py::TestPEMObjects::test_certificate_unicode", "tests/test_core.py::TestPEMObjects::test_certificate_request_unicode", "tests/test_core.py::TestPEMObjects::test_key_unicode", "tests/test_core.py::TestPEMObjects::test_rsa_key_unicode", "tests/test_core.py::TestPEMObjects::test_dhparams_unicode_deprecated", "tests/test_core.py::TestPEMObjects::test_crl_unicode", "tests/test_core.py::TestPEMObjects::test_certs_equal", "tests/test_core.py::TestPEMObjects::test_cert_reqs_equal", "tests/test_core.py::TestPEMObjects::test_keys_equal", "tests/test_core.py::TestPEMObjects::test_rsa_keys_equal", "tests/test_core.py::TestPEMObjects::test_dh_params_equal", "tests/test_core.py::TestPEMObjects::test_crl_equal", "tests/test_core.py::TestPEMObjects::test_cert_contents_unequal", "tests/test_core.py::TestPEMObjects::test_cert_req_contents_unequal", "tests/test_core.py::TestPEMObjects::test_crl_unequal", "tests/test_core.py::TestPEMObjects::test_different_objects_unequal", "tests/test_core.py::TestPEMObjects::test_incompatible_types", "tests/test_core.py::TestParse::test_key_pkcs5_unencrypted", "tests/test_core.py::TestParse::test_key_pkcs5_encrypted", "tests/test_core.py::TestParse::test_key_pkcs8_unencrypted", "tests/test_core.py::TestParse::test_key_pkcs8_encrypted", "tests/test_core.py::TestParse::test_certificates", "tests/test_core.py::TestParse::test_certificate_no_new_line", "tests/test_core.py::TestParse::test_certificates_no_new_line", "tests/test_core.py::TestParse::test_dh", "tests/test_core.py::TestParse::test_crl", "tests/test_core.py::TestParse::test_file", "tests/test_core.py::TestParse::test_loads_certifi", "tests/test_core.py::TestParse::test_allows_lf", "tests/test_core.py::TestParse::test_rsa_public_key", "tests/test_core.py::TestParse::test_generic_public_key", "tests/test_core.py::TestParse::test_ec_private_key", "tests/test_core.py::TestParse::test_openshh_private_key", "tests/test_core.py::TestParse::test_dsa_private_key" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-04-12 18:14:45+00:00
mit
2,772
hynek__pem-72
diff --git a/CHANGELOG.md b/CHANGELOG.md index ffa157c..b1bb543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,17 +12,17 @@ You can find out backwards-compatibility policy [here](https://github.com/hynek/ ## [UNRELEASED](https://github.com/hynek/pem/compare/21.2.0...HEAD) -### Backwards-incompatible changes: +### Removed - Support for Python 2.7, 3.5, and 3.6 has been dropped. -### Deprecations: -*none* +### Added -### Changes: +- Support for RFC 4880 OpenPGP private & public keys: `pem.OpenPGPPublicKey` and `pem.OpenPGPPrivateKey`. + [#72](https://github.com/hynek/pem/issues/72) +- `pem.parse_file()` now accepts also [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) objects. -- `pem.parse_file()` now accepts [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) objects. ## [21.2.0](https://github.com/hynek/pem/compare/21.1.0...21.2.0) - 2021-04-07 diff --git a/docs/api.rst b/docs/api.rst index 2081e34..980d4ef 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -38,6 +38,8 @@ The following objects can be returned by the parsing functions. .. autoclass:: OpenSSHPrivateKey(PrivateKey) .. autoclass:: SSHPublicKey(Key) .. autoclass:: SSHCOMPrivateKey(PrivateKey) +.. autoclass:: OpenPGPPublicKey(PublicKey) +.. autoclass:: OpenPGPPrivateKey(PrivateKey) .. autoclass:: DHParameters(AbstractPEMObject) .. autoclass:: CertificateRequest(AbstractPEMObject) .. autoclass:: CertificateRevocationList(AbstractPEMObject) diff --git a/src/pem/__init__.py b/src/pem/__init__.py index d297906..c9849c9 100644 --- a/src/pem/__init__.py +++ b/src/pem/__init__.py @@ -7,6 +7,8 @@ from ._core import ( DSAPrivateKey, ECPrivateKey, Key, + OpenPGPPrivateKey, + OpenPGPPublicKey, OpenSSHPrivateKey, OpenSSLTrustedCertificate, PrivateKey, @@ -44,14 +46,16 @@ __all__ = [ "DSAPrivateKey", "ECPrivateKey", "Key", + "OpenPGPPrivateKey", + "OpenPGPPublicKey", "OpenSSHPrivateKey", "OpenSSLTrustedCertificate", + "parse_file", + "parse", "PrivateKey", "PublicKey", "RSAPrivateKey", "RSAPublicKey", - "parse", - "parse_file", "SSHCOMPrivateKey", "SSHPublicKey", "twisted", diff --git a/src/pem/_core.py b/src/pem/_core.py index c6eeffa..9cbdd41 100644 --- a/src/pem/_core.py +++ b/src/pem/_core.py @@ -189,8 +189,7 @@ class OpenSSHPrivateKey(PrivateKey): class SSHPublicKey(PublicKey): """ - A public key in SSH - `RFC 4716 <https://tools.ietf.org/html/rfc4716>`_ format. + A public key in SSH :rfc:`4716` format. The Secure Shell (SSH) Public Key File Format. @@ -206,6 +205,22 @@ class SSHCOMPrivateKey(PrivateKey): """ +class OpenPGPPublicKey(PublicKey): + """ + An :rfc:`4880` armored OpenPGP public key. + + .. versionadded:: 23.1.0 + """ + + +class OpenPGPPrivateKey(PrivateKey): + """ + An :rfc:`4880` armored OpenPGP private key. + + .. versionadded:: 23.1.0 + """ + + _PEM_TO_CLASS: dict[bytes, type[AbstractPEMObject]] = { b"CERTIFICATE": Certificate, b"TRUSTED CERTIFICATE": OpenSSLTrustedCertificate, @@ -223,6 +238,8 @@ _PEM_TO_CLASS: dict[bytes, type[AbstractPEMObject]] = { b"SSH2 PUBLIC KEY": SSHPublicKey, b"SSH2 ENCRYPTED PRIVATE KEY": SSHCOMPrivateKey, b"X509 CRL": CertificateRevocationList, + b"PGP PUBLIC KEY BLOCK": OpenPGPPublicKey, + b"PGP PRIVATE KEY BLOCK": OpenPGPPrivateKey, } # See https://tools.ietf.org/html/rfc1421
hynek/pem
3bf2bcd051ac86e41f20b051d21b2f382b59bc9e
diff --git a/tests/data.py b/tests/data.py index e9a682e..8348840 100644 --- a/tests/data.py +++ b/tests/data.py @@ -308,3 +308,108 @@ EA3m/0JWkf61807iZ7AV8umYJMmNQ35HadG53n9nitpFEAAAEA4OQI1Rrh8e1EZ5qJBV8o gGyxzt4OdoXzuOtxkbHUB3U= ---- END SSH2 ENCRYPTED PRIVATE KEY ---- """ + +# https://www.intel.com/content/www/us/en/security-center/pgp-public-key.html +KEY_PEM_OPENPGP_PUBLIC = b"""\ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: Encryption Desktop 10.4.2 (Build 289) + +mQINBGLoNzcBEACXineYjpC9Am/qiSe1DOiCkf1hWeiGsoqMFToy3/qKmjccLUkc +90Ap5BCkrdl2zEWsYUfegZ6F+XQmlKK5nttVbP9Ezoz+Mn2SwPZgw7u/ZYpGPWv2 +fYJbO/yjYTfNjgfCdWnRsYAmE6bcu7mT6MoKQ/dM//plyFEwVlzjlnceVzwekeAl +SpntCnB5nEcKnG/2c9FfD8Z0vgGcHTYkP/HffSPTcpDOADlFSnjENL1v3wi2xDo/ +SRyfsTLrndkytNDyRTpVEfCduzOcAsK4/DIygucqj2Lx4kSQGpYO2lD/MV6LWH+H +NVsiOeiCREdczu6JAdnCadYqtslPL7pJ0Hg2Ji+Wo7jq8Km2p7gmFnCXHVY90nfU +z4j3nwP5Z0j3jocYd5sbks29eI0a/i+sq+JwFbfQed4PaB/onpSignyQuofEMdaF +HJeN/ld+MdeE1+xh7arzgCYY2ZVvkoEgJgE6K6N0/+teHSLKZFzTntLoeEFd0Ffa +0oiBUYNdo5di7T8XN8Q5mDa45vFBXe941Q19AaVDEsxFv7g71sZ4YEC511oT0lcQ +D/VVKtYg7kYFFmxlw9TvpKRYc0+j1sGGwxdm8s5eXGtY/eEDIfk8QI5aYnthjFbb +ZL2edcMCBHYElsR92MTb+s2c4/BKUs/q/IOoe3IkYlNUqI1H9cYoHuaLDwARAQAB +tEBJbnRlbCBQcm9kdWN0IFNlY3VyaXR5IEluY2lkZW50IFJlc3BvbnNlIFRlYW0g +PHNlY3VyZUBpbnRlbC5jb20+iQJ4BBABAgBiBQJi6Dc3BQkB3pCAMBSAAAAAACAA +B3ByZWZlcnJlZC1lbWFpbC1lbmNvZGluZ0BwZ3AuY29tcGdwbWltZQgLCQgHAwIB +CgIZAQUbAwAAAAUWAAMCAQUeAQAAAAYVCAkKAwIACgkQwOey70F1YHgnQQ/+L7n2 +7cCqUtLMqwH6W1wrQxqRIhqflmSifX8qRiYwBi/EcN1Vf958W9zcqEvX6qMyX16m +SGCKC8KjpPw22XiTKuFocSEzs9pzNRc8p6AGHdISKIMUlpr5JzruvMnraSTlJZ9h +IAuXu+6/U7Y1YG2i9VAg0dSvlpa6YLQWfZ8vB7YS0txSESx4krzF683oWW+BC5jD +01pQgmjuX1fb9KAOoIQ2GLUBZ9gAorz3Dvvas30/JG7mNYI5K6cwOILO3UVu0Hx9 +LsF/ut4iFkHNf6uQpcdmaOdcM7HME1K8khddGaop7NozXW7/LKMTwSGOCIRbqBCE +FiPF0NeE+a3tc6W1+ciOU2KFQJIIqplAN5B+kuUSYDH1JobivArtOIrV1tmfhF9H +Bbm30hw5XF0fLtCokpaUZtvGIjVcT9epaSGaEYdzkQJRI8jHsNQlms8E1G8QDDnl +29775JV+EMqQrOn9DdfgLeuRpMNeMpu6XvA6gZVr4OBO5m03ckjfx9uC11e84cNy +oN+5bacZRTQAUw7pOs8mUEYgtzDEomUnKpah/EY8H2QzheogZYwrj+hxGG9+JBm+ +L2KRzZ7N6DevcMoGwYFPUOAslzvPlLAr0atm3yNNu2HR9vFXQNkQXDJhusfLMDWQ +q5L5rjiWVDY7CFT4Sl+ULVtO6+Dwt6QERV0rt1C0QUludGVsIFByb2R1Y3QgU2Vj +dXJpdHkgQW5ub3VuY2VtZW50IDxzZWN1cml0eS1hbm5vdW5jZUBpbnRlbC5jb20+ +iQJ1BBABAgBfBQJi6DecBQkB3pCAMBSAAAAAACAAB3ByZWZlcnJlZC1lbWFpbC1l +bmNvZGluZ0BwZ3AuY29tcGdwbWltZQgLCQgHAwIBCgUbAwAAAAUWAAMCAQUeAQAA +AAYVCAkKAwIACgkQwOey70F1YHitKQ/8CbtlRKAV0d/2tMK1h1xzH6NAYF//9XsM +jW45Il05c5cIwRSybgl6YQAV+WFG24ucEwxnLpyaYPQDNHGtyM4DNZW1BA+1DE5D +A6WF8juVAw+406Uz1jmS+bg2m+lL57AMGPB1TSNR7QY/dv3McUYxSxltF61SqYvB +M/TcV5v1EirHVAjhHoAJDRCXJW19zn0lxM3ef0w2IXVbSL+1wr0mHouc4aCMHypt +NJF1Lm6qtVCWi5pQU83cqqCSwa41axMONVUKE6CI0a5DuvSHA0fOmARWBu/Wdd5A +MoE3SpiCB9LK5iaZI9rm1bL6bbj+CSnPIwEG5wS8iZNUIDqjA7l8IP34psyHWyc/ +OwbHzIkZ0Bbqiyw0+g/LB6sxOjY78PqPoHYr59DTrNflMqMgmMFSt8Ug5AbkirYn +sqnIGJzoNeWfRtN2VAa3KYxdofpnunY8BklONRwMgfgjkWtdQju6x/HJSIqQoX/4 +0F9E6fAQt4FrSGNQgNeR7X6rbCXs2z+bBS1gTOV4tlSsKDbycZjAjufSyrmCWD8J +r40Gq8FLY1r85kiwwksW2iZlhble9MlvKXIyvkuGxBrokhMLGGrSbsjPcL8t53TW +NtMo49Vd0o1AM8bLjcLzL0LqN8FKEmM9LnPaysu0XBt04g4piKxw7cgPVugUMP6g +xSQ5vvdcmpq5Ag0EYug3OAEQANP1PkBrX2wi4zrAaZ+1gdZjLwLQ08h+bCGgqxSr +aSShdl7al1sKl8enJwkHzr3Ry7nkJoVkAC0bR9BjnQZuvaZQTWA8QM/sCl/CQT6x +l7oBh3sXax3G+lLlT1XAh65dQYOOj0qYeTYqCcseNeykqv9vtHtxAdb/Cfwua9Hu +6mVWLYxW8pAP6kmG7WUCq6J6jaRby/JFXbkLoKBhRKSrJ6Vud3gq5gpEif3G81db +ApDCaPe/oguf2Sr24QFV4c+Q9JMoE6RN4DjFm5/bYcY3LJDRUsriIAOvL12cDNs6 +Tqw5/Dy7ZYtYXN6tTF3QNfpXFUEGMMb25viOsDELV7bzm4m2fFp8tC3b0TbTDGuz +lRlZanbFT7UB7SsGZWzM9limdeuPKZ5Wh25cAfKjCP4BEUM+nga3KU3LKLGd1PXN +S56KrzTQnzVvr92mdTWBy5qb7L+iX6/g67nWLrICvnLwV/9wY37EH1dQ+9Y44PcD +50X7b0CHR3Ug0HNNapnPswZOWgyEJOtPGpBU1v1W/3+uyXE8GJpmroaUTs+ECmPM +DVEszYMALf40r/ZBm1YQ+ruiHetz511Dj0wNUAnBhLfZvU/DKp38eSzkzVNetRQt +I5FauRdAlZV4T3VDeRIz+0Xg2cD9mv/gBeyiI/ybotIcfWDos0GwBvYNMnCcYB78 +GNWjABEBAAGJBEcEGAECAjEFAmLoNzkFCQHekIAFGwwAAADBXSAEGQEIAAYFAmLo +NzgACgkQdYwkt+4BKuOIwhAAn/qmTDQTE6nEEYp/u/WTpbSvKyX1G0yrLGZ15mZO +nr2tCaXlFqTMF9nc2ygXFtjyEXrfYsEaA3f6JjXCBnJttxVbiHHKAROGAn4Sod6n +ISptqmeWsMEL1NAxzN9NJJrdh/lFGUCIvr/xmOb2PBaFU0gHAMAnsS70WRfm5ud2 +13nv9FEOSDF3IcqFbiHNyk26aTCO4jKErVJkdAYuq5Je3jXi5cU/yso6v+TzCn8Z +YyDP13qBXvNoJEnmItLSc/LGIaSwXhGtI/hTWEV0LgeTRlYVzfG3i5xkS15GWaAP +QE9iVQHSI9uZF/g1sKBUU5bJRZ7I41xFpfeqNB63DlsBst0QX0sR7jgIqI/Vy0SB +yctmdQ6SmG8l8I6PgwmKCV/PqHICA3ZQj04MxIoh65l0bOI5bW3YvAWheMVBf5NB +DrmxBGZd/ineeTCH981m3QbmM+9Z17NksBZMOspXsBxXlvpGioQ9Z2PPTm14PXZN +52KEEJTPKaaUbiyo7SwMyeyAg1JoNGIAn8SmIOnm4i2vLEq5dDNas+L3MG5TbDAh +209BXbYTt4QOD5Fb1UDHYZFUnnDMxv78huVcQrOsHkXSGgosuK91ebTb4M8lw9Te +kyGVJ/vwG/wx4rZSV56TrzynAep+9d2BjwXhSLilmf2kwFYac/IM6Tj6KRmQOXxX +jlUACgkQwOey70F1YHiaMg/8CkX+f/Y0SzD/Tvbj06rM5W9JLIX175PItcoSJqlq +XZ94tCs8rcporX1nmj6moxob9MyYqxQuQ1y6sBnerLw7KmxIe+6D+jsRV+lvl7Qq +DNvoeynMIipVUIzdFlxo1e9fQjgu01wV80U20HjpMc6WTU3QtixHd0fQv1PinbvY +d802JlEYlNOdJRDvu1zt25PM8+4aGbJbd5d4E0qyZcs+V8tKwbtmGchXOaPhMeq7 +XpYjwYhlI54vU+HM8mcZTSqmezUUGqk0ySwgHB06I5QuJ6QktALZYbWofAnUpFW7 +ZDMBIibCJb8uYzLubWZE/1BPlZxg7jgy5IEKfh9RxYdSkg6tnf5Hae1Eg6V7H8EC +Uaa4E6FUEVDQrg2oujEp0aY3LRX9VaCT62Hw+IBFSF02w28qyl/pohWWf/oGsB/J +tesUKGwv0Mpi0ZqQXGSVDqXLF7UUSbHoQOotGFcZ+J9qLnDnGYO6DAPge7xR9ZKJ +3vFqyaIoi+CdU8UBSTx6GGveuUAM44G8oqQclv6UszVznL9z6CWFY2lgG8VbaS9e +S+KBZ/Z/HZwO/j9+6fdA0di5KVd1EXtBjmmFtnYFzfm0pVF53sMfR2hIu1Jauvbc +8+OnsR0t7fjotTjCAjiBcHIMCpFJjv+AsnXZEib9z206L4I6rieXTQoaazEgJcNm +kss= +=hCPU +-----END PGP PUBLIC KEY BLOCK----- +""" + +# From https://www.ietf.org/archive/id/draft-bre-openpgp-samples-01.html +KEY_PEM_OPENPGP_PRIVATE = b"""\ +-----BEGIN PGP PRIVATE KEY BLOCK----- +Comment: Alice's OpenPGP Transferable Secret Key +Comment: https://www.ietf.org/id/draft-bre-openpgp-samples-01.html + +lFgEXEcE6RYJKwYBBAHaRw8BAQdArjWwk3FAqyiFbFBKT4TzXcVBqPTB3gmzlC/U +b7O1u10AAP9XBeW6lzGOLx7zHH9AsUDUTb2pggYGMzd0P3ulJ2AfvQ4RtCZBbGlj +ZSBMb3ZlbGFjZSA8YWxpY2VAb3BlbnBncC5leGFtcGxlPoiQBBMWCAA4AhsDBQsJ +CAcCBhUKCQgLAgQWAgMBAh4BAheAFiEE64W7X6M6deFelE5j8jFVDE9H444FAl2l +nzoACgkQ8jFVDE9H447pKwD6A5xwUqIDprBzrHfahrImaYEZzncqb25vkLV2arYf +a78A/R3AwtLQvjxwLDuzk4dUtUwvUYibL2sAHwj2kGaHnfICnF0EXEcE6RIKKwYB +BAGXVQEFAQEHQEL/BiGtq0k84Km1wqQw2DIikVYrQrMttN8d7BPfnr4iAwEIBwAA +/3/xFPG6U17rhTuq+07gmEvaFYKfxRB6sgAYiW6TMTpQEK6IeAQYFggAIBYhBOuF +u1+jOnXhXpROY/IxVQxPR+OOBQJcRwTpAhsMAAoJEPIxVQxPR+OOWdABAMUdSzpM +hzGs1O0RkWNQWbUzQ8nUOeD9wNbjE3zR+yfRAQDbYqvtWQKN4AQLTxVJN5X5AWyb +Pnn+We1aTBhaGa86AQ== +=n8OM +-----END PGP PRIVATE KEY BLOCK----- +""" diff --git a/tests/test_core.py b/tests/test_core.py index e9f8293..55320de 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -18,6 +18,8 @@ from .data import ( DH_PEM, KEY_PEM_DSA_PRIVATE, KEY_PEM_EC_PRIVATE, + KEY_PEM_OPENPGP_PRIVATE, + KEY_PEM_OPENPGP_PUBLIC, KEY_PEM_OPENSSH, KEY_PEM_PKCS5_ENCRYPTED, KEY_PEM_PKCS5_UNENCRYPTED, @@ -591,3 +593,21 @@ class TestParse: assert isinstance(key, pem.SSHCOMPrivateKey) assert KEY_PEM_SSHCOM_PRIVATE == key.as_bytes() + + def test_openpgp_public_key(self): + """ + Detects and loads OpenPGP public keys. + """ + (key,) = pem.parse(KEY_PEM_OPENPGP_PUBLIC) + + assert isinstance(key, pem.OpenPGPPublicKey) + assert KEY_PEM_OPENPGP_PUBLIC == key.as_bytes() + + def test_openpgp_private_key(self): + """ + Detects and loads OpenPGP private keys. + """ + (key,) = pem.parse(KEY_PEM_OPENPGP_PRIVATE) + + assert isinstance(key, pem.OpenPGPPrivateKey) + assert KEY_PEM_OPENPGP_PRIVATE == key.as_bytes()
Add support for OpenPGP - RFC 4880 I think that it would be nice if PEM could also support the armored OpenPGP files from https://tools.ietf.org/html/rfc4880 As a start without the support for headers. Below are the message types for reference, ``` BEGIN PGP MESSAGE Used for signed, encrypted, or compressed files. BEGIN PGP PUBLIC KEY BLOCK Used for armoring public keys. BEGIN PGP PRIVATE KEY BLOCK Used for armoring private keys. BEGIN PGP MESSAGE, PART X/Y Used for multi-part messages, where the armor is split amongst Y parts, and this is the Xth part out of Y. BEGIN PGP MESSAGE, PART X Used for multi-part messages, where this is the Xth part of an unspecified number of parts. Requires the MESSAGE-ID Armor Header to be used. BEGIN PGP SIGNATURE Used for detached signatures, OpenPGP/MIME signatures, and cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE for detached signatures. ``` And this is how a PGP public key can look like ``` -----BEGIN PGP PUBLIC KEY BLOCK----- mQGiBF6PHJoRBAD5netlVGrX5TKVQ9eoWKD67cwROI0LQHMJAAMxnrhcPogeNcIX mo8WY+heFg8onJ5aV+bAhzpMRmC2DcVR3Yvoq64eAx8hSUI6eW5lsc+CseakV8Jc BOJLI+4FVhJf1qgFmTHyBvKhL8IXy80E3bBApVcNTbCHCpBcsys/ga4stwCg3BUl IFWMdNTkffrNlupUwfqmp8UD/j7ZkusPO0RjAO0gD3FBZMqeR1IfrYlsdW3oTglr NdjNuPYe1mvT3EiBAoEEthaPE3XR3kY1HQBzoFyCK7DyBUI7AmVFMzybTxm89ufQ rAr/kWSMY20fYjQZxX4705NvuLa3cGdKnmLP+cPmTHl5jV4+9d3NC58+38lpcfl7 UHk+A/wIvjiVzZgpRGF+BQccpo7JcCzJcXgxACx1lqRKNGDrSnJHUDWDXogy70xE /kwUPuLTb78mAZsJPsB+d3aL1/SoKeTcveDc+EFfGPbrA+gzLhXj1GVmK4YbCcBz TCTmVkm1OALfj0GpsP7e91wqLaAvf85sx097SDPkYanEbrE8jbQyRFNBIDEwMjQg KFdpdGggRUxHLUUgc3Via2V5KSA8ZHNhLTEwMjRAY2hldmFoLmNvbT6IYQQTEQIA IQUCXo8cmgIbIwYLCQgHAwIGFQgCCQoLAxYCAQIeAQIXgAAKCRC9K1lIgMBFqjh9 AJ9b/ezL1h0vv8WlkWA6wqnos+8tjACfWAGMDA0hXoEyL51G7dhLUyi2+5+5AQ0E Xo8cmhAEAKRKf9/t3LPvCVrdOo3smQ8+QjB5GTSXFr+9CF7mbfPYp2vq6jcAlK5g kOAXLdPvWE4DKgZBrK+kRJzs7CC+n5xo7i7nFH634lcsIIi56sYYgvz4NOahd10w yNavtcIBBCi4qWv+L9UtDld1eXoZxFYyOGrQ6tOKZq0sV30/GZ+3AAMFA/9xxj4G y72HAKlqP1Bv3n39c6cJZobbXjbG4YOFNfxjiAk9Y1kr857X1GeR4TV/mK4Zg0pE 4vLakIxoJfdYhYR54LdDeHeUC/UM6uiqkYhAsWNukjpQa6WxJT4+X5Vq5feYQRCV 2um4Aj9gEEHckw7RCAS0kvd9y+s5sgDpiVvmy4hJBBgRAgAJBQJejxyaAhsMAAoJ EL0rWUiAwEWq6LUAoJXpzDlp/9bIQe1gMf39y5FCAZ74AJ4w+IZ6mMMBZKmkq/fD 4i34eph/pg== =9ybR -----END PGP PUBLIC KEY BLOCK----- ```
0.0
3bf2bcd051ac86e41f20b051d21b2f382b59bc9e
[ "tests/test_core.py::TestParse::test_openpgp_public_key", "tests/test_core.py::TestParse::test_openpgp_private_key" ]
[ "tests/test_core.py::TestPEMObjects::test_cert_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_cert_has_correct_str", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_sha1_hexdigest[test]", "tests/test_core.py::TestPEMObjects::test_sha1_hexdigest[test\\r]", "tests/test_core.py::TestPEMObjects::test_as_text", "tests/test_core.py::TestPEMObjects::test_cert_req_has_correct_str", "tests/test_core.py::TestPEMObjects::test_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_rsa_private_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_rsa_public_key_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_rsa_key_has_correct_str", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_dh_params_has_correct_str", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_repr", "tests/test_core.py::TestPEMObjects::test_crl_has_correct_str", "tests/test_core.py::TestPEMObjects::test_certificate_unicode", "tests/test_core.py::TestPEMObjects::test_certificate_request_unicode", "tests/test_core.py::TestPEMObjects::test_key_unicode", "tests/test_core.py::TestPEMObjects::test_rsa_key_unicode", "tests/test_core.py::TestPEMObjects::test_dhparams_unicode_deprecated", "tests/test_core.py::TestPEMObjects::test_crl_unicode", "tests/test_core.py::TestPEMObjects::test_certs_equal", "tests/test_core.py::TestPEMObjects::test_cert_reqs_equal", "tests/test_core.py::TestPEMObjects::test_keys_equal", "tests/test_core.py::TestPEMObjects::test_rsa_keys_equal", "tests/test_core.py::TestPEMObjects::test_dh_params_equal", "tests/test_core.py::TestPEMObjects::test_crl_equal", "tests/test_core.py::TestPEMObjects::test_cert_contents_unequal", "tests/test_core.py::TestPEMObjects::test_cert_req_contents_unequal", "tests/test_core.py::TestPEMObjects::test_crl_unequal", "tests/test_core.py::TestPEMObjects::test_different_objects_unequal", "tests/test_core.py::TestPEMObjects::test_incompatible_types", "tests/test_core.py::TestParse::test_key_pkcs5_unencrypted", "tests/test_core.py::TestParse::test_key_pkcs5_encrypted", "tests/test_core.py::TestParse::test_key_pkcs8_unencrypted", "tests/test_core.py::TestParse::test_key_pkcs8_encrypted", "tests/test_core.py::TestParse::test_certificates", "tests/test_core.py::TestParse::test_certificate_no_new_line", "tests/test_core.py::TestParse::test_certificates_no_new_line", "tests/test_core.py::TestParse::test_certificate_openssl_trusted", "tests/test_core.py::TestParse::test_dh", "tests/test_core.py::TestParse::test_crl", "tests/test_core.py::TestParse::test_file[True]", "tests/test_core.py::TestParse::test_file[False]", "tests/test_core.py::TestParse::test_loads_certifi", "tests/test_core.py::TestParse::test_allows_lf", "tests/test_core.py::TestParse::test_rsa_public_key", "tests/test_core.py::TestParse::test_generic_public_key", "tests/test_core.py::TestParse::test_ec_private_key", "tests/test_core.py::TestParse::test_openshh_private_key", "tests/test_core.py::TestParse::test_dsa_private_key", "tests/test_core.py::TestParse::test_rfc4716_public_key_", "tests/test_core.py::TestParse::test_sshcom_private" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-19 13:49:22+00:00
mit
2,773
hynek__structlog-221
diff --git a/src/structlog/dev.py b/src/structlog/dev.py index 0160650..372f7fc 100644 --- a/src/structlog/dev.py +++ b/src/structlog/dev.py @@ -8,7 +8,7 @@ Helpers that make development with ``structlog`` more pleasant. from __future__ import absolute_import, division, print_function -from six import StringIO +from six import PY2, StringIO, string_types try: @@ -213,7 +213,11 @@ class ConsoleRenderer(object): + "] " ) + # force event to str for compatibility with standard library event = event_dict.pop("event") + if not PY2 or not isinstance(event, string_types): + event = str(event) + if event_dict: event = _pad(event, self._pad_event) + self._styles.reset + " " else:
hynek/structlog
8d3f31517caf2b877fb0dddaa61a81492d20c325
diff --git a/tests/test_dev.py b/tests/test_dev.py index ee048a4..11690ba 100644 --- a/tests/test_dev.py +++ b/tests/test_dev.py @@ -81,6 +81,27 @@ class TestConsoleRenderer(object): assert (styles.timestamp + "42" + styles.reset + " " + unpadded) == rv + def test_event_stringified(self, cr, styles, unpadded): + """ + Event is cast to string. + """ + not_a_string = Exception("test") + + rv = cr(None, None, {"event": not_a_string}) + + assert unpadded == rv + + @pytest.mark.skipif(not six.PY2, reason="Problem only exists on Python 2.") + @pytest.mark.parametrize("s", [u"\xc3\xa4".encode("utf-8"), u"ä", "ä"]) + def test_event_py2_only_stringify_non_strings(self, cr, s, styles): + """ + If event is a string type already, leave it be on Python 2. Running + str() on unicode strings with non-ascii characters raises an error. + """ + rv = cr(None, None, {"event": s}) + + assert styles.bright + s + styles.reset == rv + def test_level(self, cr, styles, padded): """ Levels are rendered aligned, in square brackets, and color coded.
ConsoleRender accepts only string as input Hello :) First of all I would like to thank you for this very handy package. I have observed the following: ```python import structlog structlog.configure( processors=[ structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.dev.ConsoleRenderer() ], context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) mylogger = structlog.get_logger('foo').new() mylogger.info('bar') >> 2018-11-08T10:49:46.903028Z [info ] bar [foo] mylogger.info({'value': 'bar'}) >> Raises TypeError: unsupported operand type(s) for +: 'dict' and 'str' ``` After checking the code for ConsoleRender, it seems that it has been implemented to accept only str as value to log. On the other hand when using JSONRenderer, it logs without any problem a single dictionary as log message. Is this by design ? Am I missing something ?
0.0
8d3f31517caf2b877fb0dddaa61a81492d20c325
[ "tests/test_dev.py::TestConsoleRenderer::test_event_stringified" ]
[ "tests/test_dev.py::TestPad::test_normal", "tests/test_dev.py::TestPad::test_negative", "tests/test_dev.py::TestConsoleRenderer::test_missing_colorama", "tests/test_dev.py::TestConsoleRenderer::test_plain", "tests/test_dev.py::TestConsoleRenderer::test_timestamp", "tests/test_dev.py::TestConsoleRenderer::test_level", "tests/test_dev.py::TestConsoleRenderer::test_init_accepts_overriding_levels", "tests/test_dev.py::TestConsoleRenderer::test_logger_name", "tests/test_dev.py::TestConsoleRenderer::test_key_values", "tests/test_dev.py::TestConsoleRenderer::test_exception", "tests/test_dev.py::TestConsoleRenderer::test_stack_info", "tests/test_dev.py::TestConsoleRenderer::test_pad_event_param", "tests/test_dev.py::TestConsoleRenderer::test_everything", "tests/test_dev.py::TestConsoleRenderer::test_colorama_colors_false", "tests/test_dev.py::TestConsoleRenderer::test_colorama_force_colors", "tests/test_dev.py::TestConsoleRenderer::test_repr_native_str[True]", "tests/test_dev.py::TestConsoleRenderer::test_repr_native_str[False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-False-False]", "tests/test_dev.py::TestSetExcInfo::test_wrong_name", "tests/test_dev.py::TestSetExcInfo::test_already_set[False]", "tests/test_dev.py::TestSetExcInfo::test_already_set[None]", "tests/test_dev.py::TestSetExcInfo::test_already_set[ei2]", "tests/test_dev.py::TestSetExcInfo::test_set_it" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-08-02 05:20:53+00:00
mit
2,774
hynek__structlog-225
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 84961d0..dfe1236 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -51,7 +51,9 @@ Changes: So far, the configuration proxy, ``structlog.processor.TimeStamper``, ``structlog.BoundLogger``, ``structlog.PrintLogger`` and ``structlog.dev.ConsoleLogger`` have been made pickelable. Please report if you need any another class ported. `#126 <https://github.com/hynek/structlog/issues/126>`_ - +- Added a new thread-local API that allows binding values to a thread-local context explicitly without affecting the default behavior of ``bind()``. + `#222 <https://github.com/hynek/structlog/issues/222>`_, + `#225 <https://github.com/hynek/structlog/issues/225>`_, ---- diff --git a/docs/api.rst b/docs/api.rst index 6e01152..231ee8c 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -77,6 +77,12 @@ API Reference .. automodule:: structlog.threadlocal +.. autofunction:: merge_threadlocal_context + +.. autofunction:: clear_threadlocal + +.. autofunction:: bind_threadlocal + .. autofunction:: wrap_dict .. autofunction:: tmp_bind(logger, **tmp_values) diff --git a/docs/thread-local.rst b/docs/thread-local.rst index 4314463..1816210 100644 --- a/docs/thread-local.rst +++ b/docs/thread-local.rst @@ -30,7 +30,57 @@ If you are willing to do that, you should stick to it because `immutable state < Sooner or later, global state and mutable data lead to unpleasant surprises. However, in the case of conventional web development, we realize that passing loggers around seems rather cumbersome, intrusive, and generally against the mainstream culture. -And since it's more important that people actually *use* ``structlog`` than to be pure and snobby, ``structlog`` contains a dirty but convenient trick: thread local context storage which you may already know from `Flask <http://flask.pocoo.org/docs/design/#thread-locals>`_: +And since it's more important that people actually *use* ``structlog`` than to be pure and snobby, ``structlog`` contains a couple of mechanisms to help here. + + +The ``merge_threadlocal_context`` processor +------------------------------------------- + +``structlog`` provides a simple set of functions that allow explicitly binding certain fields to a global (thread-local) context. +These functions are :func:`structlog.threadlocal.merge_threadlocal_context`, :func:`structlog.threadlocal.clear_threadlocal`, and :func:`structlog.threadlocal.bind_threadlocal`. + +The general flow of using these functions is: + +- Use :func:`structlog.configure` with :func:`structlog.threadlocal.merge_threadlocal_context` as your first processor. +- Call :func:`structlog.threadlocal.clear_threadlocal` at the beginning of your request handler (or whenever you want to reset the thread-local context). +- Call :func:`structlog.threadlocal.bind_threadlocal` as an alternative to :func:`structlog.BoundLogger.bind` when you want to bind a particular variable to the thread-local context. +- Use ``structlog`` as normal. + Loggers act as the always do, but the :func:`structlog.threadlocal.merge_threadlocal_context` processor ensures that any thread-local binds get included in all of your log messages. + +.. doctest:: + + >>> from structlog.threadlocal import ( + ... bind_threadlocal, + ... clear_threadlocal, + ... merge_threadlocal_context, + ... ) + >>> from structlog import configure + >>> configure( + ... processors=[ + ... merge_threadlocal_context, + ... structlog.processors.KeyValueRenderer(), + ... ] + ... ) + >>> log = structlog.get_logger() + >>> # At the top of your request handler (or, ideally, some general + >>> # middleware), clear the threadlocal context and bind some common + >>> # values: + >>> clear_threadlocal() + >>> bind_threadlocal(a=1) + >>> # Then use loggers as per normal + >>> # (perhaps by using structlog.get_logger() to create them). + >>> log.msg("hi") + a=1 event='hi' + >>> # And when we clear the threadlocal state again, it goes away. + >>> clear_threadlocal() + >>> log.msg("hi there") + event='hi there' + + +Thread-local contexts +--------------------- + +``structlog`` also provides thread local context storage which you may already know from `Flask <http://flask.pocoo.org/docs/design/#thread-locals>`_: Thread local storage makes your logger's context global but *only within the current thread*\ [*]_. In the case of web frameworks this usually means that your context becomes global to the current request. diff --git a/src/structlog/threadlocal.py b/src/structlog/threadlocal.py index d6eea3a..edbd6cf 100644 --- a/src/structlog/threadlocal.py +++ b/src/structlog/threadlocal.py @@ -9,6 +9,7 @@ Primitives to keep context global but thread (and greenlet) local. from __future__ import absolute_import, division, print_function import contextlib +import threading import uuid from structlog._config import BoundLoggerLazyProxy @@ -162,3 +163,46 @@ class _ThreadLocalDictWrapper(object): def __getattr__(self, name): method = getattr(self._dict, name) return method + + +_CONTEXT = threading.local() + + +def merge_threadlocal_context(logger, method_name, event_dict): + """ + A processor that merges in a global (thread-local) context. + + Use this as your first processor in :func:`structlog.configure` to ensure + thread-local context is included in all log calls. + """ + context = _get_context().copy() + context.update(event_dict) + return context + + +def clear_threadlocal(): + """ + Clear the thread-local context. + + The typical use-case for this function is to invoke it early in + request-handling code. + """ + _CONTEXT.context = {} + + +def bind_threadlocal(**kwargs): + """ + Put keys and values into the thread-local context. + + Use this instead of :func:`~structlog.BoundLogger.bind` when you want some + context to be global (thread-local). + """ + _get_context().update(kwargs) + + +def _get_context(): + try: + return _CONTEXT.context + except AttributeError: + _CONTEXT.context = {} + return _CONTEXT.context
hynek/structlog
d85172bfbb2a002c462a6c31edd1b86c18ed496c
diff --git a/tests/test_threadlocal.py b/tests/test_threadlocal.py index be37949..c9b527d 100644 --- a/tests/test_threadlocal.py +++ b/tests/test_threadlocal.py @@ -13,7 +13,14 @@ import pytest from structlog._base import BoundLoggerBase from structlog._config import wrap_logger from structlog._loggers import ReturnLogger -from structlog.threadlocal import as_immutable, tmp_bind, wrap_dict +from structlog.threadlocal import ( + as_immutable, + bind_threadlocal, + clear_threadlocal, + merge_threadlocal_context, + tmp_bind, + wrap_dict, +) try: @@ -262,3 +269,42 @@ class TestThreadLocalDict(object): The context of a new wrapped class is empty. """ assert 0 == len(D()) + + +class TestNewThreadLocal(object): + def test_bind_and_merge(self): + """ + Binding a variable causes it to be included in the result of + merge_threadlocal_context. + """ + bind_threadlocal(a=1) + assert {"a": 1, "b": 2} == merge_threadlocal_context( + None, None, {"b": 2} + ) + + def test_clear(self): + """ + The thread-local context can be cleared, causing any previously bound + variables to not be included in merge_threadlocal_context's result. + """ + bind_threadlocal(a=1) + clear_threadlocal() + assert {"b": 2} == merge_threadlocal_context(None, None, {"b": 2}) + + def test_merge_works_without_bind(self): + """ + merge_threadlocal_context returns values as normal even when there has + been no previous calls to bind_threadlocal. + """ + assert {"b": 2} == merge_threadlocal_context(None, None, {"b": 2}) + + def test_multiple_binds(self): + """ + Multiple calls to bind_threadlocal accumulate values instead of + replacing them. + """ + bind_threadlocal(a=1, b=2) + bind_threadlocal(c=3) + assert {"a": 1, "b": 2, "c": 3} == merge_threadlocal_context( + None, None, {"b": 2} + )
Is there a way to do threadlocal context for only certain binds? I looked at the `threadlocal` module to solve a problem I have, but from what I can tell, it has undesirable behavior in that it changes all my existing logging code. From what I can tell, all binds become thread-global. But what I want is: "bind this request user and request ID to all messages during this request", and have all the rest of my existing logging code work as it would otherwise.
0.0
d85172bfbb2a002c462a6c31edd1b86c18ed496c
[ "tests/test_threadlocal.py::TestTmpBind::test_bind", "tests/test_threadlocal.py::TestTmpBind::test_bind_exc", "tests/test_threadlocal.py::TestAsImmutable::test_does_not_affect_global", "tests/test_threadlocal.py::TestAsImmutable::test_converts_proxy", "tests/test_threadlocal.py::TestAsImmutable::test_idempotency", "tests/test_threadlocal.py::TestThreadLocalDict::test_wrap_returns_distinct_classes", "tests/test_threadlocal.py::TestThreadLocalDict::test_is_thread_local", "tests/test_threadlocal.py::TestThreadLocalDict::test_context_is_global_to_thread", "tests/test_threadlocal.py::TestThreadLocalDict::test_init_with_itself_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_iter_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_non_dunder_proxy_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_repr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr_missing", "tests/test_threadlocal.py::TestThreadLocalDict::test_del", "tests/test_threadlocal.py::TestThreadLocalDict::test_new_class", "tests/test_threadlocal.py::TestNewThreadLocal::test_bind_and_merge", "tests/test_threadlocal.py::TestNewThreadLocal::test_clear", "tests/test_threadlocal.py::TestNewThreadLocal::test_merge_works_without_bind", "tests/test_threadlocal.py::TestNewThreadLocal::test_multiple_binds" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-21 20:02:39+00:00
mit
2,775
hynek__structlog-228
diff --git a/src/structlog/stdlib.py b/src/structlog/stdlib.py index 86ada28..601a302 100644 --- a/src/structlog/stdlib.py +++ b/src/structlog/stdlib.py @@ -469,12 +469,14 @@ class ProcessorFormatter(logging.Formatter): :param logger: Logger which we want to push through the ``structlog`` processor chain. This parameter is necessary for some of the processors like `filter_by_level`. (default: None) - + :param bool pass_foreign_args: If `True`, pass a foreign log record's + `args` to the event_dict under `positional_args` key. (default: False) :rtype: str .. versionadded:: 17.1.0 .. versionadded:: 17.2.0 *keep_exc_info* and *keep_stack_info* .. versionadded:: 19.2.0 *logger* + .. versionadded:: 19.2.0 *pass_foreign_args* """ def __init__( @@ -484,6 +486,7 @@ class ProcessorFormatter(logging.Formatter): keep_exc_info=False, keep_stack_info=False, logger=None, + pass_foreign_args=False, *args, **kwargs ): @@ -495,6 +498,7 @@ class ProcessorFormatter(logging.Formatter): # The and clause saves us checking for PY3 in the formatter. self.keep_stack_info = keep_stack_info and PY3 self.logger = logger + self.pass_foreign_args = pass_foreign_args def format(self, record): """ @@ -516,6 +520,10 @@ class ProcessorFormatter(logging.Formatter): logger = self.logger meth_name = record.levelname.lower() ed = {"event": record.getMessage(), "_record": record} + + if self.pass_foreign_args: + ed["positional_args"] = record.args + record.args = () # Add stack-related attributes to event_dict and unset them
hynek/structlog
7da6d508413b9df1bd4bdcb70f2353174de70472
diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index e9abb08..b34e21a 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -455,7 +455,7 @@ def configure_for_pf(): reset_defaults() -def configure_logging(pre_chain, logger=None): +def configure_logging(pre_chain, logger=None, pass_foreign_args=False): """ Configure logging to use ProcessorFormatter. """ @@ -470,6 +470,7 @@ def configure_logging(pre_chain, logger=None): "foreign_pre_chain": pre_chain, "format": "%(message)s [in %(funcName)s]", "logger": logger, + "pass_foreign_args": pass_foreign_args, } }, "handlers": { @@ -527,6 +528,29 @@ class TestProcessorFormatter(object): "hello world. [in test_clears_args]\n", ) == capsys.readouterr() + def test_pass_foreign_args_true_sets_positional_args_key( + self, configure_for_pf, capsys + ): + """ + Test that when `pass_foreign_args` is `True` we set the + `positional_args` key in the `event_dict` before clearing args. + """ + test_processor = call_recorder(lambda l, m, event_dict: event_dict) + configure_logging((test_processor,), pass_foreign_args=True) + configure( + processors=[ProcessorFormatter.wrap_for_formatter], + logger_factory=LoggerFactory(), + wrapper_class=BoundLogger, + ) + + positional_args = {"foo": "bar"} + logging.getLogger().info("okay %(foo)s", positional_args) + + event_dict = test_processor.calls[0].args[2] + + assert "positional_args" in event_dict + assert positional_args == event_dict["positional_args"] + def test_log_dict(self, configure_for_pf, capsys): """ Test that dicts can be logged with std library loggers.
Strip LogRecord.args Attribute After foreign_pre_chain Processors Run in ProcessorFormatter First off, thank you to everyone involved in maintaining this project! I love the chained approach it provides to building up a log message context. Great work! I want to start using a structlog-based formatter to output logs as json for several small to medium size code bases I manage. In particular, I want to be able to write a `processor` that takes the *keys* from the `LogRecord.args` attribute and insert them into my `event_dict`. Right now, when the `ProcessorFormatter` class receives a log record from `logging` rather than `structlib`, it sets `LogRecord.args = ()` after generating a message [here](https://github.com/hynek/structlog/blob/0e209d95652c0f9b2943bf0334d74f4964fc7f13/src/structlog/stdlib.py#L519). This means that none of my downstream processors defined in `foreign_pre_chain` can work with the original `LogRecord.args` keys. Would the maintainers be open to moving the `record.args = ()` setting to *after* the `foreign_pre_chain` processors run? I have a working version locally and can add a test if it's a PR you would accept. Speaking more broadly, would you be open to me adding some kind of `migration` docs for projects that currently use the stdlib `logging` package but would like to switch to `structlog`?
0.0
7da6d508413b9df1bd4bdcb70f2353174de70472
[ "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_delegate", "tests/test_stdlib.py::TestProcessorFormatter::test_clears_args", "tests/test_stdlib.py::TestProcessorFormatter::test_pass_foreign_args_true_sets_positional_args_key", "tests/test_stdlib.py::TestProcessorFormatter::test_log_dict", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_add_logger_name", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_chain_can_pass_dictionaries_without_excepting", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_gets_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_other_handlers_get_original_record", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_native", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_filter_by_level" ]
[ "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_name", "tests/test_stdlib.py::TestLoggerFactory::test_ignores_frames", "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_caller", "tests/test_stdlib.py::TestLoggerFactory::test_stack_info", "tests/test_stdlib.py::TestLoggerFactory::test_no_stack_info_by_default", "tests/test_stdlib.py::TestLoggerFactory::test_find_caller", "tests/test_stdlib.py::TestLoggerFactory::test_sets_correct_logger", "tests/test_stdlib.py::TestLoggerFactory::test_positional_argument_avoids_guessing", "tests/test_stdlib.py::TestFilterByLevel::test_filters_lower_levels", "tests/test_stdlib.py::TestFilterByLevel::test_passes_higher_levels", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[debug]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[info]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[warning]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[error]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[critical]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_exception", "tests/test_stdlib.py::TestBoundLogger::test_proxies_log", "tests/test_stdlib.py::TestBoundLogger::test_positional_args_proxied", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[name]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[level]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[parent]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[propagate]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[handlers]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[disabled]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[addHandler-method_args0]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[removeHandler-method_args1]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[hasHandlers-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[callHandlers-method_args3]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[handle-method_args4]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[setLevel-method_args5]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getEffectiveLevel-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[isEnabledFor-method_args7]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[findCaller-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[makeRecord-method_args9]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getChild-method_args10]", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info_override", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_tuple", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_dict", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_positional_args_retained", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_nop_no_args", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_args_removed_if_empty", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[critical-50]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[exception-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[error-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warn-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warning-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[info-20]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[debug-10]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[notset-0]", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_added", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_alias_normalized", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added_with_record", "tests/test_stdlib.py::TestRenderToLogKW::test_default", "tests/test_stdlib.py::TestRenderToLogKW::test_add_extra_event_dict" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-26 00:31:03+00:00
mit
2,776
hynek__structlog-236
diff --git a/docs/contextvars.rst b/docs/contextvars.rst new file mode 100644 index 0000000..230023d --- /dev/null +++ b/docs/contextvars.rst @@ -0,0 +1,70 @@ +.. _contextvars: + +contextvars +=========== + +.. testsetup:: * + + import structlog + +.. testcleanup:: * + + import structlog + structlog.reset_defaults() + +Historically, ``structlog`` only supported thread-local context binding. +With the introduction of ``contextvars`` in Python 3.7, there is now a way of having a global context that is local to the current context and even works in concurrent code. + +The ``merge_context_local`` Processor +------------------------------------- + +``structlog`` provides a set of functions to bind variables to a context-local context. +This context is safe to be used in asynchronous code. +The functions are: + +- :func:`structlog.contextvars.merge_context_local`, +- :func:`structlog.contextvars.clear_context_local`, +- :func:`structlog.contextvars.bind_context_local`, +- :func:`structlog.contextvars.unbind_context_local`, + +The general flow of using these functions is: + +- Use :func:`structlog.configure` with :func:`structlog.contextvars.merge_context_local` as your first processor. +- Call :func:`structlog.contextvars.clear_context_local` at the beginning of your request handler (or whenever you want to reset the context-local context). +- Call :func:`structlog.contextvars.bind_context_local` and :func:`structlog.contextvars.unbind_context_local` instead of :func:`structlog.BoundLogger.bind` and :func:`structlog.BoundLogger.unbind` when you want to (un)bind a particular variable to the context-local context. +- Use ``structlog`` as normal. + Loggers act as the always do, but the :func:`structlog.contextvars.merge_context_local` processor ensures that any context-local binds get included in all of your log messages. + +.. doctest:: + + >>> from structlog.contextvars import ( + ... bind_context_local, + ... clear_context_local, + ... merge_context_local, + ... unbind_context_local, + ... ) + >>> from structlog import configure + >>> configure( + ... processors=[ + ... merge_context_local, + ... structlog.processors.KeyValueRenderer(), + ... ] + ... ) + >>> log = structlog.get_logger() + >>> # At the top of your request handler (or, ideally, some general + >>> # middleware), clear the threadlocal context and bind some common + >>> # values: + >>> clear_context_local() + >>> bind_context_local(a=1, b=2) + >>> # Then use loggers as per normal + >>> # (perhaps by using structlog.get_logger() to create them). + >>> log.msg("hello") + a=1 b=2 event='hello' + >>> # Use unbind_context_local to remove a variable from the context + >>> unbind_context_local("b") + >>> log.msg("world") + a=1 event='world' + >>> # And when we clear the threadlocal state again, it goes away. + >>> clear_context_local() + >>> log.msg("hi there") + event='hi there' diff --git a/docs/index.rst b/docs/index.rst index 22a51dd..eef96f4 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,6 +31,7 @@ Basics loggers configuration thread-local + contextvars processors examples development diff --git a/setup.py b/setup.py index 8993505..2cbffc3 100644 --- a/setup.py +++ b/setup.py @@ -39,6 +39,7 @@ EXTRAS_REQUIRE = { "freezegun>=0.2.8", "pretend", "pytest>=3.3.0", + "pytest-asyncio; python_version>='3.7'", "python-rapidjson; python_version>='3.6'", "simplejson", ], diff --git a/src/structlog/contextvars.py b/src/structlog/contextvars.py new file mode 100644 index 0000000..5706e65 --- /dev/null +++ b/src/structlog/contextvars.py @@ -0,0 +1,68 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the MIT License. See the LICENSE file in the root of this +# repository for complete details. + +""" +Primitives to deal with a concurrency supporting context, as introduced in +Python 3.7 as ``contextvars``. +""" + +from __future__ import absolute_import, division, print_function + +import contextvars + + +_CONTEXT = contextvars.ContextVar("structlog_context") + + +def merge_context_local(logger, method_name, event_dict): + """ + A processor that merges in a global (context-local) context. + + Use this as your first processor in :func:`structlog.configure` to ensure + context-local context is included in all log calls. + """ + ctx = _get_context().copy() + ctx.update(event_dict) + return ctx + + +def clear_context_local(): + """ + Clear the context-local context. + + The typical use-case for this function is to invoke it early in request- + handling code. + """ + ctx = _get_context() + ctx.clear() + + +def bind_context_local(**kwargs): + """ + Put keys and values into the context-local context. + + Use this instead of :func:`~structlog.BoundLogger.bind` when you want some + context to be global (context-local). + """ + _get_context().update(kwargs) + + +def unbind_context_local(*args): + """ + Remove keys from the context-local context. + + Use this instead of :func:`~structlog.BoundLogger.unbind` when you want to + remove keys from a global (context-local) context. + """ + ctx = _get_context() + for key in args: + ctx.pop(key, None) + + +def _get_context(): + try: + return _CONTEXT.get() + except LookupError: + _CONTEXT.set({}) + return _CONTEXT.get() diff --git a/tox.ini b/tox.ini index a7645a2..4126254 100644 --- a/tox.ini +++ b/tox.ini @@ -50,7 +50,7 @@ commands = coverage run --parallel -m pytest {posargs} deps = twisted setenv = PYTHONHASHSEED = 0 -commands = coverage run --parallel -m pytest {posargs} +commands = coverage run --parallel -m pytest --ignore=tests/test_contextvars.py {posargs} [testenv:py27-colorama] @@ -59,7 +59,7 @@ deps = twisted setenv = PYTHONHASHSEED = 0 -commands = coverage run --parallel -m pytest {posargs} +commands = coverage run --parallel -m pytest --ignore=tests/test_contextvars.py {posargs} [testenv:docs]
hynek/structlog
f50641be07e7aa155383cac52332fb7bf3540a59
diff --git a/conftest.py b/conftest.py index 082b344..2a9b20c 100644 --- a/conftest.py +++ b/conftest.py @@ -6,6 +6,8 @@ from __future__ import absolute_import, division, print_function +import sys + import pytest from six.moves import cStringIO as StringIO @@ -30,3 +32,8 @@ def event_dict(): return r"<A(\o/)>" return {"a": A(), "b": [3, 4], "x": 7, "y": "test", "z": (1, 2)} + + +collect_ignore = [] +if sys.version_info[:2] < (3, 7): + collect_ignore.extend(["tests/test_contextvars.py"]) diff --git a/tests/test_contextvars.py b/tests/test_contextvars.py new file mode 100644 index 0000000..d564433 --- /dev/null +++ b/tests/test_contextvars.py @@ -0,0 +1,135 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the MIT License. See the LICENSE file in the root of this +# repository for complete details. + +import pytest + +from structlog.contextvars import ( + bind_context_local, + clear_context_local, + merge_context_local, + unbind_context_local, +) + + +# All test coroutines will be treated as marked. +pytestmark = pytest.mark.asyncio + + +class TestNewContextvars(object): + async def test_bind(self, event_loop): + """ + Binding a variable causes it to be included in the result of + merge_context_local. + """ + + async def coro(): + bind_context_local(a=1) + return merge_context_local(None, None, {"b": 2}) + + assert {"a": 1, "b": 2} == await event_loop.create_task(coro()) + + async def test_multiple_binds(self, event_loop): + """ + Multiple calls to bind_context_local accumulate values instead of + replacing them. But they override redefined ones. + """ + + async def coro(): + bind_context_local(a=1, c=3) + bind_context_local(c=333, d=4) + return merge_context_local(None, None, {"b": 2}) + + assert { + "a": 1, + "b": 2, + "c": 333, + "d": 4, + } == await event_loop.create_task(coro()) + + async def test_nested_async_bind(self, event_loop): + """ + Context is passed correctly between "nested" concurrent operations. + """ + + async def coro(): + bind_context_local(a=1) + await event_loop.create_task(nested_coro()) + return merge_context_local(None, None, {"b": 2}) + + async def nested_coro(): + bind_context_local(c=3) + + assert {"a": 1, "b": 2, "c": 3} == await event_loop.create_task(coro()) + + async def test_merge_works_without_bind(self, event_loop): + """ + merge_context_local returns values as normal even when there has + been no previous calls to bind_context_local. + """ + + async def coro(): + return merge_context_local(None, None, {"b": 2}) + + assert {"b": 2} == await event_loop.create_task(coro()) + + async def test_merge_overrides_bind(self, event_loop): + """ + Variables included in merge_context_local override previously bound + variables. + """ + + async def coro(): + bind_context_local(a=1) + return merge_context_local(None, None, {"a": 111, "b": 2}) + + assert {"a": 111, "b": 2} == await event_loop.create_task(coro()) + + async def test_clear(self, event_loop): + """ + The context-local context can be cleared, causing any previously bound + variables to not be included in merge_context_local's result. + """ + + async def coro(): + bind_context_local(a=1) + clear_context_local() + return merge_context_local(None, None, {"b": 2}) + + assert {"b": 2} == await event_loop.create_task(coro()) + + async def test_clear_without_bind(self, event_loop): + """ + The context-local context can be cleared, causing any previously bound + variables to not be included in merge_context_local's result. + """ + + async def coro(): + clear_context_local() + return merge_context_local(None, None, {}) + + assert {} == await event_loop.create_task(coro()) + + async def test_undbind(self, event_loop): + """ + Unbinding a previously bound variable causes it to be removed from the + result of merge_context_local. + """ + + async def coro(): + bind_context_local(a=1) + unbind_context_local("a") + return merge_context_local(None, None, {"b": 2}) + + assert {"b": 2} == await event_loop.create_task(coro()) + + async def test_undbind_not_bound(self, event_loop): + """ + Unbinding a not bound variable causes doesn't raise an exception. + """ + + async def coro(): + unbind_context_local("a") + return merge_context_local(None, None, {"b": 2}) + + assert {"b": 2} == await event_loop.create_task(coro())
Support for contextvars Does structlog have support for contextvars similar to threadlocal? They are new to Python 3.7, with a backport package available for Python 3.6 and 3.5, and IIUC correctly they are a reasonable replacement for threadlocal even when thread-local is the only requirement, but they also support async functions that would be run in the same thread. http://www.structlog.org/en/stable/thread-local.html https://docs.python.org/3/library/contextvars.html https://github.com/MagicStack/contextvars
0.0
f50641be07e7aa155383cac52332fb7bf3540a59
[ "tests/test_contextvars.py::TestNewContextvars::test_bind", "tests/test_contextvars.py::TestNewContextvars::test_multiple_binds", "tests/test_contextvars.py::TestNewContextvars::test_nested_async_bind", "tests/test_contextvars.py::TestNewContextvars::test_merge_works_without_bind", "tests/test_contextvars.py::TestNewContextvars::test_merge_overrides_bind", "tests/test_contextvars.py::TestNewContextvars::test_clear", "tests/test_contextvars.py::TestNewContextvars::test_clear_without_bind", "tests/test_contextvars.py::TestNewContextvars::test_undbind", "tests/test_contextvars.py::TestNewContextvars::test_undbind_not_bound" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-12-23 12:22:11+00:00
mit
2,777
hynek__structlog-240
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index fe05562..3ab315f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -25,7 +25,7 @@ Deprecations: Changes: ^^^^^^^^ -- Added a new module ``structlog.contextvars`` that allows to have a global but context-local ``structlog`` context the same way as with ``structlog.threalocal`` since 19.2.0. +- Added a new module ``structlog.contextvars`` that allows to have a global but context-local ``structlog`` context the same way as with ``structlog.threadlocal`` since 19.2.0. `#201 <https://github.com/hynek/structlog/issues/201>`_ `#236 <https://github.com/hynek/structlog/pull/236>`_ - Added a new module ``structlog.testing`` for first class testing support. diff --git a/docs/api.rst b/docs/api.rst index bf35681..f1f5220 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -85,7 +85,7 @@ API Reference .. automodule:: structlog.threadlocal -.. autofunction:: merge_threadlocal_context +.. autofunction:: merge_threadlocal .. autofunction:: clear_threadlocal @@ -114,7 +114,7 @@ API Reference .. automodule:: structlog.contextvars -.. autofunction:: merge_contextvars_context +.. autofunction:: merge_contextvars .. autofunction:: clear_contextvars .. autofunction:: bind_contextvars .. autofunction:: unbind_contextvars diff --git a/docs/contextvars.rst b/docs/contextvars.rst index a23edb6..6add8a5 100644 --- a/docs/contextvars.rst +++ b/docs/contextvars.rst @@ -19,31 +19,31 @@ For that ``structlog`` provides a set of functions to bind variables to a contex This context is safe to be used in asynchronous code. The functions are: -- :func:`structlog.contextvars.merge_contextvars_context`, +- :func:`structlog.contextvars.merge_contextvars`, - :func:`structlog.contextvars.clear_contextvars`, - :func:`structlog.contextvars.bind_contextvars`, - :func:`structlog.contextvars.unbind_contextvars`, The general flow of using these functions is: -- Use :func:`structlog.configure` with :func:`structlog.contextvars.merge_contextvars_context` as your first processor. +- Use :func:`structlog.configure` with :func:`structlog.contextvars.merge_contextvars` as your first processor. - Call :func:`structlog.contextvars.clear_contextvars` at the beginning of your request handler (or whenever you want to reset the context-local context). - Call :func:`structlog.contextvars.bind_contextvars` and :func:`structlog.contextvars.unbind_contextvars` instead of :func:`structlog.BoundLogger.bind` and :func:`structlog.BoundLogger.unbind` when you want to (un)bind a particular variable to the context-local context. - Use ``structlog`` as normal. - Loggers act as the always do, but the :func:`structlog.contextvars.merge_contextvars_context` processor ensures that any context-local binds get included in all of your log messages. + Loggers act as the always do, but the :func:`structlog.contextvars.merge_contextvars` processor ensures that any context-local binds get included in all of your log messages. .. doctest:: >>> from structlog.contextvars import ( ... bind_contextvars, ... clear_contextvars, - ... merge_contextvars_context, + ... merge_contextvars, ... unbind_contextvars, ... ) >>> from structlog import configure >>> configure( ... processors=[ - ... merge_contextvars_context, + ... merge_contextvars, ... structlog.processors.KeyValueRenderer(), ... ] ... ) diff --git a/docs/thread-local.rst b/docs/thread-local.rst index c0282d4..fd9f581 100644 --- a/docs/thread-local.rst +++ b/docs/thread-local.rst @@ -33,31 +33,31 @@ However, in the case of conventional web development, we realize that passing lo And since it's more important that people actually *use* ``structlog`` than to be pure and snobby, ``structlog`` contains a couple of mechanisms to help here. -The ``merge_threadlocal_context`` Processor -------------------------------------------- +The ``merge_threadlocal`` Processor +----------------------------------- ``structlog`` provides a simple set of functions that allow explicitly binding certain fields to a global (thread-local) context. -These functions are :func:`structlog.threadlocal.merge_threadlocal_context`, :func:`structlog.threadlocal.clear_threadlocal`, and :func:`structlog.threadlocal.bind_threadlocal`. +These functions are :func:`structlog.threadlocal.merge_threadlocal`, :func:`structlog.threadlocal.clear_threadlocal`, and :func:`structlog.threadlocal.bind_threadlocal`. The general flow of using these functions is: -- Use :func:`structlog.configure` with :func:`structlog.threadlocal.merge_threadlocal_context` as your first processor. +- Use :func:`structlog.configure` with :func:`structlog.threadlocal.merge_threadlocal` as your first processor. - Call :func:`structlog.threadlocal.clear_threadlocal` at the beginning of your request handler (or whenever you want to reset the thread-local context). - Call :func:`structlog.threadlocal.bind_threadlocal` as an alternative to :func:`structlog.BoundLogger.bind` when you want to bind a particular variable to the thread-local context. - Use ``structlog`` as normal. - Loggers act as the always do, but the :func:`structlog.threadlocal.merge_threadlocal_context` processor ensures that any thread-local binds get included in all of your log messages. + Loggers act as the always do, but the :func:`structlog.threadlocal.merge_threadlocal` processor ensures that any thread-local binds get included in all of your log messages. .. doctest:: >>> from structlog.threadlocal import ( ... bind_threadlocal, ... clear_threadlocal, - ... merge_threadlocal_context, + ... merge_threadlocal, ... ) >>> from structlog import configure >>> configure( ... processors=[ - ... merge_threadlocal_context, + ... merge_threadlocal, ... structlog.processors.KeyValueRenderer(), ... ] ... ) diff --git a/src/structlog/_base.py b/src/structlog/_base.py index 3b5c461..23acbc1 100644 --- a/src/structlog/_base.py +++ b/src/structlog/_base.py @@ -86,7 +86,7 @@ class BoundLoggerBase(object): def try_unbind(self, *keys): """ - Like :meth:`unbind`, but best effort: missing keys are ignored. + Like :meth:`unbind`, but best effort: missing keys are ignored. :rtype: `self.__class__` @@ -94,10 +94,8 @@ class BoundLoggerBase(object): """ bl = self.bind() for key in keys: - try: - del bl._context[key] - except KeyError: - pass + bl._context.pop(key, None) + return bl def new(self, **new_values): diff --git a/src/structlog/contextvars.py b/src/structlog/contextvars.py index c780f5b..4fc0bd6 100644 --- a/src/structlog/contextvars.py +++ b/src/structlog/contextvars.py @@ -19,7 +19,7 @@ import contextvars _CONTEXT = contextvars.ContextVar("structlog_context") -def merge_contextvars_context(logger, method_name, event_dict): +def merge_contextvars(logger, method_name, event_dict): """ A processor that merges in a global (context-local) context. @@ -58,9 +58,9 @@ def bind_contextvars(**kwargs): _get_context().update(kwargs) -def unbind_contextvars(*args): +def unbind_contextvars(*keys): """ - Remove keys from the context-local context. + Remove *keys* from the context-local context if they are present. Use this instead of :func:`~structlog.BoundLogger.unbind` when you want to remove keys from a global (context-local) context. @@ -68,7 +68,7 @@ def unbind_contextvars(*args): .. versionadded:: 20.1.0 """ ctx = _get_context() - for key in args: + for key in keys: ctx.pop(key, None) diff --git a/src/structlog/threadlocal.py b/src/structlog/threadlocal.py index ac7d0ad..c5e4a58 100644 --- a/src/structlog/threadlocal.py +++ b/src/structlog/threadlocal.py @@ -170,24 +170,36 @@ class _ThreadLocalDictWrapper(object): _CONTEXT = threading.local() -def merge_threadlocal_context(logger, method_name, event_dict): +def merge_threadlocal(logger, method_name, event_dict): """ A processor that merges in a global (thread-local) context. Use this as your first processor in :func:`structlog.configure` to ensure thread-local context is included in all log calls. + + .. versionadded:: 19.2.0 + + .. versionchanged:: 20.1.0 + This function used to be called ``merge_threalocal_context`` and that + name is still kept around for backward compatability. """ context = _get_context().copy() context.update(event_dict) return context +# Alias that shouldn't be used anymore. +merge_threadlocal_context = merge_threadlocal + + def clear_threadlocal(): """ Clear the thread-local context. The typical use-case for this function is to invoke it early in request-handling code. + + .. versionadded:: 19.2.0 """ _CONTEXT.context = {} @@ -198,6 +210,8 @@ def bind_threadlocal(**kwargs): Use this instead of :func:`~structlog.BoundLogger.bind` when you want some context to be global (thread-local). + + .. versionadded:: 19.2.0 """ _get_context().update(kwargs)
hynek/structlog
0e6a3c6b9b18e57a86137c5b093289f003e2cc6d
diff --git a/tests/test_contextvars.py b/tests/test_contextvars.py index 1257230..c9cf1b0 100644 --- a/tests/test_contextvars.py +++ b/tests/test_contextvars.py @@ -7,7 +7,7 @@ import pytest from structlog.contextvars import ( bind_contextvars, clear_contextvars, - merge_contextvars_context, + merge_contextvars, unbind_contextvars, ) @@ -20,12 +20,12 @@ class TestNewContextvars(object): async def test_bind(self, event_loop): """ Binding a variable causes it to be included in the result of - merge_contextvars_context. + merge_contextvars. """ async def coro(): bind_contextvars(a=1) - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert {"a": 1, "b": 2} == await event_loop.create_task(coro()) @@ -38,7 +38,7 @@ class TestNewContextvars(object): async def coro(): bind_contextvars(a=1, c=3) bind_contextvars(c=333, d=4) - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert { "a": 1, @@ -55,7 +55,7 @@ class TestNewContextvars(object): async def coro(): bind_contextvars(a=1) await event_loop.create_task(nested_coro()) - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) async def nested_coro(): bind_contextvars(c=3) @@ -64,62 +64,62 @@ class TestNewContextvars(object): async def test_merge_works_without_bind(self, event_loop): """ - merge_contextvars_context returns values as normal even when there has + merge_contextvars returns values as normal even when there has been no previous calls to bind_contextvars. """ async def coro(): - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert {"b": 2} == await event_loop.create_task(coro()) async def test_merge_overrides_bind(self, event_loop): """ - Variables included in merge_contextvars_context override previously + Variables included in merge_contextvars override previously bound variables. """ async def coro(): bind_contextvars(a=1) - return merge_contextvars_context(None, None, {"a": 111, "b": 2}) + return merge_contextvars(None, None, {"a": 111, "b": 2}) assert {"a": 111, "b": 2} == await event_loop.create_task(coro()) async def test_clear(self, event_loop): """ The context-local context can be cleared, causing any previously bound - variables to not be included in merge_contextvars_context's result. + variables to not be included in merge_contextvars's result. """ async def coro(): bind_contextvars(a=1) clear_contextvars() - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert {"b": 2} == await event_loop.create_task(coro()) async def test_clear_without_bind(self, event_loop): """ The context-local context can be cleared, causing any previously bound - variables to not be included in merge_contextvars_context's result. + variables to not be included in merge_contextvars's result. """ async def coro(): clear_contextvars() - return merge_contextvars_context(None, None, {}) + return merge_contextvars(None, None, {}) assert {} == await event_loop.create_task(coro()) async def test_undbind(self, event_loop): """ Unbinding a previously bound variable causes it to be removed from the - result of merge_contextvars_context. + result of merge_contextvars. """ async def coro(): bind_contextvars(a=1) unbind_contextvars("a") - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert {"b": 2} == await event_loop.create_task(coro()) @@ -130,6 +130,6 @@ class TestNewContextvars(object): async def coro(): unbind_contextvars("a") - return merge_contextvars_context(None, None, {"b": 2}) + return merge_contextvars(None, None, {"b": 2}) assert {"b": 2} == await event_loop.create_task(coro()) diff --git a/tests/test_threadlocal.py b/tests/test_threadlocal.py index 6661ccb..c986723 100644 --- a/tests/test_threadlocal.py +++ b/tests/test_threadlocal.py @@ -17,6 +17,7 @@ from structlog.threadlocal import ( as_immutable, bind_threadlocal, clear_threadlocal, + merge_threadlocal, merge_threadlocal_context, tmp_bind, wrap_dict, @@ -272,33 +273,37 @@ class TestThreadLocalDict(object): class TestNewThreadLocal(object): + def test_alias(self): + """ + We're keeping the old alias around. + """ + assert merge_threadlocal_context is merge_threadlocal + def test_bind_and_merge(self): """ Binding a variable causes it to be included in the result of - merge_threadlocal_context. + merge_threadlocal. """ bind_threadlocal(a=1) - assert {"a": 1, "b": 2} == merge_threadlocal_context( - None, None, {"b": 2} - ) + assert {"a": 1, "b": 2} == merge_threadlocal(None, None, {"b": 2}) def test_clear(self): """ The thread-local context can be cleared, causing any previously bound - variables to not be included in merge_threadlocal_context's result. + variables to not be included in merge_threadlocal's result. """ bind_threadlocal(a=1) clear_threadlocal() - assert {"b": 2} == merge_threadlocal_context(None, None, {"b": 2}) + assert {"b": 2} == merge_threadlocal(None, None, {"b": 2}) def test_merge_works_without_bind(self): """ - merge_threadlocal_context returns values as normal even when there has + merge_threadlocal returns values as normal even when there has been no previous calls to bind_threadlocal. """ - assert {"b": 2} == merge_threadlocal_context(None, None, {"b": 2}) + assert {"b": 2} == merge_threadlocal(None, None, {"b": 2}) def test_multiple_binds(self): """ @@ -308,6 +313,6 @@ class TestNewThreadLocal(object): bind_threadlocal(a=1, b=2) bind_threadlocal(c=3) - assert {"a": 1, "b": 2, "c": 3} == merge_threadlocal_context( + assert {"a": 1, "b": 2, "c": 3} == merge_threadlocal( None, None, {"b": 2} )
Consistently name threadlocal and contextvars helper functions The threadlocal and contextvars integrations use a different naming for their functions to bind, unbind, merge and clear the context. This came up as part of #236 and e3a6213afb2844572c8890693a83e142c41b1f0b. I'd like to propose the following function names: - `contextvars` - `merge_contextvars_context` - `clear_contextvars_context` - `bind_to_contextvars_context` - `unbind_from_contextvars_context` - `threadlocal` - `merge_threadlocal_context` - `clear_threadlocal_context` - `bind_to_threadlocal_context` - `unbind_from_threadlocal_context` -- doesn't exist but should probably be added
0.0
0e6a3c6b9b18e57a86137c5b093289f003e2cc6d
[ "tests/test_contextvars.py::TestNewContextvars::test_bind", "tests/test_contextvars.py::TestNewContextvars::test_multiple_binds", "tests/test_contextvars.py::TestNewContextvars::test_nested_async_bind", "tests/test_contextvars.py::TestNewContextvars::test_merge_works_without_bind", "tests/test_contextvars.py::TestNewContextvars::test_merge_overrides_bind", "tests/test_contextvars.py::TestNewContextvars::test_clear", "tests/test_contextvars.py::TestNewContextvars::test_clear_without_bind", "tests/test_contextvars.py::TestNewContextvars::test_undbind", "tests/test_contextvars.py::TestNewContextvars::test_undbind_not_bound", "tests/test_threadlocal.py::TestTmpBind::test_bind", "tests/test_threadlocal.py::TestTmpBind::test_bind_exc", "tests/test_threadlocal.py::TestAsImmutable::test_does_not_affect_global", "tests/test_threadlocal.py::TestAsImmutable::test_converts_proxy", "tests/test_threadlocal.py::TestAsImmutable::test_idempotency", "tests/test_threadlocal.py::TestThreadLocalDict::test_wrap_returns_distinct_classes", "tests/test_threadlocal.py::TestThreadLocalDict::test_is_thread_local", "tests/test_threadlocal.py::TestThreadLocalDict::test_context_is_global_to_thread", "tests/test_threadlocal.py::TestThreadLocalDict::test_init_with_itself_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_iter_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_non_dunder_proxy_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_repr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr_missing", "tests/test_threadlocal.py::TestThreadLocalDict::test_del", "tests/test_threadlocal.py::TestThreadLocalDict::test_new_class", "tests/test_threadlocal.py::TestNewThreadLocal::test_alias", "tests/test_threadlocal.py::TestNewThreadLocal::test_bind_and_merge", "tests/test_threadlocal.py::TestNewThreadLocal::test_clear", "tests/test_threadlocal.py::TestNewThreadLocal::test_merge_works_without_bind", "tests/test_threadlocal.py::TestNewThreadLocal::test_multiple_binds" ]
[]
{ "failed_lite_validators": [ "has_git_commit_hash", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-18 16:36:33+00:00
mit
2,778
hynek__structlog-331
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index fa6b7c3..edd47b8 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -32,6 +32,8 @@ Changes: - If the `better-exceptions <https://github.com/qix-/better-exceptions>`_ package is present, ``structlog.dev.ConsoleRenderer`` will now pretty-print exceptions using it. Pass ``pretty_exceptions=False`` to disable. This only works if ``format_exc_info`` is **absent** in the processor chain. +- ``structlog.threadlocal.get_threadlocal()`` can now be used to get a copy of the current thread-local context that has been bound using ``structlog.threadlocal.bind_threadlocal()``. +- ``structlog.threadlocal.get_merged_threadlocal(bl)`` does the same, but also merges the context from a bound logger *bl*. ---- diff --git a/docs/api.rst b/docs/api.rst index b1307da..869ba83 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -109,11 +109,39 @@ API Reference .. automodule:: structlog.threadlocal + +Modern Approach +~~~~~~~~~~~~~~~ + +.. autofunction:: bind_threadlocal + +.. autofunction:: get_threadlocal + + >>> from structlog.threadlocal import bind_threadlocal, get_threadlocal + >>> bind_threadlocal(x=1) + >>> get_threadlocal() + {'x': 1} + +.. autofunction:: get_merged_threadlocal + + >>> from structlog import get_logger + >>> from structlog.threadlocal import bind_threadlocal, get_merged_threadlocal + >>> bind_threadlocal(x=1) + >>> log = get_logger() + >>> log = log.bind(y=2) + >>> get_merged_threadlocal(log) + {'x': 1, 'y': 2} + .. autofunction:: merge_threadlocal .. autofunction:: clear_threadlocal -.. autofunction:: bind_threadlocal + +Old Approach +~~~~~~~~~~~~ + +The following APIs use a different approach, that we discourage nowadays. +Please see :doc:`thread-local` for details. .. autofunction:: wrap_dict diff --git a/docs/thread-local.rst b/docs/thread-local.rst index 0a08281..efe6993 100644 --- a/docs/thread-local.rst +++ b/docs/thread-local.rst @@ -19,16 +19,16 @@ Immutability You should call some functions with some arguments. - ---David Reid + --- David Reid -The behavior of copying itself, adding new values, and returning the result is useful for applications that keep somehow their own context using classes or closures. -Twisted is a `fine example <twisted-example>` for that. -Another possible approach is passing wrapped loggers around or log only within your view where you gather errors and events using return codes and exceptions. -If you are willing to do that, you should stick to it because `immutable state <https://en.wikipedia.org/wiki/Immutable_object>`_ is a very good thing\ [*]_. -Sooner or later, global state and mutable data lead to unpleasant surprises. +``structlog`` does its best to have as little global state as possible to achieve its goals. +In an ideal world, you would just stick to its immutable\ [*]_ bound loggers and reap all the rewards of having purely `immutable state <https://en.wikipedia.org/wiki/Immutable_object>`_. -However, in the case of conventional web development, we realize that passing loggers around seems rather cumbersome, intrusive, and generally against the mainstream culture. -And since it's more important that people actually *use* ``structlog`` than to be pure and snobby, ``structlog`` ships with the `structlog.threadlocal` module and a couple of mechanisms to help here. +However, we realize that passing loggers around is rather clunky and intrusive in practice. +And since `practicality beats purity <https://www.python.org/dev/peps/pep-0020/>`_, ``structlog`` ships with the `structlog.threadlocal` module to help you to safely have global context storage. + +.. [*] In the spirit of Python's 'consenting adults', ``structlog`` doesn't enforce the immutability with technical means. + However, if you don't meddle with undocumented data, the objects can be safely considered immutable. The ``merge_threadlocal`` Processor @@ -43,6 +43,7 @@ The general flow of using these functions is: - Call `structlog.threadlocal.bind_threadlocal` as an alternative to your bound logger's ``bind()`` when you want to bind a particular variable to the thread-local context. - Use ``structlog`` as normal. Loggers act as they always do, but the `structlog.threadlocal.merge_threadlocal` processor ensures that any thread-local binds get included in all of your log messages. +- If you want to access the thread-local storage, you use `structlog.threadlocal.get_threadlocal` and `structlog.threadlocal.get_merged_threadlocal`. .. doctest:: @@ -184,7 +185,3 @@ In this case we feel like this is an acceptable trade-off. You can easily write deterministic tests using a call-capturing processor if you use the API properly (cf. warning above). This big red box is also what separates immutable local from mutable global data. - - -.. [*] In the spirit of Python's 'consenting adults', ``structlog`` doesn't enforce the immutability with technical means. - However, if you don't meddle with undocumented data, the objects can be safely considered immutable. diff --git a/src/structlog/threadlocal.py b/src/structlog/threadlocal.py index ea221ac..31df92e 100644 --- a/src/structlog/threadlocal.py +++ b/src/structlog/threadlocal.py @@ -13,6 +13,8 @@ import uuid from typing import Any, Dict, Generator, Iterator, Type, TypeVar +import structlog + from ._config import BoundLoggerLazyProxy from .types import BindableLogger, Context, EventDict, WrappedLogger @@ -169,6 +171,28 @@ class _ThreadLocalDictWrapper: _CONTEXT = threading.local() +def get_threadlocal() -> Context: + """ + Return a copy of the current thread-local context. + + .. versionadded:: 21.2.0 + """ + return _get_context().copy() + + +def get_merged_threadlocal(bound_logger: BindableLogger) -> Context: + """ + Return a copy of the current thread-local context merged with the context + from *bound_logger*. + + .. versionadded:: 21.2.0 + """ + ctx = _get_context().copy() + ctx.update(structlog.get_context(bound_logger)) + + return ctx + + def merge_threadlocal( logger: WrappedLogger, method_name: str, event_dict: EventDict ) -> EventDict: @@ -181,7 +205,7 @@ def merge_threadlocal( .. versionadded:: 19.2.0 .. versionchanged:: 20.1.0 - This function used to be called ``merge_threalocal_context`` and that + This function used to be called ``merge_threadlocal_context`` and that name is still kept around for backward compatibility. """ context = _get_context().copy()
hynek/structlog
1f76a041dbeeb4e23a5128c9465a96a0ef789267
diff --git a/tests/test_threadlocal.py b/tests/test_threadlocal.py index 1675078..2cac457 100644 --- a/tests/test_threadlocal.py +++ b/tests/test_threadlocal.py @@ -7,15 +7,18 @@ import threading import pytest +import structlog + from structlog._base import BoundLoggerBase from structlog._config import wrap_logger from structlog.testing import ReturnLogger from structlog.threadlocal import ( _CONTEXT, - _get_context, as_immutable, bind_threadlocal, clear_threadlocal, + get_merged_threadlocal, + get_threadlocal, merge_threadlocal, merge_threadlocal_context, tmp_bind, @@ -326,19 +329,18 @@ class TestNewThreadLocal: Test that unbinding from threadlocal works for keys that exist and does not raise error when they do not exist. """ - clear_threadlocal() bind_threadlocal(a=234, b=34) - assert {"a": 234, "b": 34} == merge_threadlocal_context(None, None, {}) + assert {"a": 234, "b": 34} == get_threadlocal() unbind_threadlocal("a") - assert {"b": 34} == merge_threadlocal_context(None, None, {}) + assert {"b": 34} == get_threadlocal() unbind_threadlocal("non-existing-key") - assert {"b": 34} == merge_threadlocal_context(None, None, {}) + assert {"b": 34} == get_threadlocal() def test_get_context_no_context(self): """ @@ -351,4 +353,16 @@ class TestNewThreadLocal: with pytest.raises(AttributeError): _CONTEXT.context - assert {} == _get_context() + assert {} == get_threadlocal() + + def test_get_merged(self): + """ + Returns a copy of the threadlocal context merged with the logger's + context. + """ + clear_threadlocal() + bind_threadlocal(x=1) + + log = structlog.get_logger().bind(y=2) + + assert {"x": 1, "y": 2} == get_merged_threadlocal(log)
Public access to threadlocal._get_context() Similarly to #266, I find myself needing to access the thread-local context (I need to re-estabish some bound variables after a `clean_threadlocal()`). I tried to use `structlog.get_context()` but it's not returning the threadlocal context. If this would be accepted, I might even come up with a PR.
0.0
1f76a041dbeeb4e23a5128c9465a96a0ef789267
[ "tests/test_threadlocal.py::TestTmpBind::test_bind", "tests/test_threadlocal.py::TestTmpBind::test_bind_exc", "tests/test_threadlocal.py::TestAsImmutable::test_does_not_affect_global", "tests/test_threadlocal.py::TestAsImmutable::test_converts_proxy", "tests/test_threadlocal.py::TestAsImmutable::test_idempotency", "tests/test_threadlocal.py::TestThreadLocalDict::test_wrap_returns_distinct_classes", "tests/test_threadlocal.py::TestThreadLocalDict::test_is_thread_local", "tests/test_threadlocal.py::TestThreadLocalDict::test_context_is_global_to_thread", "tests/test_threadlocal.py::TestThreadLocalDict::test_init_with_itself_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_iter_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_non_dunder_proxy_works", "tests/test_threadlocal.py::TestThreadLocalDict::test_repr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr", "tests/test_threadlocal.py::TestThreadLocalDict::test_delattr_missing", "tests/test_threadlocal.py::TestThreadLocalDict::test_del", "tests/test_threadlocal.py::TestThreadLocalDict::test_new_class", "tests/test_threadlocal.py::TestNewThreadLocal::test_alias", "tests/test_threadlocal.py::TestNewThreadLocal::test_bind_and_merge", "tests/test_threadlocal.py::TestNewThreadLocal::test_clear", "tests/test_threadlocal.py::TestNewThreadLocal::test_merge_works_without_bind", "tests/test_threadlocal.py::TestNewThreadLocal::test_multiple_binds", "tests/test_threadlocal.py::TestNewThreadLocal::test_unbind_threadlocal", "tests/test_threadlocal.py::TestNewThreadLocal::test_get_context_no_context", "tests/test_threadlocal.py::TestNewThreadLocal::test_get_merged" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-11 08:46:55+00:00
mit
2,779
hynek__structlog-350
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2b4d49b..4332c70 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -39,6 +39,8 @@ Changes: - All use of ``colorama`` on non-Windows systems has been excised. Thus, colors are now enabled by default in ``structlog.dev.ConsoleRenderer`` on non-Windows systems. You can keep using ``colorama`` to customize colors, of course. +- The final processor can now return a ``bytearray`` (additionally to ``str`` and ``bytes``). + `#344 <https://github.com/hynek/structlog/issues/344>`_ ---- diff --git a/docs/processors.rst b/docs/processors.rst index 40cca26..427c63c 100644 --- a/docs/processors.rst +++ b/docs/processors.rst @@ -101,7 +101,7 @@ With that, it's also the *only* processor that needs to know anything about the It can return one of three types: -- An Unicode string or a bytes string (i.e. `str` or `bytes`) that is passed as the first (and only) positional argument to the underlying logger. +- An Unicode string (`str`), a bytes string (`bytes`), or a `bytearray` that is passed as the first (and only) positional argument to the underlying logger. - A tuple of ``(args, kwargs)`` that are passed as ``log_method(*args, **kwargs)``. - A dictionary which is passed as ``log_method(**kwargs)``. diff --git a/src/structlog/_base.py b/src/structlog/_base.py index ec6a2a8..8c97ac9 100644 --- a/src/structlog/_base.py +++ b/src/structlog/_base.py @@ -131,7 +131,7 @@ class BoundLoggerBase: :raises: `structlog.DropEvent` if log entry should be dropped. :raises: `ValueError` if the final processor doesn't return a - str, bytes, tuple, or a dict. + str, bytes, bytearray, tuple, or a dict. :returns: `tuple` of ``(*args, **kw)`` @@ -143,6 +143,10 @@ class BoundLoggerBase: .. versionchanged:: 14.0.0 Allow final processor to return a `dict`. + .. versionchanged:: 20.2.0 + Allow final processor to return `bytes`. + .. versionchanged:: 21.2.0 + Allow final processor to return a `bytearray`. """ # We're typing it as Any, because processors can return more than an # EventDict. @@ -154,7 +158,7 @@ class BoundLoggerBase: for proc in self._processors: event_dict = proc(self._logger, method_name, event_dict) - if isinstance(event_dict, (str, bytes)): + if isinstance(event_dict, (str, bytes, bytearray)): return (event_dict,), {} elif isinstance(event_dict, tuple): # In this case we assume that the last processor returned a tuple diff --git a/src/structlog/types.py b/src/structlog/types.py index 199a706..c4a0dd4 100644 --- a/src/structlog/types.py +++ b/src/structlog/types.py @@ -64,7 +64,7 @@ copy itself. Processor = Callable[ [WrappedLogger, str, EventDict], - Union[Mapping[str, Any], str, bytes, Tuple[Any, ...]], + Union[Mapping[str, Any], str, bytes, bytearray, Tuple[Any, ...]], ] """ A callable that is part of the processor chain.
hynek/structlog
6bd5b32ea58a9f9a8edfd846284f918b78fe3468
diff --git a/tests/test_base.py b/tests/test_base.py index 4021a3e..6299461 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -186,6 +186,16 @@ class TestProcessing: assert ((b"foo",), {}) == b._process_event(None, "name", {}) + def test_last_processor_returns_bytearray(self): + """ + If the final processor returns a bytearray, ``(the_array,), {}`` is + returned. + """ + logger = stub(msg=lambda *args, **kw: (args, kw)) + b = build_bl(logger, processors=[lambda *_: bytearray(b"foo")]) + + assert ((bytearray(b"foo"),), {}) == b._process_event(None, "name", {}) + def test_last_processor_returns_tuple(self): """ If the final processor returns a tuple, it is just passed through.
Support bytearray for final processor output Use case: For performance in concatenating bytes, one might want their final processor to output a `bytearray` instead of `bytes`. This [blog post](https://www.guyrutenberg.com/2020/04/04/fast-bytes-concatenation-in-python/) illustrates that using a `bytearray` is the most performant way to concatenate bytes in Python (with all the caveats of sharing results from a blog post that haven't been verified locally, and the experiment can't exactly be considered comprehensive or rigorous). Use of `bytearray` output is currently unsupported, as can be seen in [_base.py](https://github.com/hynek/structlog/blob/4c19f0c10077492212b9b6aa0a9e68b6a644675e/src/structlog/_base.py#L157): ```python ... if isinstance(event_dict, (str, bytes)): return (event_dict,), {} elif isinstance(event_dict, tuple): # In this case we assume that the last processor returned a tuple # of ``(args, kwargs)`` and pass it right through. return event_dict # type: ignore elif isinstance(event_dict, dict): return (), event_dict else: raise ValueError( "Last processor didn't return an appropriate value. Valid " "return values are a dict, a tuple of (args, kwargs), bytes, " "or a str." ) ... ``` I'll be honest in that I'm not an expert in byte handling in Python, but it seems like `bytearray` quacks like `bytes` according to the docs: - https://docs.python.org/3/library/functions.html#func-bytearray - https://docs.python.org/3/library/stdtypes.html#bytearray In a very crude and naive local test, I modified this line in `structlog` from: `if isinstance(event_dict, (str, bytes)):` to: `if isinstance(event_dict, (str, bytes, bytearray)):` and my stdout bytes logging still worked (configured identically to [this example](https://www.structlog.org/en/stable/performance.html#example) in the Performance section of the `structlog` docs).
0.0
6bd5b32ea58a9f9a8edfd846284f918b78fe3468
[ "tests/test_base.py::TestProcessing::test_last_processor_returns_bytearray" ]
[ "tests/test_base.py::TestBinding::test_repr", "tests/test_base.py::TestBinding::test_binds_independently", "tests/test_base.py::TestBinding::test_new_clears_state", "tests/test_base.py::TestBinding::test_comparison", "tests/test_base.py::TestBinding::test_bind_keeps_class", "tests/test_base.py::TestBinding::test_new_keeps_class", "tests/test_base.py::TestBinding::test_unbind", "tests/test_base.py::TestBinding::test_unbind_fail", "tests/test_base.py::TestBinding::test_try_unbind", "tests/test_base.py::TestBinding::test_try_unbind_fail", "tests/test_base.py::TestProcessing::test_event_empty_string", "tests/test_base.py::TestProcessing::test_copies_context_before_processing", "tests/test_base.py::TestProcessing::test_chain_does_not_swallow_all_exceptions", "tests/test_base.py::TestProcessing::test_last_processor_returns_string", "tests/test_base.py::TestProcessing::test_last_processor_returns_bytes", "tests/test_base.py::TestProcessing::test_last_processor_returns_tuple", "tests/test_base.py::TestProcessing::test_last_processor_returns_dict", "tests/test_base.py::TestProcessing::test_last_processor_returns_unknown_value", "tests/test_base.py::TestProxying::test_processor_raising_DropEvent_silently_aborts_chain" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-08-29 08:00:08+00:00
mit
2,780
hynek__structlog-463
diff --git a/src/structlog/_log_levels.py b/src/structlog/_log_levels.py index 997d948..501c44a 100644 --- a/src/structlog/_log_levels.py +++ b/src/structlog/_log_levels.py @@ -88,11 +88,10 @@ def exception(self: FilteringBoundLogger, event: str, **kw: Any) -> Any: async def aexception(self: FilteringBoundLogger, event: str, **kw: Any) -> Any: kw.setdefault("exc_info", True) + ctx = contextvars.copy_context() return await asyncio.get_running_loop().run_in_executor( None, - lambda: contextvars.copy_context().run( - lambda: self.error(event, **kw) - ), + lambda: ctx.run(lambda: self.error(event, **kw)), ) @@ -157,9 +156,10 @@ def _make_filtering_bound_logger(min_level: int) -> type[FilteringBoundLogger]: return self._proxy_to_logger(name, event % args, **kw) async def ameth(self: Any, event: str, *args: Any, **kw: Any) -> Any: + ctx = contextvars.copy_context() await asyncio.get_running_loop().run_in_executor( None, - lambda: contextvars.copy_context().run( + lambda: ctx.run( lambda: self._proxy_to_logger(name, event % args, **kw) ), ) @@ -183,9 +183,10 @@ def _make_filtering_bound_logger(min_level: int) -> type[FilteringBoundLogger]: return None name = _LEVEL_TO_NAME[level] + ctx = contextvars.copy_context() return await asyncio.get_running_loop().run_in_executor( None, - lambda: contextvars.copy_context().run( + lambda: ctx.run( lambda: self._proxy_to_logger(name, event % args, **kw) ), )
hynek/structlog
14cb331a62a38c71e4de19d66f75d3a8d3389c58
diff --git a/tests/test_log_levels.py b/tests/test_log_levels.py index 285dbfc..1a37273 100644 --- a/tests/test_log_levels.py +++ b/tests/test_log_levels.py @@ -10,6 +10,11 @@ import pytest from structlog import make_filtering_bound_logger from structlog._log_levels import _LEVEL_TO_NAME +from structlog.contextvars import ( + bind_contextvars, + clear_contextvars, + merge_contextvars, +) from structlog.testing import CapturingLogger @@ -88,7 +93,7 @@ class TestFilteringLogger: assert [] == cl.calls - def test_filter_bound_below_missing_event_string(self, bl, cl): + def test_filter_bound_below_missing_event_string(self, bl): """ Missing event arg causes exception below min_level. """ @@ -99,7 +104,7 @@ class TestFilteringLogger: message = "missing 1 required positional argument: 'event'" assert message in exc_info.value.args[0] - def test_filter_bound_exact_missing_event_string(self, bl, cl): + def test_filter_bound_exact_missing_event_string(self, bl): """ Missing event arg causes exception even at min_level. """ @@ -110,23 +115,23 @@ class TestFilteringLogger: message = "missing 1 required positional argument: 'event'" assert message in exc_info.value.args[0] - def test_exception(self, bl): + def test_exception(self, bl, cl): """ exception ensures that exc_info is set to True, unless it's already set. """ bl.exception("boom") - assert [("error", (), {"event": "boom", "exc_info": True})] + assert [("error", (), {"event": "boom", "exc_info": True})] == cl.calls - async def test_async_exception(self, bl): + async def test_async_exception(self, bl, cl): """ exception ensures that exc_info is set to True, unless it's already set. """ await bl.aexception("boom") - assert [("error", (), {"event": "boom", "exc_info": True})] + assert [("error", (), {"event": "boom", "exc_info": True})] == cl.calls def test_exception_passed(self, bl, cl): """ @@ -134,7 +139,7 @@ class TestFilteringLogger: """ bl.exception("boom", exc_info=42) - assert [("error", (), {"event": "boom", "exc_info": 42})] + assert [("error", (), {"event": "boom", "exc_info": 42})] == cl.calls async def test_async_exception_passed(self, bl, cl): """ @@ -142,7 +147,7 @@ class TestFilteringLogger: """ await bl.aexception("boom", exc_info=42) - assert [("error", (), {"event": "boom", "exc_info": 42})] + assert [("error", (), {"event": "boom", "exc_info": 42})] == cl.calls @pytest.mark.parametrize("level", tuple(_LEVEL_TO_NAME.keys())) def test_pickle(self, level): @@ -168,3 +173,21 @@ class TestFilteringLogger: await bl.ainfo("hello %s -- %d!", "world", 42) assert [("info", (), {"event": "hello world -- 42!"})] == cl.calls + + @pytest.mark.parametrize( + "meth,args", + [ + ("aexception", ("ev",)), + ("ainfo", ("ev",)), + ("alog", (logging.INFO, "ev")), + ], + ) + async def test_async_contextvars_merged(self, meth, args, cl): + clear_contextvars() + bl = make_filtering_bound_logger(logging.INFO)( + cl, [merge_contextvars], {} + ) + bind_contextvars(context_included="yep") + await getattr(bl, meth)(*args) + assert len(cl.calls) == 1 + assert "context_included" in cl.calls[0].kwargs
FilteringBoundLogger Async methods - capture context outside of executor thread Taking the new async methods on `FilteringBoundLogger` for a spin, I noticed context captured with `bind_contextvars()` is not logged. Narrowed it down to this pattern: ```python return await asyncio.get_running_loop().run_in_executor( None, lambda: contextvars.copy_context().run( lambda: self._proxy_to_logger(name, event % args, **kw) ), ) ``` When `contextvars.copy_context()` is called it is in in the executor thread, so different context. To fix, just capture the context outside of the lambda: ```python ctx = contextvars.copy_context() return await asyncio.get_running_loop().run_in_executor( None, lambda: ctx.run( lambda: self._proxy_to_logger(name, event % args, **kw) ), ) ``` I'd be happy to PR. Cheers!
0.0
14cb331a62a38c71e4de19d66f75d3a8d3389c58
[ "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[aexception-args0]", "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[ainfo-args1]", "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[alog-args2]" ]
[ "tests/test_log_levels.py::TestFilteringLogger::test_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_async_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_async_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_log_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_alog_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_log_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_alog_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_filter_bound_below_missing_event_string", "tests/test_log_levels.py::TestFilteringLogger::test_filter_bound_exact_missing_event_string", "tests/test_log_levels.py::TestFilteringLogger::test_exception", "tests/test_log_levels.py::TestFilteringLogger::test_async_exception", "tests/test_log_levels.py::TestFilteringLogger::test_exception_passed", "tests/test_log_levels.py::TestFilteringLogger::test_async_exception_passed", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[50]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[40]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[30]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[20]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[10]", "tests/test_log_levels.py::TestFilteringLogger::test_pos_args", "tests/test_log_levels.py::TestFilteringLogger::test_async_pos_args" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-11-03 12:19:34+00:00
mit
2,781
hynek__structlog-478
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ddee6f..48eeb0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,12 @@ This prevents crashes if something different than a string is passed for the *ev [#475](https://github.com/hynek/structlog/pull/475) +### Fixed + +- String interpolation doesn't cause crashes in filtered log call anymore. + [#478](https://github.com/hynek/structlog/pull/478) + + ## [22.2.0](https://github.com/hynek/structlog/compare/22.1.0...22.2.0) - 2022-11-19 ### Deprecated diff --git a/src/structlog/_log_levels.py b/src/structlog/_log_levels.py index 4d49780..6e9fb1a 100644 --- a/src/structlog/_log_levels.py +++ b/src/structlog/_log_levels.py @@ -71,11 +71,11 @@ def add_log_level( return event_dict -def _nop(self: Any, event: str, **kw: Any) -> Any: +def _nop(self: Any, event: str, *args: Any, **kw: Any) -> Any: return None -async def _anop(self: Any, event: str, **kw: Any) -> Any: +async def _anop(self: Any, event: str, *args: Any, **kw: Any) -> Any: return None
hynek/structlog
87cdcaf0205f9b62f793f331160d17cb12316e0d
diff --git a/tests/test_log_levels.py b/tests/test_log_levels.py index fff9cce..2a0e579 100644 --- a/tests/test_log_levels.py +++ b/tests/test_log_levels.py @@ -61,6 +61,22 @@ class TestFilteringLogger: assert [] == cl.calls + def test_filtered_interp(self, bl, cl): + """ + Passing interpolation args works if the log entry is filtered out. + """ + bl.debug("hello %s!", "world") + + assert [] == cl.calls + + async def test_async_filtered_interp(self, bl, cl): + """ + Passing interpolation args works if the log entry is filtered out. + """ + await bl.adebug("hello %s!", "world") + + assert [] == cl.calls + def test_no_args(self, bl, cl): """ If no args are passed, don't attempt intepolation.
Interpolation raises an error for filtered out logs Interpolation appears to be broken when the log is filtered out. Observed with structulog 22.2.0. ```python import logging import structlog structlog.configure( processors=[ structlog.contextvars.merge_contextvars, structlog.processors.add_log_level, structlog.processors.StackInfoRenderer(), structlog.dev.set_exc_info, structlog.processors.TimeStamper(), structlog.dev.ConsoleRenderer() ], # Note this is set at the INFO level wrapper_class=structlog.make_filtering_bound_logger(logging.INFO), context_class=dict, logger_factory=structlog.PrintLoggerFactory(), cache_logger_on_first_use=False ) log = structlog.get_logger() # Note this is at the DEBUG level, there's no problem at the INFO level or higher log.debug('hello %s', 'world') ``` Traceback: ``` Traceback (most recent call last): File "/home/liquetm/dev/python-panels/bug.py", line 21, in <module> log.debug('hello %s', 'world') TypeError: _nop() takes 2 positional arguments but 3 were given ```
0.0
87cdcaf0205f9b62f793f331160d17cb12316e0d
[ "tests/test_log_levels.py::TestFilteringLogger::test_filtered_interp", "tests/test_log_levels.py::TestFilteringLogger::test_async_filtered_interp" ]
[ "tests/test_log_levels.py::TestFilteringLogger::test_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_async_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_async_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_no_args", "tests/test_log_levels.py::TestFilteringLogger::test_async_no_args", "tests/test_log_levels.py::TestFilteringLogger::test_log_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_alog_exact_level", "tests/test_log_levels.py::TestFilteringLogger::test_log_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_alog_one_below", "tests/test_log_levels.py::TestFilteringLogger::test_alog_no_args", "tests/test_log_levels.py::TestFilteringLogger::test_log_interp", "tests/test_log_levels.py::TestFilteringLogger::test_alog_interp", "tests/test_log_levels.py::TestFilteringLogger::test_filter_bound_below_missing_event_string", "tests/test_log_levels.py::TestFilteringLogger::test_filter_bound_exact_missing_event_string", "tests/test_log_levels.py::TestFilteringLogger::test_exception", "tests/test_log_levels.py::TestFilteringLogger::test_async_exception", "tests/test_log_levels.py::TestFilteringLogger::test_exception_passed", "tests/test_log_levels.py::TestFilteringLogger::test_async_exception_passed", "tests/test_log_levels.py::TestFilteringLogger::test_exception_pass_exception", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[50]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[40]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[30]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[20]", "tests/test_log_levels.py::TestFilteringLogger::test_pickle[10]", "tests/test_log_levels.py::TestFilteringLogger::test_pos_args", "tests/test_log_levels.py::TestFilteringLogger::test_async_pos_args", "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[aexception-args0]", "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[ainfo-args1]", "tests/test_log_levels.py::TestFilteringLogger::test_async_contextvars_merged[alog-args2]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-11-23 09:09:11+00:00
mit
2,782
hynek__structlog-549
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dd3029..858080b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,11 +24,16 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - Official support for Python 3.12. [#515](https://github.com/hynek/structlog/issues/515) + - `structlog.processors.MaybeTimeStamper` that only adds a timestamp if there isn't one already. [#81](https://github.com/hynek/structlog/issues/81) + - `structlog.dev.ConsoleRenderer` now supports renamed timestamp keys using the *timestamp_key* parameter. [#541](https://github.com/hynek/structlog/issues/541) +- `structlog.dev.RichTracebackFormatter` that allows to configure the traceback formatting. + [#542](https://github.com/hynek/structlog/issues/542) + ### Fixed diff --git a/docs/api.rst b/docs/api.rst index 5286276..f58f50f 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -79,6 +79,7 @@ API Reference :members: get_default_level_styles .. autofunction:: plain_traceback +.. autoclass:: RichTracebackFormatter .. autofunction:: rich_traceback .. autofunction:: better_traceback diff --git a/docs/conf.py b/docs/conf.py index 8334f67..5948b03 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -160,4 +160,7 @@ linkcheck_ignore = [ # Twisted's trac tends to be slow linkcheck_timeout = 300 -intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "rich": ("https://rich.readthedocs.io/en/stable/", None), +} diff --git a/src/structlog/dev.py b/src/structlog/dev.py index c8d7387..1bc9bbf 100644 --- a/src/structlog/dev.py +++ b/src/structlog/dev.py @@ -11,11 +11,23 @@ See also the narrative documentation in `development`. from __future__ import annotations +import shutil import sys import warnings +from dataclasses import dataclass from io import StringIO -from typing import Any, Iterable, Protocol, TextIO, Type, Union +from types import ModuleType +from typing import ( + Any, + Iterable, + Literal, + Protocol, + Sequence, + TextIO, + Type, + Union, +) from ._frames import _format_exception from .processors import _figure_out_exc_info @@ -160,25 +172,78 @@ def plain_traceback(sio: TextIO, exc_info: ExcInfo) -> None: Used by default if neither Rich nor *better-exceptions* are present. - .. versionadded:: 21.2 + .. versionadded:: 21.2.0 """ sio.write("\n" + _format_exception(exc_info)) -def rich_traceback(sio: TextIO, exc_info: ExcInfo) -> None: +@dataclass +class RichTracebackFormatter: """ - Pretty-print *exc_info* to *sio* using the Rich package. + A Rich traceback renderer with the given options. - To be passed into `ConsoleRenderer`'s ``exception_formatter`` argument. + Pass an instance as `ConsoleRenderer`'s ``exception_formatter`` argument. - Used by default if Rich is installed. + See :class:`rich.traceback.Traceback` for details on the arguments. - .. versionadded:: 21.2 + If a *width* of -1 is passed, the terminal width is used. If the width + can't be determined, fall back to 80. + + .. versionadded:: 23.2.0 """ - sio.write("\n") - Console(file=sio, color_system="truecolor").print( - Traceback.from_exception(*exc_info, show_locals=True) - ) + + color_system: Literal[ + "auto", "standard", "256", "truecolor", "windows" + ] = "truecolor" + show_locals: bool = True + max_frames: int = 100 + theme: str | None = None + word_wrap: bool = False + extra_lines: int = 3 + width: int = 100 + indent_guides: bool = True + locals_max_length: int = 10 + locals_max_string: int = 80 + locals_hide_dunder: bool = True + locals_hide_sunder: bool = False + suppress: Sequence[str | ModuleType] = () + + def __call__(self, sio: TextIO, exc_info: ExcInfo) -> None: + if self.width == -1: + self.width, _ = shutil.get_terminal_size((80, 0)) + + sio.write("\n") + + Console(file=sio, color_system=self.color_system).print( + Traceback.from_exception( + *exc_info, + show_locals=self.show_locals, + max_frames=self.max_frames, + theme=self.theme, + word_wrap=self.word_wrap, + extra_lines=self.extra_lines, + width=self.width, + indent_guides=self.indent_guides, + locals_max_length=self.locals_max_length, + locals_max_string=self.locals_max_string, + locals_hide_dunder=self.locals_hide_dunder, + locals_hide_sunder=self.locals_hide_sunder, + suppress=self.suppress, + ) + ) + + +rich_traceback = RichTracebackFormatter() +""" +Pretty-print *exc_info* to *sio* using the Rich package. + +To be passed into `ConsoleRenderer`'s ``exception_formatter`` argument. + +This is a `RichTracebackFormatter` with default arguments and used by default +if Rich is installed. + +.. versionadded:: 21.2.0 +""" def better_traceback(sio: TextIO, exc_info: ExcInfo) -> None:
hynek/structlog
25c361c71763df0e7f39d0d36cca08ff4b46e924
diff --git a/tests/test_dev.py b/tests/test_dev.py index 2d84557..531e76d 100644 --- a/tests/test_dev.py +++ b/tests/test_dev.py @@ -7,6 +7,7 @@ import pickle import sys from io import StringIO +from unittest import mock import pytest @@ -560,20 +561,19 @@ class TestSetExcInfo: assert {"exc_info": True} == dev.set_exc_info(None, "exception", {}) [email protected](dev.rich is None, reason="Needs rich.") -class TestRichTraceback: [email protected](dev.rich is None, reason="Needs Rich.") +class TestRichTracebackFormatter: def test_default(self): """ If Rich is present, it's the default. """ assert dev.default_exception_formatter is dev.rich_traceback - def test_does_not_blow_up(self): + def test_does_not_blow_up(self, sio): """ We trust Rich to do the right thing, so we just exercise the function and check the first new line that we add manually is present. """ - sio = StringIO() try: 0 / 0 except ZeroDivisionError: @@ -581,6 +581,20 @@ class TestRichTraceback: assert sio.getvalue().startswith("\n") + def test_width_minus_one(self, sio): + """ + If width is -1, it's replaced by the terminal width on first use. + """ + rtf = dev.RichTracebackFormatter(width=-1) + + with mock.patch("shutil.get_terminal_size", return_value=(42, 0)): + try: + 0 / 0 + except ZeroDivisionError: + rtf(sio, sys.exc_info()) + + assert 42 == rtf.width + @pytest.mark.skipif( dev.better_exceptions is None, reason="Needs better-exceptions."
Allow passing arguments to Rich in structlog.dev.rich_traceback I'm trying to figure out how to turn off locals when printing out stack traces with the rich logger (but also with the JSONRenderer). Can't seem to find a way to do that in the documentation, aside from just extracting it from the final `dict` log record. Here's the the important bits of (still exploring things, some variables are undefined): ```python shared_processors = [ structlog.processors.TimeStamper(fmt="iso", utc=True), structlog.stdlib.add_log_level, structlog.contextvars.merge_contextvars, structlog.processors.StackInfoRenderer(), structlog.processors.UnicodeDecoder(), structlog.processors.CallsiteParameterAdder( parameters=[ CallsiteParameter.MODULE, CallsiteParameter.FUNC_NAME, CallsiteParameter.LINENO, CallsiteParameter.THREAD, CallsiteParameter.THREAD_NAME, ], ), ] # Here, we are prepping structlog to deal with logging from the stdlib structlog.configure( processors=shared_processors + [ structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.make_filtering_bound_logger(level), cache_logger_on_first_use=cache_logger, ) # These are processors that are shared for the formatter, used later in the root logger. shared_formatter_processors = [ structlog.stdlib.ProcessorFormatter.remove_processors_meta, ] # If we're connected to a tty-like device (like a user shell), or we've disabled json logging, render to the console. if sys.stderr.isatty() and json_disabled: processor_renderers = shared_formatter_processors + [ structlog.dev.ConsoleRenderer(), ] # Otherwise, use the json renderer. else: processor_renderers = shared_formatter_processors + [ structlog.processors.dict_tracebacks, structlog.processors.StackInfoRenderer(), structlog.processors.JSONRenderer(), ] formatter = structlog.stdlib.ProcessorFormatter( # These run ONLY on `logging` entries that do NOT originate within structlog. foreign_pre_chain=shared_processors, # These run on ALL entries after the pre_chain is done. processors=processor_renderers, ) # Make sure uncaught exceptions are formatted properly sys.excepthook = _log_uncaught_exceptions # Use OUR `ProcessorFormatter` to format all `logging` entries. handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(level) ``` Any help would be appreciated, thanks!
0.0
25c361c71763df0e7f39d0d36cca08ff4b46e924
[ "tests/test_dev.py::TestRichTracebackFormatter::test_width_minus_one" ]
[ "tests/test_dev.py::TestPad::test_normal", "tests/test_dev.py::TestPad::test_negative", "tests/test_dev.py::TestConsoleRenderer::test_plain", "tests/test_dev.py::TestConsoleRenderer::test_timestamp", "tests/test_dev.py::TestConsoleRenderer::test_event_stringified", "tests/test_dev.py::TestConsoleRenderer::test_event_renamed", "tests/test_dev.py::TestConsoleRenderer::test_timestamp_renamed", "tests/test_dev.py::TestConsoleRenderer::test_level", "tests/test_dev.py::TestConsoleRenderer::test_init_accepts_overriding_levels", "tests/test_dev.py::TestConsoleRenderer::test_logger_name", "tests/test_dev.py::TestConsoleRenderer::test_logger_name_name", "tests/test_dev.py::TestConsoleRenderer::test_key_values", "tests/test_dev.py::TestConsoleRenderer::test_key_values_unsorted", "tests/test_dev.py::TestConsoleRenderer::test_exception_rendered[True]", "tests/test_dev.py::TestConsoleRenderer::test_exception_rendered[False]", "tests/test_dev.py::TestConsoleRenderer::test_stack_info", "tests/test_dev.py::TestConsoleRenderer::test_exc_info_tuple", "tests/test_dev.py::TestConsoleRenderer::test_exc_info_bool", "tests/test_dev.py::TestConsoleRenderer::test_exc_info_exception", "tests/test_dev.py::TestConsoleRenderer::test_pad_event_param", "tests/test_dev.py::TestConsoleRenderer::test_everything[tuple]", "tests/test_dev.py::TestConsoleRenderer::test_everything[exception]", "tests/test_dev.py::TestConsoleRenderer::test_everything[False]", "tests/test_dev.py::TestConsoleRenderer::test_colorama_colors_false", "tests/test_dev.py::TestConsoleRenderer::test_colorama_force_colors", "tests/test_dev.py::TestConsoleRenderer::test_repr_native_str[True]", "tests/test_dev.py::TestConsoleRenderer::test_repr_native_str[False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[0-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[1-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[2-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[3-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[4-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[5-True-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[5-True-False]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[5-False-True]", "tests/test_dev.py::TestConsoleRenderer::test_pickle[5-False-False]", "tests/test_dev.py::TestConsoleRenderer::test_no_exception", "tests/test_dev.py::TestSetExcInfo::test_wrong_name", "tests/test_dev.py::TestSetExcInfo::test_already_set[False]", "tests/test_dev.py::TestSetExcInfo::test_already_set[None]", "tests/test_dev.py::TestSetExcInfo::test_already_set[ei2]", "tests/test_dev.py::TestSetExcInfo::test_set_it", "tests/test_dev.py::TestRichTracebackFormatter::test_default", "tests/test_dev.py::TestRichTracebackFormatter::test_does_not_blow_up" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-07 06:45:08+00:00
mit
2,783
hynek__structlog-550
diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a12c8f..7a0e35c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - `structlog.threadlocal.tmp_bind()` now also works with `BoundLoggerLazyProxy` (in other words: before anything is bound to a bound logger). +- stdlib: `ProcessorFormatter` can now be told to not render the log record message using `getMessage` and just `str(record.msg)` instead. + [#550](https://github.com/hynek/structlog/issues/550) + - stdlib: `structlog.stdlib.BoundLogger.exception()`'s handling of`LogRecord.exc_info` is now set consistent with `logging`. [#571](https://github.com/hynek/structlog/issues/571) [#572](https://github.com/hynek/structlog/issues/572) diff --git a/src/structlog/stdlib.py b/src/structlog/stdlib.py index 9e82035..5e05e9b 100644 --- a/src/structlog/stdlib.py +++ b/src/structlog/stdlib.py @@ -964,6 +964,10 @@ class ProcessorFormatter(logging.Formatter): This parameter exists for historic reasons. Please use *processors* instead. + use_get_message: + If True, use ``record.getMessage`` to get a fully rendered log + message, otherwise use ``str(record.msg)``. (default: True) + Raises: TypeError: If both or neither *processor* and *processors* are passed. @@ -976,6 +980,7 @@ class ProcessorFormatter(logging.Formatter): .. deprecated:: 21.3.0 *processor* (singular) in favor of *processors* (plural). Removal is not planned. + .. versionadded:: 23.3.0 *use_get_message* """ def __init__( @@ -987,6 +992,7 @@ class ProcessorFormatter(logging.Formatter): keep_stack_info: bool = False, logger: logging.Logger | None = None, pass_foreign_args: bool = False, + use_get_message: bool = True, *args: Any, **kwargs: Any, ) -> None: @@ -1011,6 +1017,7 @@ class ProcessorFormatter(logging.Formatter): self.keep_stack_info = keep_stack_info self.logger = logger self.pass_foreign_args = pass_foreign_args + self.use_get_message = use_get_message def format(self, record: logging.LogRecord) -> str: """ @@ -1043,7 +1050,9 @@ class ProcessorFormatter(logging.Formatter): logger = self.logger meth_name = record.levelname.lower() ed = { - "event": record.getMessage(), + "event": record.getMessage() + if self.use_get_message + else str(record.msg), "_record": record, "_from_structlog": False, }
hynek/structlog
6323d5fc54a5e5ff09eca7d8b912ab6ef9256992
diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index 626b1a7..569bbbd 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -1189,6 +1189,34 @@ class TestProcessorFormatter: assert not records + def test_use_get_message_false(self): + """ + If use_get_message_is False, the event is obtained using + str(record.msg) instead of calling record.getMessage. That means + positional formatting is not performed. + """ + event_dicts = [] + + def capture(_, __, ed): + event_dicts.append(ed.copy()) + + return str(ed) + + proc = ProcessorFormatter(processors=[capture], use_get_message=False) + + record = logging.LogRecord( + "foo", + logging.INFO, + "path.py", + 42, + "le msg: %s", + ("keep separate",), + None, + ) + + assert proc.format(record) + assert "le msg: %s" == event_dicts[0]["event"] + @pytest_asyncio.fixture(name="abl") async def _abl(cl):
ProcessorFormatter should be able to pass the message unformatted https://github.com/hynek/structlog/blob/f7145a6a815083a748ec2e41a1d66dd63ce6c411/src/structlog/stdlib.py#L1016 The problematic pipeline is logging -> ProcessorFormatter -> structlog -> Sentry. Currently ProcessorFormatter calls `getMessage` on the log record. This means that the formatted log message from `logging` becomes the "event" field in `structlog`. This causes duplicates if structlog is integrated with Sentry, which groups messages by the "event" field. If the "event" field wasn't formatted, the messages would get grouped correctly. There should be a flag on ProcessorFormatter that allows it to pass the log message unformatted, like `"event": str(record.msg),` ([`LogRecord.msg` can be anything supporting `__str__`](https://docs.python.org/3/library/logging.html#logging.LogRecord)). Passing positional args is already supported thanks to the `pass_foreign_args` flag.
0.0
6323d5fc54a5e5ff09eca7d8b912ab6ef9256992
[ "tests/test_stdlib.py::TestProcessorFormatter::test_use_get_message_false" ]
[ "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_name", "tests/test_stdlib.py::TestLoggerFactory::test_ignores_frames", "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_caller", "tests/test_stdlib.py::TestLoggerFactory::test_stack_info", "tests/test_stdlib.py::TestLoggerFactory::test_no_stack_info_by_default", "tests/test_stdlib.py::TestLoggerFactory::test_find_caller", "tests/test_stdlib.py::TestLoggerFactory::test_sets_correct_logger", "tests/test_stdlib.py::TestLoggerFactory::test_positional_argument_avoids_guessing", "tests/test_stdlib.py::TestFilterByLevel::test_filters_lower_levels", "tests/test_stdlib.py::TestFilterByLevel::test_passes_higher_levels", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[debug]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[info]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[warning]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[error]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[exception]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[critical]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_log", "tests/test_stdlib.py::TestBoundLogger::test_positional_args_proxied", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[name]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[level]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[parent]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[propagate]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[handlers]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[disabled]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[addHandler-method_args0]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[removeHandler-method_args1]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[hasHandlers-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[callHandlers-method_args3]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[handle-method_args4]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[setLevel-method_args5]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getEffectiveLevel-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[isEnabledFor-method_args7]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[findCaller-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[makeRecord-method_args9]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getChild-method_args10]", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info_override", "tests/test_stdlib.py::TestBoundLogger::test_proxies_bind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_new", "tests/test_stdlib.py::TestBoundLogger::test_proxies_unbind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_try_unbind", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[debug]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[info]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[warning]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[error]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[critical]", "tests/test_stdlib.py::TestBoundLogger::test_alog", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_true", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_explicit", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_tuple", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_dict", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_positional_args_retained", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_nop_no_args", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_args_removed_if_empty", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[critical-50]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[exception-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[error-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warn-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warning-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[info-20]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[debug-10]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[notset-0]", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_added", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_alias_normalized", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added_with_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow8-None]", "tests/test_stdlib.py::TestExtraAdder::test_no_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow8-None]", "tests/test_stdlib.py::TestRenderToLogKW::test_default", "tests/test_stdlib.py::TestRenderToLogKW::test_add_extra_event_dict", "tests/test_stdlib.py::TestRenderToLogKW::test_handles_special_kw", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_delegate", "tests/test_stdlib.py::TestProcessorFormatter::test_clears_args", "tests/test_stdlib.py::TestProcessorFormatter::test_pass_foreign_args_true_sets_positional_args_key", "tests/test_stdlib.py::TestProcessorFormatter::test_log_dict", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_add_logger_name", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_chain_can_pass_dictionaries_without_excepting", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_gets_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_sys_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_other_handlers_get_original_record", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_native", "tests/test_stdlib.py::TestProcessorFormatter::test_native_logger", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_filter_by_level", "tests/test_stdlib.py::TestProcessorFormatter::test_processor_and_processors", "tests/test_stdlib.py::TestProcessorFormatter::test_no_renderer", "tests/test_stdlib.py::TestProcessorFormatter::test_remove_processors_meta", "tests/test_stdlib.py::TestProcessorFormatter::test_non_string_message_warning", "tests/test_stdlib.py::TestProcessorFormatter::test_logrecord_exc_info", "tests/test_stdlib.py::TestAsyncBoundLogger::test_sync_bl", "tests/test_stdlib.py::TestAsyncBoundLogger::test_protocol", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[critical]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[exception]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[error]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warn]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warning]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[info]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[debug]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_log_method", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception_do_not_overwrite", "tests/test_stdlib.py::TestAsyncBoundLogger::test_bind_unbind", "tests/test_stdlib.py::TestAsyncBoundLogger::test_integration", "tests/test_stdlib.py::test_recreate_defaults[None]", "tests/test_stdlib.py::test_recreate_defaults[45]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-07 07:02:12+00:00
mit
2,784
hynek__structlog-572
diff --git a/CHANGELOG.md b/CHANGELOG.md index cbc966e..9a12c8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,10 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - `structlog.threadlocal.tmp_bind()` now also works with `BoundLoggerLazyProxy` (in other words: before anything is bound to a bound logger). +- stdlib: `structlog.stdlib.BoundLogger.exception()`'s handling of`LogRecord.exc_info` is now set consistent with `logging`. + [#571](https://github.com/hynek/structlog/issues/571) + [#572](https://github.com/hynek/structlog/issues/572) + ## [23.2.0](https://github.com/hynek/structlog/compare/23.1.0...23.2.0) - 2023-10-09 diff --git a/src/structlog/stdlib.py b/src/structlog/stdlib.py index 0cac035..9e82035 100644 --- a/src/structlog/stdlib.py +++ b/src/structlog/stdlib.py @@ -16,9 +16,10 @@ import contextvars import functools import logging import sys +import warnings from functools import partial -from typing import Any, Callable, Collection, Iterable, Sequence +from typing import Any, Callable, Collection, Dict, Iterable, Sequence, cast from . import _config from ._base import BoundLoggerBase @@ -27,7 +28,14 @@ from ._log_levels import _LEVEL_TO_NAME, _NAME_TO_LEVEL, add_log_level from .contextvars import _ASYNC_CALLING_STACK, merge_contextvars from .exceptions import DropEvent from .processors import StackInfoRenderer -from .typing import Context, EventDict, ExcInfo, Processor, WrappedLogger +from .typing import ( + Context, + EventDict, + ExcInfo, + Processor, + ProcessorReturnValue, + WrappedLogger, +) __all__ = [ @@ -209,12 +217,11 @@ class BoundLogger(BoundLoggerBase): self, event: str | None = None, *args: Any, **kw: Any ) -> Any: """ - Process event and call `logging.Logger.error` with the result, - after setting ``exc_info`` to `True`. + Process event and call `logging.Logger.exception` with the result, + after setting ``exc_info`` to `True` if it's not already set. """ kw.setdefault("exc_info", True) - - return self.error(event, *args, **kw) + return self._proxy_to_logger("exception", event, *args, **kw) def log( self, level: int, event: str | None = None, *args: Any, **kw: Any @@ -1019,16 +1026,17 @@ class ProcessorFormatter(logging.Formatter): logger = getattr(record, "_logger", _SENTINEL) meth_name = getattr(record, "_name", "__structlog_sentinel__") + ed: ProcessorReturnValue if logger is not _SENTINEL and meth_name != "__structlog_sentinel__": # Both attached by wrap_for_formatter if self.logger is not None: logger = self.logger - meth_name = record._name # type: ignore[attr-defined] + meth_name = cast(str, record._name) # type:ignore[attr-defined] # We need to copy because it's possible that the same record gets - # processed by multiple logging formatters. LogRecord.getMessage + # processed by multiple logging formatters. LogRecord.getMessage # would transform our dict into a str. - ed = record.msg.copy() # type: ignore[union-attr] + ed = cast(Dict[str, Any], record.msg).copy() ed["_record"] = record ed["_from_structlog"] = True else: @@ -1045,27 +1053,38 @@ class ProcessorFormatter(logging.Formatter): record.args = () - # Add stack-related attributes to event_dict and unset them - # on the record copy so that the base implementation wouldn't - # append stacktraces to the output. + # Add stack-related attributes to the event dict if record.exc_info: ed["exc_info"] = record.exc_info if record.stack_info: ed["stack_info"] = record.stack_info - if not self.keep_exc_info: - record.exc_text = None - record.exc_info = None - if not self.keep_stack_info: - record.stack_info = None - # Non-structlog allows to run through a chain to prepare it for the # final processor (e.g. adding timestamps and log levels). for proc in self.foreign_pre_chain or (): - ed = proc(logger, meth_name, ed) + ed = cast(EventDict, proc(logger, meth_name, ed)) + + # If required, unset stack-related attributes on the record copy so + # that the base implementation doesn't append stacktraces to the + # output. + if not self.keep_exc_info: + record.exc_text = None + record.exc_info = None + if not self.keep_stack_info: + record.stack_info = None for p in self.processors: - ed = p(logger, meth_name, ed) + ed = p(logger, meth_name, cast(EventDict, ed)) + + if not isinstance(ed, str): + warnings.warn( + "The last processor in ProcessorFormatter.processors must " + f"return a string, but {self.processors[-1]} returned a " + f"{type(ed)} instead.", + category=RuntimeWarning, + stacklevel=1, + ) + ed = cast(str, ed) record.msg = ed diff --git a/src/structlog/typing.py b/src/structlog/typing.py index 66f6a7e..c258e11 100644 --- a/src/structlog/typing.py +++ b/src/structlog/typing.py @@ -60,11 +60,15 @@ copy itself. .. versionadded:: 20.2.0 """ -Processor = Callable[ - [WrappedLogger, str, EventDict], - Union[Mapping[str, Any], str, bytes, bytearray, Tuple[Any, ...]], +ProcessorReturnValue = Union[ + Mapping[str, Any], str, bytes, bytearray, Tuple[Any, ...] ] """ +A value returned by a processor. +""" + +Processor = Callable[[WrappedLogger, str, EventDict], ProcessorReturnValue] +""" A callable that is part of the processor chain. See :doc:`processors`.
hynek/structlog
8d3eeb1d9a7f7d5e20d515df45fa7779223bbbba
diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index 4e3c9f5..626b1a7 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -12,7 +12,7 @@ import os import sys from io import StringIO -from typing import Any, Callable, Collection +from typing import Any, Callable, Collection, Dict import pytest import pytest_asyncio @@ -193,7 +193,8 @@ class TestFilterByLevel: class TestBoundLogger: @pytest.mark.parametrize( - ("method_name"), ["debug", "info", "warning", "error", "critical"] + ("method_name"), + ["debug", "info", "warning", "error", "exception", "critical"], ) def test_proxies_to_correct_method(self, method_name): """ @@ -203,14 +204,6 @@ class TestBoundLogger: assert method_name == getattr(bl, method_name)("event") - def test_proxies_exception(self): - """ - BoundLogger.exception is proxied to Logger.error. - """ - bl = BoundLogger(ReturnLogger(), [return_method_name], {}) - - assert "error" == bl.exception("event") - def test_proxies_log(self): """ BoundLogger.exception.log() is proxied to the appropriate method. @@ -1123,6 +1116,79 @@ class TestProcessorFormatter: {"foo": "bar", "_record": "foo", "_from_structlog": True}, ) + def test_non_string_message_warning(self): + """ + A warning is raised if the last processor in + ProcessorFormatter.processors doesn't return a string. + """ + configure_logging(None) + logger = logging.getLogger() + + formatter = ProcessorFormatter( + processors=[lambda *args, **kwargs: {"foo": "bar"}], + ) + logger.handlers[0].setFormatter(formatter) + + with pytest.warns( + RuntimeWarning, + match="The last processor in ProcessorFormatter.processors must return a string", + ): + logger.info("baz") + + def test_logrecord_exc_info(self): + """ + LogRecord.exc_info is set consistently for structlog and non-structlog + log records. + """ + configure_logging(None) + + # This doesn't test ProcessorFormatter itself directly, but it's + # relevant to setups where ProcessorFormatter is used, i.e. where + # handlers will receive LogRecord objects that come from both structlog + # and non-structlog loggers. + + records: Dict[ # noqa: UP006 - dict isn't generic until Python 3.9 + str, logging.LogRecord + ] = {} + + class DummyHandler(logging.Handler): + def emit(self, record): + # Don't do anything; just store the record in the records dict + # by its message, so we can assert things about it. + if isinstance(record.msg, dict): + records[record.msg["event"]] = record + else: + records[record.msg] = record + + stdlib_logger = logging.getLogger() + structlog_logger = get_logger() + + # It doesn't matter which logger we add the handler to here. + stdlib_logger.addHandler(DummyHandler()) + + try: + raise Exception("foo") + except Exception: + stdlib_logger.exception("bar") + structlog_logger.exception("baz") + + stdlib_record = records.pop("bar") + + assert "bar" == stdlib_record.msg + assert stdlib_record.exc_info + assert Exception is stdlib_record.exc_info[0] + assert ("foo",) == stdlib_record.exc_info[1].args + + structlog_record = records.pop("baz") + + assert "baz" == structlog_record.msg["event"] + assert True is structlog_record.msg["exc_info"] + assert structlog_record.exc_info + assert Exception is structlog_record.exc_info[0] + assert ("foo",) == structlog_record.exc_info[1].args + + assert not records + @pytest_asyncio.fixture(name="abl") async def _abl(cl): @@ -1154,7 +1220,7 @@ class TestAsyncBoundLogger: """ await getattr(abl.bind(foo="bar"), stdlib_log_method)("42") - aliases = {"exception": "error", "warn": "warning"} + aliases = {"warn": "warning"} alias = aliases.get(stdlib_log_method) expect = alias if alias else stdlib_log_method
exc_info is not resolved properly when calling BoundLogger.exception I have a slightly unusual setup that I should explain first. I'm using the maximalist approach of routing all of my structlog and stdlib logging through `ProcessorFormatter` as per [the docs](https://www.structlog.org/en/stable/standard-library.html#rendering-using-structlog-based-formatters-within-logging), but we're also sending logs at `ERROR` and above to Rollbar using `pyrollbar` and its [RollbarHandler](https://github.com/rollbar/pyrollbar/blob/master/rollbar/logger.py). Unfortunately, `RollbarHandler` on its own doesn't play nicely with that approach because it doesn't call `self.format()` anywhere meaning we don't have anywhere to plug in `ProcessorFormatter`. So, we have a custom subclass (called `StructlogRollbarHandler`) that does similar things to `ProcessorFormatter.format()` in its `emit()` method before calling the superclass `emit()` method to send the payload to Rollbar. A notable exception to that is using the raw `record.msg` rather than `record.getMessage()` as per #520. That means that it's really important for us that all our `LogRecord` objects, whether from `structlog` or stdlib loggers, look the same when they get to the `Handler.emit(record)` stage of the pipeline, because we can't rely on `ProcessorFormatter` or any structlog renderers patching things up for us. This is mostly working fine, apart from calls to `BoundLogger.exception`. When we call `BoundLogger.exception`, the `LogRecord` that gets to our `StructlogRollbarHandler.emit(record)` method has an event dict for its `record.msg` attribute, as you'd expect, and that dict has `"exc_info"` in it, but the `record.exc_info` attribute itself is `None`! Obviously this isn't the case for stdlib-originated records. Having spent a while debugging, this seems to be because `BoundLogger.exception` calls `self.error` rather than doing something like `self._proxy_to_logger("exception", event, *args, **{"exc_info": True, **kw})`. That means that the wrapped `logging.Logger` thinks this was a `logger.error` call and not a `logger.exception` call, which changes the behaviour in a really subtle way. All of our `LogRecord` objects from `structlog` go through `ProcessorFormatter.wrap_for_formatter`, which puts `exc_info` in the `record.msg` event dict and strips it out of the kwargs. Then, because of the aforementioned change of the effective log method from `.exception` to `.error`, the stdlib logger doesn't set this back to `True` for us and then `Logger._log` doesn't call `sys.exc_info()` for us. - [logging.Logger.error](https://github.com/python/cpython/blob/4fe22c73770fe86b01ef7a4f1f38e7e925c0e090/Lib/logging/__init__.py#L1525) - [logging.Logger.exception](https://github.com/python/cpython/blob/4fe22c73770fe86b01ef7a4f1f38e7e925c0e090/Lib/logging/__init__.py#L1537) I'm honestly not sure whether this is a bug in my code or `structlog`. I accept that using `ProcessorFormatter` alongside other formatters isn't really documented/supported, but it's really close to working perfectly apart from this! Sorry for writing such a long issue, thank you for an amazing library! :heart:
0.0
8d3eeb1d9a7f7d5e20d515df45fa7779223bbbba
[ "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[exception]", "tests/test_stdlib.py::TestProcessorFormatter::test_non_string_message_warning", "tests/test_stdlib.py::TestProcessorFormatter::test_logrecord_exc_info", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[exception]" ]
[ "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_name", "tests/test_stdlib.py::TestLoggerFactory::test_ignores_frames", "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_caller", "tests/test_stdlib.py::TestLoggerFactory::test_stack_info", "tests/test_stdlib.py::TestLoggerFactory::test_no_stack_info_by_default", "tests/test_stdlib.py::TestLoggerFactory::test_find_caller", "tests/test_stdlib.py::TestLoggerFactory::test_sets_correct_logger", "tests/test_stdlib.py::TestLoggerFactory::test_positional_argument_avoids_guessing", "tests/test_stdlib.py::TestFilterByLevel::test_filters_lower_levels", "tests/test_stdlib.py::TestFilterByLevel::test_passes_higher_levels", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[debug]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[info]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[warning]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[error]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[critical]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_log", "tests/test_stdlib.py::TestBoundLogger::test_positional_args_proxied", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[name]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[level]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[parent]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[propagate]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[handlers]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[disabled]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[addHandler-method_args0]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[removeHandler-method_args1]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[hasHandlers-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[callHandlers-method_args3]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[handle-method_args4]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[setLevel-method_args5]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getEffectiveLevel-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[isEnabledFor-method_args7]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[findCaller-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[makeRecord-method_args9]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getChild-method_args10]", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info_override", "tests/test_stdlib.py::TestBoundLogger::test_proxies_bind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_new", "tests/test_stdlib.py::TestBoundLogger::test_proxies_unbind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_try_unbind", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[debug]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[info]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[warning]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[error]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[critical]", "tests/test_stdlib.py::TestBoundLogger::test_alog", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_true", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_explicit", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_tuple", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_dict", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_positional_args_retained", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_nop_no_args", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_args_removed_if_empty", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[critical-50]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[exception-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[error-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warn-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warning-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[info-20]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[debug-10]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[notset-0]", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_added", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_alias_normalized", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added_with_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow8-None]", "tests/test_stdlib.py::TestExtraAdder::test_no_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow8-None]", "tests/test_stdlib.py::TestRenderToLogKW::test_default", "tests/test_stdlib.py::TestRenderToLogKW::test_add_extra_event_dict", "tests/test_stdlib.py::TestRenderToLogKW::test_handles_special_kw", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_delegate", "tests/test_stdlib.py::TestProcessorFormatter::test_clears_args", "tests/test_stdlib.py::TestProcessorFormatter::test_pass_foreign_args_true_sets_positional_args_key", "tests/test_stdlib.py::TestProcessorFormatter::test_log_dict", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_add_logger_name", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_chain_can_pass_dictionaries_without_excepting", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_gets_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_sys_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_other_handlers_get_original_record", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_native", "tests/test_stdlib.py::TestProcessorFormatter::test_native_logger", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_filter_by_level", "tests/test_stdlib.py::TestProcessorFormatter::test_processor_and_processors", "tests/test_stdlib.py::TestProcessorFormatter::test_no_renderer", "tests/test_stdlib.py::TestProcessorFormatter::test_remove_processors_meta", "tests/test_stdlib.py::TestAsyncBoundLogger::test_sync_bl", "tests/test_stdlib.py::TestAsyncBoundLogger::test_protocol", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[critical]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[error]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warn]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warning]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[info]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[debug]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_log_method", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception_do_not_overwrite", "tests/test_stdlib.py::TestAsyncBoundLogger::test_bind_unbind", "tests/test_stdlib.py::TestAsyncBoundLogger::test_integration", "tests/test_stdlib.py::test_recreate_defaults[None]", "tests/test_stdlib.py::test_recreate_defaults[45]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-11-03 19:09:15+00:00
mit
2,785
hynek__structlog-586
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dd033e..85fb3e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,10 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - The lazy logger proxy returned by `structlog.get_logger()` now returns its initial values when asked for context. When asked for context before binding for the first time, it returned an empty dictionary in 23.3.0. +- The displayed level name when using `structlog.stdlib.BoundLogger.exception()` is `"error"` instead of `"exception"`. + Fixes regression in 23.3.0. + [#584](https://github.com/hynek/structlog/issues/584) + - Don't ignore the `width` argument of `RichTracebackFormatter`. [#587](https://github.com/hynek/structlog/issues/587) diff --git a/src/structlog/_log_levels.py b/src/structlog/_log_levels.py index bb7e67b..df1e81a 100644 --- a/src/structlog/_log_levels.py +++ b/src/structlog/_log_levels.py @@ -60,10 +60,15 @@ def add_log_level( .. versionchanged:: 20.2.0 Importable from `structlog.processors` (additionally to `structlog.stdlib`). + .. versionchanged:: 24.1.0 + Added mapping from "exception" to "error" """ if method_name == "warn": # The stdlib has an alias method_name = "warning" + elif method_name == "exception": + # exception("") method is the same as error("", exc_info=True) + method_name = "error" event_dict["level"] = method_name
hynek/structlog
ac37281c66efe82f4dfc8f812ab91f391548fd6b
diff --git a/tests/test_stdlib.py b/tests/test_stdlib.py index f1ae444..1c690f1 100644 --- a/tests/test_stdlib.py +++ b/tests/test_stdlib.py @@ -488,13 +488,16 @@ class TestAddLogLevel: assert "error" == event_dict["level"] - def test_log_level_alias_normalized(self): + @pytest.mark.parametrize( + ("alias", "normalized"), [("warn", "warning"), ("exception", "error")] + ) + def test_log_level_alias_normalized(self, alias, normalized): """ The normalized name of the log level is added to the event dict. """ - event_dict = add_log_level(None, "warn", {}) + event_dict = add_log_level(None, alias, {}) - assert "warning" == event_dict["level"] + assert normalized == event_dict["level"] @pytest.fixture(name="make_log_record")
"exception" is a possible log level from processors.add_log_level since 23.3.0 structlog.processors.add_log_level used to report the level of "exception" events as "error", but since 23.3.0 with certain configurations it's possible to get "exception" instead: ```sh $ pip3 install structlog==23.2.0 && python3 main.py {'exc_info': True, 'event': 'test', '_record': <LogRecord: root, 40, 223, "{...}">, '_from_structlog': True, 'level': 'error'} $ pip3 install structlog==23.3.0 && python3 main.py {'exc_info': True, 'event': 'test', '_record': <LogRecord: root, 40, 217, "{...}">, '_from_structlog': True, 'level': 'exception'} ``` I wonder if this is intentional, since it's not very clearly listed in the changelog. There is "stdlib: structlog.stdlib.BoundLogger.exception()'s handling ofLogRecord.exc_info is now set consistent with logging." but I don't think this change falls into that category. It seems to be reliant on `wrapper_class=structlog.stdlib.BoundLogger`. Example code: ```python import logging.config import structlog structlog.configure( processors=[ structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, ) logging_config = { "version": 1, "formatters": { "json": { "()": structlog.stdlib.ProcessorFormatter, "processors": [ structlog.processors.add_log_level, ], } }, "handlers": { "json": { "class": "logging.StreamHandler", "formatter": "json", }, }, "root": { "handlers": ["json"], }, } logging.config.dictConfig(logging_config) ```
0.0
ac37281c66efe82f4dfc8f812ab91f391548fd6b
[ "tests/test_stdlib.py::TestAddLogLevel::test_log_level_alias_normalized[exception-error]" ]
[ "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_name", "tests/test_stdlib.py::TestLoggerFactory::test_ignores_frames", "tests/test_stdlib.py::TestLoggerFactory::test_deduces_correct_caller", "tests/test_stdlib.py::TestLoggerFactory::test_stack_info", "tests/test_stdlib.py::TestLoggerFactory::test_no_stack_info_by_default", "tests/test_stdlib.py::TestLoggerFactory::test_find_caller", "tests/test_stdlib.py::TestLoggerFactory::test_sets_correct_logger", "tests/test_stdlib.py::TestLoggerFactory::test_positional_argument_avoids_guessing", "tests/test_stdlib.py::TestFilterByLevel::test_filters_lower_levels", "tests/test_stdlib.py::TestFilterByLevel::test_passes_higher_levels", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[debug]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[info]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[warning]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[error]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[exception]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_to_correct_method[critical]", "tests/test_stdlib.py::TestBoundLogger::test_proxies_log", "tests/test_stdlib.py::TestBoundLogger::test_positional_args_proxied", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[name]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[level]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[parent]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[propagate]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[handlers]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_attributes[disabled]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[addHandler-method_args0]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[removeHandler-method_args1]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[hasHandlers-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[callHandlers-method_args3]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[handle-method_args4]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[setLevel-method_args5]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getEffectiveLevel-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[isEnabledFor-method_args7]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[findCaller-None]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[makeRecord-method_args9]", "tests/test_stdlib.py::TestBoundLogger::test_stdlib_passthrough_methods[getChild-method_args10]", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info", "tests/test_stdlib.py::TestBoundLogger::test_exception_exc_info_override", "tests/test_stdlib.py::TestBoundLogger::test_proxies_bind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_new", "tests/test_stdlib.py::TestBoundLogger::test_proxies_unbind", "tests/test_stdlib.py::TestBoundLogger::test_proxies_try_unbind", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[debug]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[info]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[warning]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[error]", "tests/test_stdlib.py::TestBoundLogger::test_async_log_methods[critical]", "tests/test_stdlib.py::TestBoundLogger::test_alog", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_true", "tests/test_stdlib.py::TestBoundLogger::test_aexception_exc_info_explicit", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_tuple", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_formats_dict", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_positional_args_retained", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_nop_no_args", "tests/test_stdlib.py::TestPositionalArgumentsFormatter::test_args_removed_if_empty", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[critical-50]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[exception-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[error-40]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warn-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[warning-30]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[info-20]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[debug-10]", "tests/test_stdlib.py::TestAddLogLevelNumber::test_log_level_number_added[notset-0]", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_added", "tests/test_stdlib.py::TestAddLogLevel::test_log_level_alias_normalized[warn-warning]", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added", "tests/test_stdlib.py::TestAddLoggerName::test_logger_name_added_with_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra[allow8-None]", "tests/test_stdlib.py::TestExtraAdder::test_no_record", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[None-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow1-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow2-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow3-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow4-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow5-None]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow6-misses6]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow7-misses7]", "tests/test_stdlib.py::TestExtraAdder::test_add_extra_e2e[allow8-None]", "tests/test_stdlib.py::TestRenderToLogKW::test_default", "tests/test_stdlib.py::TestRenderToLogKW::test_add_extra_event_dict", "tests/test_stdlib.py::TestRenderToLogKW::test_handles_special_kw", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_delegate", "tests/test_stdlib.py::TestProcessorFormatter::test_clears_args", "tests/test_stdlib.py::TestProcessorFormatter::test_pass_foreign_args_true_sets_positional_args_key", "tests/test_stdlib.py::TestProcessorFormatter::test_log_dict", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_add_logger_name", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_chain_can_pass_dictionaries_without_excepting", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_gets_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_sys_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_other_handlers_get_original_record", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_exc_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[True]", "tests/test_stdlib.py::TestProcessorFormatter::test_formatter_unsets_stack_info[False]", "tests/test_stdlib.py::TestProcessorFormatter::test_native", "tests/test_stdlib.py::TestProcessorFormatter::test_native_logger", "tests/test_stdlib.py::TestProcessorFormatter::test_foreign_pre_chain_filter_by_level", "tests/test_stdlib.py::TestProcessorFormatter::test_processor_and_processors", "tests/test_stdlib.py::TestProcessorFormatter::test_no_renderer", "tests/test_stdlib.py::TestProcessorFormatter::test_remove_processors_meta", "tests/test_stdlib.py::TestProcessorFormatter::test_non_string_message_warning", "tests/test_stdlib.py::TestProcessorFormatter::test_logrecord_exc_info", "tests/test_stdlib.py::TestProcessorFormatter::test_use_get_message_false", "tests/test_stdlib.py::TestAsyncBoundLogger::test_sync_bl", "tests/test_stdlib.py::TestAsyncBoundLogger::test_protocol", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[critical]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[exception]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[error]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warn]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[warning]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[info]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_correct_levels[debug]", "tests/test_stdlib.py::TestAsyncBoundLogger::test_log_method", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception", "tests/test_stdlib.py::TestAsyncBoundLogger::test_exception_do_not_overwrite", "tests/test_stdlib.py::TestAsyncBoundLogger::test_bind_unbind", "tests/test_stdlib.py::TestAsyncBoundLogger::test_integration", "tests/test_stdlib.py::test_recreate_defaults[None]", "tests/test_stdlib.py::test_recreate_defaults[45]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-01-03 18:12:35+00:00
mit
2,786
hynek__structlog-594
diff --git a/CHANGELOG.md b/CHANGELOG.md index fd810de..9d3b8d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,9 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - `structlog.processors.LogfmtRenderer` now escapes newlines. [#592](https://github.com/hynek/structlog/pull/592) +- `structlog.processors.LogfmtRenderer` now escapes backslashes and double quotes. + [#594](https://github.com/hynek/structlog/pull/594) + ## [24.1.0](https://github.com/hynek/structlog/compare/23.3.0...24.1.0) - 2024-01-08 diff --git a/src/structlog/processors.py b/src/structlog/processors.py index ba87eb3..e597eae 100644 --- a/src/structlog/processors.py +++ b/src/structlog/processors.py @@ -170,9 +170,16 @@ class LogfmtRenderer: continue value = "true" if value else "false" - value = f"{value}".replace('"', '\\"').replace("\n", "\\n") + value = str(value) + backslashes_need_escaping = ( + " " in value or "=" in value or '"' in value + ) + if backslashes_need_escaping and "\\" in value: + value = value.replace("\\", "\\\\") + + value = value.replace('"', '\\"').replace("\n", "\\n") - if " " in value or "=" in value: + if backslashes_need_escaping: value = f'"{value}"' elements.append(f"{key}={value}")
hynek/structlog
db834f532618e28d3fb68349a6d76af8493de541
diff --git a/tests/processors/test_renderers.py b/tests/processors/test_renderers.py index b3d6e51..8f225c8 100644 --- a/tests/processors/test_renderers.py +++ b/tests/processors/test_renderers.py @@ -275,6 +275,33 @@ class TestLogfmtRenderer: assert r"with_newline=some\nvalue" == rv + @pytest.mark.parametrize( + ("raw", "escaped"), + [ + # Slash by itself does not need to be escaped. + (r"a\slash", r"a\slash"), + # A quote requires quoting, and escaping the quote. + ('a"quote', r'"a\"quote"'), + # If anything triggers quoting of the string, then the slash must + # be escaped. + ( + r'a\slash with space or a"quote', + r'"a\\slash with space or a\"quote"', + ), + ( + r"I want to render this \"string\" with logfmtrenderer", + r'"I want to render this \\\"string\\\" with logfmtrenderer"', + ), + ], + ) + def test_escaping(self, raw, escaped): + """ + Backslashes and quotes are escaped. + """ + rv = LogfmtRenderer()(None, None, {"key": raw}) + + assert f"key={escaped}" == rv + class TestJSONRenderer: def test_renders_json(self, event_dict):
LogfmtRenderer has a bug with escaped double quotes In the code of LogFmtRenderer there is: `value = f"{value}".replace('"', '\\"')` However if you are trying to render an escaped double quote like `"I want to render this \"string\" with logfmtrenderer"` it ends up rendering it as `\"I want to render this \\"string\\" with logfmtrenderer\"` `\\"` is wrong and won't be parsed correctly by a logfmtparser.
0.0
db834f532618e28d3fb68349a6d76af8493de541
[ "tests/processors/test_renderers.py::TestLogfmtRenderer::test_escaping[a\"quote-\"a\\\\\"quote\"]", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_escaping[a\\\\slash", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_escaping[I" ]
[ "tests/processors/test_renderers.py::TestKeyValueRenderer::test_sort_keys", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_order_complete", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_order_missing", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_order_missing_dropped", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_order_extra", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_order_sorted_missing_dropped", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_random_order", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_repr_native_str[True]", "tests/processors/test_renderers.py::TestKeyValueRenderer::test_repr_native_str[False]", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_sort_keys", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_order_complete", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_order_missing", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_order_missing_dropped", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_order_extra", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_order_sorted_missing_dropped", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_random_order", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_empty_event_dict", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_bool_as_flag", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_reference_format", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_equal_sign_or_space_in_value", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_invalid_key", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_newline_in_value", "tests/processors/test_renderers.py::TestLogfmtRenderer::test_escaping[a\\\\slash-a\\\\slash]", "tests/processors/test_renderers.py::TestJSONRenderer::test_renders_json", "tests/processors/test_renderers.py::TestJSONRenderer::test_FallbackEncoder_handles_ThreadLocalDictWrapped_dicts", "tests/processors/test_renderers.py::TestJSONRenderer::test_FallbackEncoder_falls_back", "tests/processors/test_renderers.py::TestJSONRenderer::test_serializer", "tests/processors/test_renderers.py::TestJSONRenderer::test_custom_fallback", "tests/processors/test_renderers.py::TestJSONRenderer::test_simplejson", "tests/processors/test_renderers.py::TestTimeStamper::test_disallows_non_utc_unix_timestamps", "tests/processors/test_renderers.py::TestTimeStamper::test_inserts_utc_unix_timestamp_by_default", "tests/processors/test_renderers.py::TestTimeStamper::test_local", "tests/processors/test_renderers.py::TestTimeStamper::test_formats", "tests/processors/test_renderers.py::TestTimeStamper::test_adds_Z_to_iso", "tests/processors/test_renderers.py::TestTimeStamper::test_key_can_be_specified", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[0-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[1-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[2-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[3-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[4-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-None-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-None-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-None-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-other-key-True-None]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-other-key-True-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_pickle[5-other-key-False-%Y]", "tests/processors/test_renderers.py::TestTimeStamper::test_apply_freezegun_after_instantiation", "tests/processors/test_renderers.py::TestMaybeTimeStamper::test_overwrite", "tests/processors/test_renderers.py::TestMaybeTimeStamper::test_none", "tests/processors/test_renderers.py::TestFormatExcInfo::test_custom_formatter", "tests/processors/test_renderers.py::TestFormatExcInfo::test_nop[False]", "tests/processors/test_renderers.py::TestFormatExcInfo::test_nop[None]", "tests/processors/test_renderers.py::TestFormatExcInfo::test_nop[]", "tests/processors/test_renderers.py::TestFormatExcInfo::test_nop_missing", "tests/processors/test_renderers.py::TestFormatExcInfo::test_formats_tuple", "tests/processors/test_renderers.py::TestFormatExcInfo::test_gets_exc_info_on_bool", "tests/processors/test_renderers.py::TestFormatExcInfo::test_exception", "tests/processors/test_renderers.py::TestFormatExcInfo::test_exception_without_traceback", "tests/processors/test_renderers.py::TestFormatExcInfo::test_format_exception", "tests/processors/test_renderers.py::TestFormatExcInfo::test_no_exception[True]", "tests/processors/test_renderers.py::TestFormatExcInfo::test_no_exception[ei1]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-02-05 08:03:20+00:00
mit
2,787
hynek__structlog-603
diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f8df4..cf107bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/ - It is now possible to disable log level-padding in `structlog.dev.LogLevelColumnFormatter` and `structlog.dev.ConsoleRenderer`. [#599](https://github.com/hynek/structlog/pull/599) +- The `structlog.processors.CallsiteParameterAdder` can now be pickled. + [#603](https://github.com/hynek/structlog/pull/603) ### Changed diff --git a/src/structlog/processors.py b/src/structlog/processors.py index e597eae..ae873ce 100644 --- a/src/structlog/processors.py +++ b/src/structlog/processors.py @@ -724,6 +724,46 @@ class CallsiteParameter(enum.Enum): PROCESS_NAME = "process_name" +def _get_callsite_pathname(module: str, frame_info: inspect.Traceback) -> Any: + return frame_info.filename + + +def _get_callsite_filename(module: str, frame_info: inspect.Traceback) -> Any: + return os.path.basename(frame_info.filename) + + +def _get_callsite_module(module: str, frame_info: inspect.Traceback) -> Any: + return os.path.splitext(os.path.basename(frame_info.filename))[0] + + +def _get_callsite_func_name(module: str, frame_info: inspect.Traceback) -> Any: + return frame_info.function + + +def _get_callsite_lineno(module: str, frame_info: inspect.Traceback) -> Any: + return frame_info.lineno + + +def _get_callsite_thread(module: str, frame_info: inspect.Traceback) -> Any: + return threading.get_ident() + + +def _get_callsite_thread_name( + module: str, frame_info: inspect.Traceback +) -> Any: + return threading.current_thread().name + + +def _get_callsite_process(module: str, frame_info: inspect.Traceback) -> Any: + return os.getpid() + + +def _get_callsite_process_name( + module: str, frame_info: inspect.Traceback +) -> Any: + return get_processname() + + class CallsiteParameterAdder: """ Adds parameters of the callsite that an event dictionary originated from to @@ -767,33 +807,15 @@ class CallsiteParameterAdder: _handlers: ClassVar[ dict[CallsiteParameter, Callable[[str, inspect.Traceback], Any]] ] = { - CallsiteParameter.PATHNAME: ( - lambda module, frame_info: frame_info.filename - ), - CallsiteParameter.FILENAME: ( - lambda module, frame_info: os.path.basename(frame_info.filename) - ), - CallsiteParameter.MODULE: ( - lambda module, frame_info: os.path.splitext( - os.path.basename(frame_info.filename) - )[0] - ), - CallsiteParameter.FUNC_NAME: ( - lambda module, frame_info: frame_info.function - ), - CallsiteParameter.LINENO: ( - lambda module, frame_info: frame_info.lineno - ), - CallsiteParameter.THREAD: ( - lambda module, frame_info: threading.get_ident() - ), - CallsiteParameter.THREAD_NAME: ( - lambda module, frame_info: threading.current_thread().name - ), - CallsiteParameter.PROCESS: (lambda module, frame_info: os.getpid()), - CallsiteParameter.PROCESS_NAME: ( - lambda module, frame_info: get_processname() - ), + CallsiteParameter.PATHNAME: _get_callsite_pathname, + CallsiteParameter.FILENAME: _get_callsite_filename, + CallsiteParameter.MODULE: _get_callsite_module, + CallsiteParameter.FUNC_NAME: _get_callsite_func_name, + CallsiteParameter.LINENO: _get_callsite_lineno, + CallsiteParameter.THREAD: _get_callsite_thread, + CallsiteParameter.THREAD_NAME: _get_callsite_thread_name, + CallsiteParameter.PROCESS: _get_callsite_process, + CallsiteParameter.PROCESS_NAME: _get_callsite_process_name, } _record_attribute_map: ClassVar[dict[CallsiteParameter, str]] = { CallsiteParameter.PATHNAME: "pathname",
hynek/structlog
f0c7e8c71eeb504829218b434bfb7774884bec5c
diff --git a/tests/processors/test_processors.py b/tests/processors/test_processors.py index 865c1f7..cec0647 100644 --- a/tests/processors/test_processors.py +++ b/tests/processors/test_processors.py @@ -11,6 +11,7 @@ import itertools import json import logging import os +import pickle import sys import threading @@ -492,6 +493,14 @@ class TestCallsiteParameterAdder: assert expected == actual + def test_pickeable_callsite_parameter_adder(self) -> None: + """ + An instance of ``CallsiteParameterAdder`` can be pickled. This + functionality may be used to propagate structlog configurations to + subprocesses. + """ + pickle.dumps(CallsiteParameterAdder()) + @classmethod def make_processor( cls,
`CallsiteParameterAdder` not pickleable I am developing an application where I bind a collection of data to a logger and ultimately pass that logger into subprocess. For my application, it's desired to have call stack information from the [`CallsiteParameterAdder`](https://github.com/hynek/structlog/blob/186d2eaf7a1d78cba940bd3e99277a538894a6f2/src/structlog/processors.py#L727-L863) ; however, I noticed that the serialization failed when passing a logger with this processor through the pipe (b/c of the lambda functions) The following implementation works well; however, it would be nice to have native support or an example in the docs of how to make it pickleable (please disregard if this already exists and I just missed it). ``` def _pathname(module, frame_info) -> Any: return frame_info.filename def _filename(module, frame_info) -> Any: return os.path.basename(frame_info.filename) def _module(module, frame_info) -> Any: return os.path.splitext(os.path.basename(frame_info.filename))[0] def _func_name(module, frame_info) -> Any: return frame_info.function def _lineno(module, frame_info) -> Any: return frame_info.lineno def _thread(module, frame_info) -> Any: return threading.get_ident() def _thread_name(module, frame_info) -> Any: return threading.current_thread().name def _process(module, frame_info) -> Any: return os.getpid() def _process_name(module, frame_info) -> Any: return get_processname() class PickleableCallsiteParameterAdder(CallsiteParameterAdder): """ Subclass of `CallsiteParameterAdder` that is pickleable. The original implementation is not pickleable because it uses lambda functions to define a handlers dict (see https://github.com/hynek/structlog/blob/186d2eaf7a1d78cba940bd3e99277a538894a6f2/src/structlog/processors.py#L767-L797). This subclass wraps the original, but redefines the lambda functions as top level functions """ _handlers: ClassVar[ dict[CallsiteParameter, Callable[[str, inspect.Traceback], Any]] ] = { CallsiteParameter.PATHNAME: _pathname, CallsiteParameter.FILENAME: _filename, CallsiteParameter.MODULE: _module, CallsiteParameter.FUNC_NAME: _func_name, CallsiteParameter.LINENO: _lineno, CallsiteParameter.THREAD: _thread, CallsiteParameter.THREAD_NAME: _thread_name, CallsiteParameter.PROCESS: _process, CallsiteParameter.PROCESS_NAME: _process_name, } ```
0.0
f0c7e8c71eeb504829218b434bfb7774884bec5c
[ "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_pickeable_callsite_parameter_adder" ]
[ "tests/processors/test_processors.py::TestUnicodeEncoder::test_encodes", "tests/processors/test_processors.py::TestUnicodeEncoder::test_passes_arguments", "tests/processors/test_processors.py::TestUnicodeEncoder::test_bytes_nop", "tests/processors/test_processors.py::TestUnicodeDecoder::test_decodes", "tests/processors/test_processors.py::TestUnicodeDecoder::test_passes_arguments", "tests/processors/test_processors.py::TestUnicodeDecoder::test_bytes_nop", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_stdout_by_default", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_prints_exception", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_removes_exception_after_printing", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_handles_exc_info", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_removes_exc_info_after_printing", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_nop_if_no_exception", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_own_exc_info", "tests/processors/test_processors.py::TestExceptionPrettyPrinter::test_exception_on_py3", "tests/processors/test_processors.py::TestStackInfoRenderer::test_removes_stack_info", "tests/processors/test_processors.py::TestStackInfoRenderer::test_adds_stack_if_asked", "tests/processors/test_processors.py::TestStackInfoRenderer::test_renders_correct_stack", "tests/processors/test_processors.py::TestStackInfoRenderer::test_additional_ignores", "tests/processors/test_processors.py::TestFigureOutExcInfo::test_obtains_exc_info_on_True[True]", "tests/processors/test_processors.py::TestFigureOutExcInfo::test_obtains_exc_info_on_True[1]", "tests/processors/test_processors.py::TestFigureOutExcInfo::test_obtains_exc_info_on_True[1.1]", "tests/processors/test_processors.py::TestFigureOutExcInfo::test_py3_exception_no_traceback", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_all_parameters", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_async", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_additional_ignores", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings1]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings2]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings3]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings4]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings5]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings6]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings7]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings8]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings9]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings10]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings11]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings12]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[logging-parameter_strings13]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings15]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings16]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings17]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings18]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings19]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings20]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings21]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings22]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings23]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings24]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings25]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings26]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_processor[structlog-parameter_strings27]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings1]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings2]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings3]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings4]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings5]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings6]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings7]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings8]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings9]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings10]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings11]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings12]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-logging-parameter_strings13]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings15]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings16]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings17]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings18]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings19]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings20]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings21]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings22]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings23]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings24]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings25]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings26]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-without-pre-structlog-parameter_strings27]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings29]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings30]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings31]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings32]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings33]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings34]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings35]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings36]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings37]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings38]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings39]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings40]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-logging-parameter_strings41]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings43]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings44]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings45]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings46]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings47]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings48]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings49]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings50]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings51]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings52]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings53]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings54]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[common-with-pre-structlog-parameter_strings55]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings57]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings58]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings59]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings60]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings61]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings62]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings63]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings64]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings65]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings66]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings67]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings68]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-logging-parameter_strings69]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings71]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings72]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings73]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings74]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings75]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings76]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings77]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings78]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings79]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings80]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings81]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings82]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[shared-structlog-parameter_strings83]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings85]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings86]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings87]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings88]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings89]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings90]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings91]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings92]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings93]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings94]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings95]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings96]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-logging-parameter_strings97]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-None]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings99]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings100]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings101]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings102]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings103]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings104]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings105]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings106]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings107]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings108]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings109]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings110]", "tests/processors/test_processors.py::TestCallsiteParameterAdder::test_e2e[everywhere-structlog-parameter_strings111]", "tests/processors/test_processors.py::TestRenameKey::test_rename_once", "tests/processors/test_processors.py::TestRenameKey::test_rename_twice", "tests/processors/test_processors.py::TestRenameKey::test_replace_by_key_is_optional" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-03-11 18:20:17+00:00
mit
2,788
iamjackg__md2cf-97
diff --git a/CHANGELOG.md b/CHANGELOG.md index 3614043..a26d632 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased +### Fixed +- Local section links are no longer rendered as broken relative links (e.g. `[this section](#section-header)`) + ## 2.2.0 - 2023-07-08 ### Added - Relative links support section headers (@jimstein3d) diff --git a/md2cf/confluence_renderer.py b/md2cf/confluence_renderer.py index 5829fa2..74b3496 100644 --- a/md2cf/confluence_renderer.py +++ b/md2cf/confluence_renderer.py @@ -105,8 +105,10 @@ class ConfluenceRenderer(mistune.Renderer): def link(self, link, title, text): parsed_link = urlparse(link) - if self.enable_relative_links and ( - not parsed_link.scheme and not parsed_link.netloc + if ( + self.enable_relative_links + and (not parsed_link.scheme and not parsed_link.netloc) + and parsed_link.path ): # relative link replacement_link = f"md2cf-internal-link-{uuid.uuid4()}"
iamjackg/md2cf
1572ed3c4ecf849b8602d25b733852338f131baf
diff --git a/test_package/unit/test_renderer.py b/test_package/unit/test_renderer.py index 40c50fc..1ab9596 100644 --- a/test_package/unit/test_renderer.py +++ b/test_package/unit/test_renderer.py @@ -1,3 +1,7 @@ +import re + +import pytest + from md2cf.confluence_renderer import ConfluenceRenderer, ConfluenceTag @@ -263,3 +267,93 @@ def test_renderer_remove_text_newlines(): renderer = ConfluenceRenderer(remove_text_newlines=True) assert renderer.text(test_text) == test_stripped_text + + [email protected]("relative_links", [False, True]) +def test_renderer_normal_link(relative_links): + renderer = ConfluenceRenderer(enable_relative_links=relative_links) + + assert ( + renderer.link(link="https://example.com", text="example link", title=None) + == '<a href="https://example.com">example link</a>' + ) + + [email protected]("relative_links", [False, True]) +def test_renderer_local_header_link(relative_links): + renderer = ConfluenceRenderer(enable_relative_links=relative_links) + + assert ( + renderer.link(link="#header-name", text="example link", title=None) + == '<a href="#header-name">example link</a>' + ) + + +def test_renderer_relative_link_enabled(): + renderer = ConfluenceRenderer(enable_relative_links=True) + + relative_link_regex = re.compile( + r"<a href=\"md2cf-internal-link-([-a-z0-9]+)\">relative link</a>" + ) + temporary_link = renderer.link( + link="document/../path/page.md", text="relative link", title=None + ) + assert relative_link_regex.match(temporary_link) + assert len(renderer.relative_links) == 1 + relative_link = renderer.relative_links[0] + + assert relative_link.path == "document/../path/page.md" + assert ( + relative_link.replacement == f"md2cf-internal-link-" + f"{relative_link_regex.match(temporary_link).groups(1)[0]}" + ) + assert relative_link.fragment == "" + assert relative_link.original == "document/../path/page.md" + assert relative_link.escaped_original == "document/../path/page.md" + + +def test_renderer_relative_link_with_fragment_enabled(): + renderer = ConfluenceRenderer(enable_relative_links=True) + + relative_link_regex = re.compile( + r"<a href=\"md2cf-internal-link-([-a-z0-9]+)\">relative link</a>" + ) + temporary_link = renderer.link( + link="document/../path/page.md#header-name", text="relative link", title=None + ) + assert relative_link_regex.match(temporary_link) + assert len(renderer.relative_links) == 1 + relative_link = renderer.relative_links[0] + + assert relative_link.path == "document/../path/page.md" + assert ( + relative_link.replacement == f"md2cf-internal-link-" + f"{relative_link_regex.match(temporary_link).groups(1)[0]}" + ) + assert relative_link.fragment == "header-name" + assert relative_link.original == "document/../path/page.md#header-name" + assert relative_link.escaped_original == "document/../path/page.md#header-name" + + +def test_renderer_relative_link_disabled(): + renderer = ConfluenceRenderer(enable_relative_links=False) + + assert ( + renderer.link(link="document/../path/page.md", text="relative link", title=None) + == '<a href="document/../path/page.md">relative link</a>' + ) + assert renderer.relative_links == [] + + +def test_renderer_relative_link_with_fragment_disabled(): + renderer = ConfluenceRenderer(enable_relative_links=False) + + assert ( + renderer.link( + link="document/../path/page.md#header-name", + text="relative link", + title=None, + ) + == '<a href="document/../path/page.md#header-name">relative link</a>' + ) + assert renderer.relative_links == []
Link parsing fails for document references Hi, I just noticed that it's not possible to use `md2cf` anymore with document references like table of contents, since the relative path detector detects the paths that start with `#` ```md [Frequently Asked Questions](#frequently-asked-questions-osep) ``` Having something like this in the document results in ``` Page test.md has a relative link to , which is not in the list of pages to be uploaded. ```
0.0
1572ed3c4ecf849b8602d25b733852338f131baf
[ "test_package/unit/test_renderer.py::test_renderer_local_header_link[True]" ]
[ "test_package/unit/test_renderer.py::test_add_namespace", "test_package/unit/test_renderer.py::test_tag_append", "test_package/unit/test_renderer.py::test_tag_render", "test_package/unit/test_renderer.py::test_tag_render_with_text", "test_package/unit/test_renderer.py::test_tag_render_with_cdata_text", "test_package/unit/test_renderer.py::test_tag_render_with_attribute", "test_package/unit/test_renderer.py::test_tag_render_with_multiple_attributes", "test_package/unit/test_renderer.py::test_tag_render_with_child", "test_package/unit/test_renderer.py::test_tag_render_with_child_and_text", "test_package/unit/test_renderer.py::test_renderer_reinit", "test_package/unit/test_renderer.py::test_renderer_block_code", "test_package/unit/test_renderer.py::test_renderer_block_code_with_language", "test_package/unit/test_renderer.py::test_renderer_header_sets_title", "test_package/unit/test_renderer.py::test_renderer_strips_header", "test_package/unit/test_renderer.py::test_renderer_header_lower_level_does_not_set_title", "test_package/unit/test_renderer.py::test_renderer_header_later_level_sets_title", "test_package/unit/test_renderer.py::test_renderer_header_only_sets_first_title", "test_package/unit/test_renderer.py::test_renderer_image_external", "test_package/unit/test_renderer.py::test_renderer_image_external_alt_and_title", "test_package/unit/test_renderer.py::test_renderer_image_internal_absolute", "test_package/unit/test_renderer.py::test_renderer_image_internal_relative", "test_package/unit/test_renderer.py::test_renderer_remove_text_newlines", "test_package/unit/test_renderer.py::test_renderer_normal_link[False]", "test_package/unit/test_renderer.py::test_renderer_normal_link[True]", "test_package/unit/test_renderer.py::test_renderer_local_header_link[False]", "test_package/unit/test_renderer.py::test_renderer_relative_link_enabled", "test_package/unit/test_renderer.py::test_renderer_relative_link_with_fragment_enabled", "test_package/unit/test_renderer.py::test_renderer_relative_link_disabled", "test_package/unit/test_renderer.py::test_renderer_relative_link_with_fragment_disabled" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-17 15:33:37+00:00
mit
2,789
iaroslavscript__elk-confd-parser-12
diff --git a/elkconfdparser/__main__.py b/elkconfdparser/__main__.py new file mode 100644 index 0000000..1615c0c --- /dev/null +++ b/elkconfdparser/__main__.py @@ -0,0 +1,7 @@ +import sys + +from elkconfdparser.cli import main + + +if __name__ == "__main__": # noqa + main(sys.argv[1:]) diff --git a/elkconfdparser/cli.py b/elkconfdparser/cli.py index d8d92a7..9e296b3 100644 --- a/elkconfdparser/cli.py +++ b/elkconfdparser/cli.py @@ -37,4 +37,4 @@ def display(data): if __name__ == "__main__": # noqa - main(sys.argv[1:]) \ No newline at end of file + main(sys.argv[1:]) diff --git a/elkconfdparser/parser.py b/elkconfdparser/parser.py index a4406fb..0fe7718 100644 --- a/elkconfdparser/parser.py +++ b/elkconfdparser/parser.py @@ -104,7 +104,7 @@ def _parse(text, start, end): # noqa: C901 # FIXME def _drop_stack(root, stack): if len(stack) > 1: - root.append({stack.pop(): stack.pop()}) + root.setdefault(stack.pop(), []).append(stack.pop()) if len(stack): raise errors.StackNotEmptyException('Unknown operands left on stack after assigment')
iaroslavscript/elk-confd-parser
4eca1a05488ece59a61c788cc377a90a5a9dcfd1
diff --git a/tests/test_parser.py b/tests/test_parser.py index 5a90c3a..8f1c6ea 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -3,6 +3,7 @@ import pytest from elkconfdparser import errors from elkconfdparser import parser + class TestDropStack: @pytest.mark.parametrize( "input_root, input_stack, expected_root, expected_stack", @@ -10,11 +11,11 @@ class TestDropStack: ({}, [], {}, []), ({}, [1], {}, [1]), ({}, [2, 1], {1: [2]}, []), - ({1:[8]}, [2, 1], {1: [8, 2]}, []), - ({1:[8], 3: [9]}, [2, 1], {1: [8, 2], 3: [9]}, []), + ({1: [8]}, [2, 1], {1: [8, 2]}, []), + ({1: [8], 3: [9]}, [2, 1], {1: [8, 2], 3: [9]}, []), ], ) - def testTwoOperands(input_root, input_stack, expected_root, expected_stack): + def testTwoOperands(self, input_root, input_stack, expected_root, expected_stack): assert parser._drop_stack(input_root, input_stack) is None assert input_root == expected_root @@ -23,10 +24,10 @@ class TestDropStack: @pytest.mark.parametrize( "input_root, input_stack, expected_root, expected_stack", [ - ({}, [3, 2, 1,], {1: [2]}, [3]), + ({}, [3, 2, 1], {1: [2]}, [3]), ], ) - def testMultipleOperands(input_root, input_stack, expected_root, expected_stack): + def testMultipleOperands(self, input_root, input_stack, expected_root, expected_stack): with pytest.raises(errors.StackNotEmptyException, match=r'.*operands left.*'): parser._drop_stack(input_root, input_stack)
hot fix for root.append AttributeError: 'dict' object has no attribute 'append'
0.0
4eca1a05488ece59a61c788cc377a90a5a9dcfd1
[ "tests/test_parser.py::TestDropStack::testTwoOperands[input_root2-input_stack2-expected_root2-expected_stack2]", "tests/test_parser.py::TestDropStack::testTwoOperands[input_root3-input_stack3-expected_root3-expected_stack3]", "tests/test_parser.py::TestDropStack::testTwoOperands[input_root4-input_stack4-expected_root4-expected_stack4]", "tests/test_parser.py::TestDropStack::testMultipleOperands[input_root0-input_stack0-expected_root0-expected_stack0]" ]
[ "tests/test_parser.py::TestDropStack::testTwoOperands[input_root0-input_stack0-expected_root0-expected_stack0]", "tests/test_parser.py::TestDropStack::testTwoOperands[input_root1-input_stack1-expected_root1-expected_stack1]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2021-07-30 17:50:14+00:00
mit
2,790
icetemple__genrss-11
diff --git a/.gitignore b/.gitignore index d9ecf51..361de9e 100644 --- a/.gitignore +++ b/.gitignore @@ -152,4 +152,5 @@ tags # IDE .idea/ -.c9/ \ No newline at end of file +.c9/ +.vscode/ \ No newline at end of file diff --git a/genrss/__init__.py b/genrss/__init__.py index 5dd3096..725cba3 100644 --- a/genrss/__init__.py +++ b/genrss/__init__.py @@ -100,7 +100,7 @@ class GenRSS: channel_image = self.image if not channel_image and self.image_url: channel_image = Image(self.image_url, self.site_url, self.title) - if isinstance(image, Image): + if isinstance(channel_image, Image): channel.append(channel_image.to_element()) for category in self.categories:
icetemple/genrss
be86824ab086290cf85509625b204d59d839e4be
diff --git a/tests/test_rss.py b/tests/test_rss.py index d9c0eff..cbae47f 100644 --- a/tests/test_rss.py +++ b/tests/test_rss.py @@ -80,10 +80,15 @@ def test_feed_image_url(): image_url = 'https://s3.smartfridge.me/image.jpg' feed = create_rss(image_url=image_url) xml = feed.xml() + assert xml - assert (f'<image><url>{image_url}</url>' + assert ( + '<image>' + f'<url>{image_url}</url>' + '<link>https://smartfridge.me/</link>' '<title><![CDATA[SmartFridge]]></title>' - '<link>https://smartfridge.me/</link></image>') in xml + '</image>' + ) in xml def test_feed_webmaster():
Genrss don't return image <!-- Describe the bug --> When i add image or image_url, genrss generate xml without image. ### To Reproduce Steps to reproduce the behavior: 1. Init GenRSS object with arguments title, site_url, feed_url and image_url with any link. 2. try to get xml. ```python image_url = 'https://s3.smartfridge.me/image.jpg' feed = GenRSS( title='SmartFridge', site_url='https://example.com/', feed_url='https://example.com/rss.xml', image_url='https://example.com/image.jpg' ) xml = feed.xml() ``` ### Expected Behavior <!-- Tell us what should happen. --> returns xml like ```python '<image>' '<url>https://example.com/image.jpg</url>' '<link>https://example.com</link>' '<title><![CDATA[title]]></title>' '</image>' ``` ### Actual Behavior <!-- Tell us what happens instead. --> Returns xml without image attribute without errors. ### Environment * OS: Ubuntu 20.04.1 LTS (64 bit) * Python version: 3.8 * GenRSS version: 1.0.5
0.0
be86824ab086290cf85509625b204d59d839e4be
[ "tests/test_rss.py::test_feed_image_url" ]
[ "tests/test_rss.py::test_init_rss", "tests/test_rss.py::test_feed_description[short(10)]", "tests/test_rss.py::test_feed_description[long(285)]", "tests/test_rss.py::test_feed_description[+nl]", "tests/test_rss.py::test_feed_copyright[copy]", "tests/test_rss.py::test_feed_pub_date", "tests/test_rss.py::test_feed_language", "tests/test_rss.py::test_feed_editor", "tests/test_rss.py::test_feed_webmaster", "tests/test_rss.py::test_feed_docs_url", "tests/test_rss.py::test_feed_categories", "tests/test_rss.py::test_feed_bad_items" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-11-08 01:43:51+00:00
mit
2,791
ifosch__accloudtant-104
diff --git a/accloudtant/aws/prices.py b/accloudtant/aws/prices.py index 44435af..1cb74ef 100644 --- a/accloudtant/aws/prices.py +++ b/accloudtant/aws/prices.py @@ -143,7 +143,8 @@ def process_model(url, instances=None): instances = {} js_name = url.split('/')[-1] pricing = requests.get(url) - for js_line in io.StringIO(pricing.content.decode("utf-8").replace("\n", "")): + content = pricing.content.decode("utf-8").replace("\n", "") + for js_line in io.StringIO(content): if 'callback' in js_line: data = fix_lazy_json(re.sub(r".*callback\((.+)\).*", r"\1", js_line)) diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index 65a433e..0f56ea5 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -24,7 +24,7 @@ import sys class Reports(object): - def __init__(self, logger = None): + def __init__(self, logger=None): if logger is None: self.logger = getLogger('accloudtant.report') self.logger.setLevel(DEBUG) @@ -33,25 +33,36 @@ class Reports(object): self.logger = logger ec2 = boto3.resource('ec2') ec2_client = boto3.client('ec2') - instances_filters = [{ - 'Name': 'instance-state-name', - 'Values': ['running', ], - }, ] - reserved_instances_filters = [{ - 'Name': 'state', - 'Values': ['active', ], - }, ] + self.counters = { + 'instances': { + 'total': 0, + }, + 'reserved': { + 'total': 0, + }, + } + self.instances = [] + self.reserved_instances = [] try: - self.instances = [ - Instance(i) - for i in ec2.instances.filter(Filters=instances_filters) - ] - self.reserved_instances = [ - ReservedInstance(i) - for i in ec2_client.describe_reserved_instances( - Filters=reserved_instances_filters - )['ReservedInstances'] - ] + for i in ec2.instances.all(): + instance = Instance(i) + if instance.state == "running": + self.instances.append(instance) + if instance.state not in self.counters['instances']: + self.counters['instances'][instance.state] = 0 + self.counters['instances'][instance.state] += 1 + self.counters['instances']['total'] += 1 + ri_key = 'ReservedInstances' + reserved_ctrs = self.counters['reserved'] + for r in ec2_client.describe_reserved_instances()[ri_key]: + reserved_instance = ReservedInstance(r) + if reserved_instance.state == "active": + self.reserved_instances.append(reserved_instance) + reserved_ctrs['total'] += reserved_instance.instance_count + reserved_ctrs['free'] = reserved_ctrs['total'] + reserved_ctrs['not_reserved'] = reserved_ctrs['total'] + reserved_ctrs['used'] = 0 + reserved_ctrs['not reserved'] = 0 except exceptions.NoCredentialsError: logger.error("Error: no AWS credentials found") sys.exit(1) @@ -72,30 +83,60 @@ class Reports(object): instance.reserved = 'Yes' instance.current = reserved.usage_price reserved.link(instance) + self.counters['reserved']['used'] += 1 + self.counters['reserved']['free'] -= 1 break + reserved_counters = self.counters['reserved'] + instances_counters = self.counters['instances'] + reserved_counters['not reserved'] = instances_counters['running'] + reserved_counters['not reserved'] -= reserved_counters['used'] def __repr__(self): - headers = ['Id', - 'Name', - 'Type', - 'AZ', - 'OS', - 'State', - 'Launch time', - 'Reserved', - 'Current hourly price', - 'Renewed hourly price'] + headers = [ + 'Id', + 'Name', + 'Type', + 'AZ', + 'OS', + 'State', + 'Launch time', + 'Reserved', + 'Current hourly price', + 'Renewed hourly price', + ] table = [] for instance in self.instances: - row = [instance.id, - instance.name, - instance.size, - instance.availability_zone, - instance.operating_system, - instance.state, - instance.launch_time.strftime('%Y-%m-%d %H:%M:%S'), - instance.reserved, - instance.current, - instance.best] + row = [ + instance.id, + instance.name, + instance.size, + instance.availability_zone, + instance.operating_system, + instance.state, + instance.launch_time.strftime('%Y-%m-%d %H:%M:%S'), + instance.reserved, + instance.current, + instance.best, + ] table.append(row) - return tabulate(table, headers) + footer_headers = [ + 'Running', + 'Stopped', + 'Total instances', + 'Used', + 'Free', + 'Not reserved', + 'Total reserved', + ] + footer_table = [[ + self.counters['instances']['running'], + self.counters['instances']['stopped'], + self.counters['instances']['total'], + self.counters['reserved']['used'], + self.counters['reserved']['free'], + self.counters['reserved']['not reserved'], + self.counters['reserved']['total'], + ]] + inventory = tabulate(table, headers) + summary = tabulate(footer_table, footer_headers) + return "{}\n\n{}".format(inventory, summary) diff --git a/accloudtant/utils/__init__.py b/accloudtant/utils/__init__.py index c1b5df2..1e7211d 100644 --- a/accloudtant/utils/__init__.py +++ b/accloudtant/utils/__init__.py @@ -15,7 +15,6 @@ # limitations under the License. import io -import codecs import tokenize import token
ifosch/accloudtant
8fdb36de3e41cc719b1e1df95c1083a9ea427392
diff --git a/tests/aws/report_expected.txt b/tests/aws/report_expected.txt index f2bbb8b..882ff19 100644 --- a/tests/aws/report_expected.txt +++ b/tests/aws/report_expected.txt @@ -7,3 +7,7 @@ i-1840273d database1 r2.8xlarge us-east-1c Linux/UNIX stopped i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892 + + Running Stopped Total instances Used Free Not reserved Total reserved +--------- --------- ----------------- ------ ------ -------------- ---------------- + 6 1 7 5 1 1 6 diff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected.txt index befecd0..e7bd69c 100644 --- a/tests/aws/report_running_expected.txt +++ b/tests/aws/report_running_expected.txt @@ -6,3 +6,7 @@ i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892 + + Running Stopped Total instances Used Free Not reserved Total reserved +--------- --------- ----------------- ------ ------ -------------- ---------------- + 6 1 7 5 1 1 6 diff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py index d0f6793..57084c3 100644 --- a/tests/aws/test_reports.py +++ b/tests/aws/test_reports.py @@ -320,6 +320,39 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): 'UsagePrice': 0.611, 'Duration': 31536000, 'State': 'active', + }, { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 't2.micro', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + tzinfo=tzutc() + ), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', + 'FixedPrice': 5352.36, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.611, + 'Duration': 31536000, + 'State': 'active', }, { 'ProductDescription': 'Linux/UNIX', 'InstanceTenancy': 'default', diff --git a/tests/aws/test_reserved_instance.py b/tests/aws/test_reserved_instance.py index 9627ebf..50fd6fc 100644 --- a/tests/aws/test_reserved_instance.py +++ b/tests/aws/test_reserved_instance.py @@ -13,7 +13,6 @@ # limitations under the License. import datetime -import pytest from dateutil.tz import tzutc import accloudtant.aws.reserved_instance from conftest import MockEC2Instance diff --git a/tests/test_utils.py b/tests/test_utils.py index caad5a4..c3b0877 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -19,4 +19,5 @@ import accloudtant.utils def test_fix_lazy_json(): bad_json = '{ key: "value" }'.encode('utf-8') good_json = '{"key":"value"}' - assert(accloudtant.utils.fix_lazy_json(codecs.decode(bad_json)) == good_json) + result = accloudtant.utils.fix_lazy_json(codecs.decode(bad_json)) + assert(result == good_json)
Create footer for report When I use the `report` command I want to get a footer with totals.
0.0
8fdb36de3e41cc719b1e1df95c1083a9ea427392
[ "tests/aws/test_reports.py::test_reports" ]
[ "tests/aws/test_reserved_instance.py::test_retired_ri", "tests/aws/test_reserved_instance.py::test_active_ri", "tests/aws/test_reserved_instance.py::test_ri_link", "tests/test_utils.py::test_fix_lazy_json" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-07-19 10:07:22+00:00
apache-2.0
2,792
ifosch__accloudtant-108
diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index 0f56ea5..6754f6b 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -22,15 +22,15 @@ from accloudtant.aws.reserved_instance import ReservedInstance from accloudtant.aws.prices import Prices import sys - class Reports(object): - def __init__(self, logger=None): + def __init__(self, output_format, logger=None): if logger is None: self.logger = getLogger('accloudtant.report') self.logger.setLevel(DEBUG) self.logger.addHandler(StreamHandler(sys.stdout)) else: self.logger = logger + self.output_format=output_format ec2 = boto3.resource('ec2') ec2_client = boto3.client('ec2') self.counters = { @@ -91,7 +91,7 @@ class Reports(object): reserved_counters['not reserved'] = instances_counters['running'] reserved_counters['not reserved'] -= reserved_counters['used'] - def __repr__(self): + def print_report(self): headers = [ 'Id', 'Name', @@ -119,24 +119,45 @@ class Reports(object): instance.best, ] table.append(row) - footer_headers = [ - 'Running', - 'Stopped', - 'Total instances', - 'Used', - 'Free', - 'Not reserved', - 'Total reserved', - ] - footer_table = [[ - self.counters['instances']['running'], - self.counters['instances']['stopped'], - self.counters['instances']['total'], - self.counters['reserved']['used'], - self.counters['reserved']['free'], - self.counters['reserved']['not reserved'], - self.counters['reserved']['total'], - ]] - inventory = tabulate(table, headers) - summary = tabulate(footer_table, footer_headers) - return "{}\n\n{}".format(inventory, summary) + + if self.output_format == 'table': + footer_headers = [ + 'Running', + 'Stopped', + 'Total instances', + 'Used', + 'Free', + 'Not reserved', + 'Total reserved', + ] + footer_table = [[ + self.counters['instances']['running'], + self.counters['instances']['stopped'], + self.counters['instances']['total'], + self.counters['reserved']['used'], + self.counters['reserved']['free'], + self.counters['reserved']['not reserved'], + self.counters['reserved']['total'], + ]] + inventory = tabulate(table, headers) + summary = tabulate(footer_table, footer_headers) + + return "{}\n\n{}".format(inventory, summary) + + elif self.output_format == 'csv': + output = '' + for header in headers: + output += header + ',' + output = output[:-1] + '\n' + for row in table: + for column in row: + output += str(column) + ',' + output = output[:-1] + '\n' + + return output[:-1] + + else: + raise Exception() + + def __repr__(self): + return self.print_report() diff --git a/bin/accloudtant b/bin/accloudtant index 148bc66..f9ab2b0 100755 --- a/bin/accloudtant +++ b/bin/accloudtant @@ -14,15 +14,15 @@ logger.addHandler(StreamHandler(sys.stdout)) def cli(): pass - @cli.command('list', short_help='prints current price lists') def price_list(): logger.info(Prices()) - @cli.command(short_help='provides price/usage reports') -def report(): - logger.info(Reports()) [email protected]('--output', default='table', type=click.Choice(['table', 'csv']), + help='Change output format') +def report(output): + logger.info(Reports(output_format=output)) if __name__ == '__main__': cli()
ifosch/accloudtant
b662c13380e9e5c42232e51ef3ef059c679ad5e9
diff --git a/tests/aws/report_running_expected_csv.txt b/tests/aws/report_running_expected_csv.txt new file mode 100644 index 0000000..ba4cbe8 --- /dev/null +++ b/tests/aws/report_running_expected_csv.txt @@ -0,0 +1,7 @@ +Id,Name,Type,AZ,OS,State,Launch time,Reserved,Current hourly price,Renewed hourly price +i-912a4392,web1,c3.8xlarge,us-east-1c,Windows,running,2015-10-22 14:15:10,Yes,0.5121,0.3894 +i-1840273e,app1,r2.8xlarge,us-east-1b,Red Hat Enterprise Linux,running,2015-10-22 14:15:10,Yes,0.3894,0.3794 +i-9840273d,app2,r2.8xlarge,us-east-1c,SUSE Linux,running,2015-10-22 14:15:10,Yes,0.5225,0.389 +i-1840273c,database2,r2.8xlarge,us-east-1c,Linux/UNIX,running,2015-10-22 14:15:10,Yes,0.611,0.379 +i-1840273b,database3,r2.8xlarge,us-east-1c,Linux/UNIX,running,2015-10-22 14:15:10,Yes,0.611,0.379 +i-912a4393,test,t1.micro,us-east-1c,Linux/UNIX,running,2015-10-22 14:15:10,No,0.767,0.3892 diff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected_table.txt similarity index 100% rename from tests/aws/report_running_expected.txt rename to tests/aws/report_running_expected_table.txt diff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py index 57084c3..80d2c24 100644 --- a/tests/aws/test_reports.py +++ b/tests/aws/test_reports.py @@ -20,8 +20,635 @@ import accloudtant.aws.reports def get_future_date(years=1): return datetime.datetime.now() + datetime.timedelta(years) +def test_reports_table(capsys, monkeypatch, ec2_resource, ec2_client, + process_ec2): + instances = { + 'instances': [{ + 'id': 'i-912a4392', + 'tags': [{ + 'Key': 'Name', + 'Value': 'web1', + }, ], + 'instance_type': 'c3.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc(), + ), + 'console_output': {'Output': 'Windows', }, + }, { + 'id': 'i-1840273e', + 'tags': [{ + 'Key': 'Name', + 'Value': 'app1', + }, ], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1b', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'RHEL Linux', }, + }, { + 'id': 'i-9840273d', + 'tags': [{ + 'Key': 'Name', + 'Value': 'app2', + }, ], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'SUSE Linux', }, + }, { + 'id': 'i-1840273d', + 'tags': [{ + 'Key': 'Name', + 'Value': 'database1', + }, ], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'stopped', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'Linux', }, + }, { + 'id': 'i-1840273c', + 'tags': [{ + 'Key': 'Name', + 'Value': 'database2', + }, ], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'Linux', }, + }, { + 'id': 'i-1840273b', + 'tags': [{ + 'Key': 'Name', + 'Value': 'database3', + }, ], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'Linux', }, + }, { + 'id': 'i-912a4393', + 'tags': [{ + 'Key': 'Name', + 'Value': 'test', + }, ], + 'instance_type': 't1.micro', + 'placement': { + 'AvailabilityZone': 'us-east-1c', + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc(), + ), + 'console_output': {'Output': 'Linux', }, + }, ] + } + reserved_instances = { + 'ReservedInstances': [{ + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 29, + 'InstanceType': 'm1.large', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + tzinfo=tzutc() + ), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df1223331f', + 'FixedPrice': 910.0, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.12, + 'Duration': 31536000, + 'State': 'retired', + }, { + 'ProductDescription': 'Windows', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'c3.8xlarge', + 'Start': datetime.datetime( + 2015, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', + 'FixedPrice': 4486.0, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.5121, + 'Duration': 31536000, + 'State': 'active', + }, { + 'ProductDescription': 'Red Hat Enterprise Linux', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'r2.8xlarge', + 'Start': datetime.datetime( + 2015, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321', + 'FixedPrice': 10234, + 'AvailabilityZone': 'us-east-1b', + 'UsagePrice': 0.3894, + 'Duration': 94608000, + 'State': 'active', + }, { + 'ProductDescription': 'SUSE Linux', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'r2.8xlarge', + 'Start': datetime.datetime( + 2015, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233322', + 'FixedPrice': 2974.0, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.5225, + 'Duration': 31536000, + 'State': 'active', + }, { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'r2.8xlarge', + 'Start': datetime.datetime( + 2015, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': get_future_date(), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', + 'FixedPrice': 5352.36, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.611, + 'Duration': 31536000, + 'State': 'active', + }, { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 't2.micro', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + tzinfo=tzutc() + ), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', + 'FixedPrice': 5352.36, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.611, + 'Duration': 31536000, + 'State': 'active', + }, { + 'ProductDescription': 'Linux/UNIX', + 'InstanceTenancy': 'default', + 'InstanceCount': 1, + 'InstanceType': 'r2.8xlarge', + 'Start': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + 494000, + tzinfo=tzutc() + ), + 'RecurringCharges': [], + 'End': datetime.datetime( + 2011, + 6, + 5, + 6, + 20, + 10, + tzinfo=tzutc() + ), + 'CurrencyCode': 'USD', + 'OfferingType': 'Medium Utilization', + 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', + 'FixedPrice': 5352.36, + 'AvailabilityZone': 'us-east-1c', + 'UsagePrice': 0.611, + 'Duration': 31536000, + 'State': 'active', + }, ] + } + prices = { + 'win': { + 'us-east-1': { + 'c3.8xlarge': { + 'storageGB': '60 SSD', + 'ri': { + 'yrTerm1': { + 'noUpfront': { + 'upfront': '0', + 'monthlyStar': '446.03', + 'effectiveHourly': '0.611', + }, + 'partialUpfront': { + 'upfront': '2974', + 'monthlyStar': '133.59', + 'effectiveHourly': '0.5225', + }, + 'allUpfront': { + 'upfront': '4398.4', + 'monthlyStar': '0', + 'effectiveHourly': '0.5021', + }, + }, + 'yrTerm3': { + 'allUpfront': { + 'upfront': '10234', + 'monthlyStar': '0', + 'effectiveHourly': '0.3894', + }, + 'partialUpfront': { + 'upfront': '7077', + 'monthlyStar': '105.85', + 'effectiveHourly': '0.4143', + }, + }, + }, + 'od': '0.867', + 'memoryGiB': '15', + 'vCPU': '8', + }, + }, + }, + 'rhel': { + 'us-east-1': { + 'r2.8xlarge': { + 'storageGB': '60 SSD', + 'ri': { + 'yrTerm1': { + 'noUpfront': { + 'upfront': '0', + 'monthlyStar': '446.03', + 'effectiveHourly': '0.611', + }, + 'partialUpfront': { + 'upfront': '2974', + 'monthlyStar': '133.59', + 'effectiveHourly': '0.5225', + }, + 'allUpfront': { + 'upfront': '4486', + 'monthlyStar': '0', + 'effectiveHourly': '0.5121', + }, + }, + 'yrTerm3': { + 'allUpfront': { + 'upfront': '10233.432', + 'monthlyStar': '0', + 'effectiveHourly': '0.3794', + }, + 'partialUpfront': { + 'upfront': '7077', + 'monthlyStar': '105.85', + 'effectiveHourly': '0.4143', + }, + }, + }, + 'od': '0.767', + 'memoryGiB': '15', + 'vCPU': '8', + }, + }, + }, + 'suse': { + 'us-east-1': { + 'r2.8xlarge': { + 'storageGB': '60 SSD', + 'ri': { + 'yrTerm1': { + 'noUpfront': { + 'upfront': '0', + 'monthlyStar': '446.03', + 'effectiveHourly': '0.611', + }, + 'partialUpfront': { + 'upfront': '2974', + 'monthlyStar': '133.59', + 'effectiveHourly': '0.5225', + }, + 'allUpfront': { + 'upfront': '4486', + 'monthlyStar': '0', + 'effectiveHourly': '0.5121', + }, + }, + 'yrTerm3': { + 'allUpfront': { + 'upfront': '10234', + 'monthlyStar': '0', + 'effectiveHourly': '0.3890', + }, + 'partialUpfront': { + 'upfront': '7077', + 'monthlyStar': '105.85', + 'effectiveHourly': '0.4143', + }, + }, + }, + 'od': '0.767', + 'memoryGiB': '15', + 'vCPU': '8', + }, + }, + }, + 'linux': { + 'us-east-1': { + 't1.micro': { + 'storageGB': '60 SSD', + 'ri': { + 'yrTerm1': { + 'noUpfront': { + 'upfront': '0', + 'monthlyStar': '446.03', + 'effectiveHourly': '0.611', + }, + 'allUpfront': { + 'upfront': '2974', + 'monthlyStar': '133.59', + 'effectiveHourly': '0.5225', + }, + 'partialUpfront': { + 'upfront': '4486', + 'monthlyStar': '0', + 'effectiveHourly': '0.5121', + }, + }, + 'yrTerm3': { + 'allUpfront': { + 'upfront': '10234', + 'monthlyStar': '0', + 'effectiveHourly': '0.3892', + }, + 'partialUpfront': { + 'upfront': '7077', + 'monthlyStar': '105.85', + 'effectiveHourly': '0.4143', + }, + }, + }, + 'od': '0.767', + 'memoryGiB': '15', + 'vCPU': '8', + }, + 'r2.8xlarge': { + 'storageGB': '60 SSD', + 'ri': { + 'yrTerm1': { + 'noUpfront': { + 'upfront': '0', + 'monthlyStar': '446.03', + 'effectiveHourly': '0.611', + }, + 'allUpfront': { + 'upfront': '2974', + 'monthlyStar': '133.59', + 'effectiveHourly': '0.5225', + }, + 'partialUpfront': { + 'upfront': '4486', + 'monthlyStar': '0', + 'effectiveHourly': '0.5121', + }, + }, + 'yrTerm3': { + 'allUpfront': { + 'upfront': '10234', + 'monthlyStar': '0', + 'effectiveHourly': '0.3790', + }, + 'partialUpfront': { + 'upfront': '7077', + 'monthlyStar': '105.85', + 'effectiveHourly': '0.4143', + }, + }, + }, + 'od': '0.767', + 'memoryGiB': '15', + 'vCPU': '8', + }, + }, + }, + } + instances_prices = { + 'i-912a4392': { + 'current': 0.5121, + 'best': 0.3894, + }, + 'i-1840273e': { + 'current': 0.3894, + 'best': 0.3794, + }, + 'i-9840273d': { + 'current': 0.5225, + 'best': 0.3890, + }, + 'i-1840273d': { + 'current': 0.0, + 'best': 0.3790, + }, + 'i-1840273c': { + 'current': 0.611, + 'best': 0.3790, + }, + 'i-1840273b': { + 'current': 0.611, + 'best': 0.3790, + }, + 'i-912a4393': { + 'current': 0.767, + 'best': 0.3892, + }, + } + expected = open('tests/aws/report_running_expected_table.txt', 'r').read() + + monkeypatch.setattr('boto3.resource', ec2_resource) + ec2_resource.set_responses(instances) + monkeypatch.setattr('boto3.client', ec2_client) + ec2_client.set_responses({}, reserved_instances) + monkeypatch.setattr( + 'accloudtant.aws.prices.process_ec2', + process_ec2 + ) + process_ec2.set_responses(prices) + + reports = accloudtant.aws.reports.Reports(output_format='table') + print(reports) + out, err = capsys.readouterr() + + assert(len(reports.instances) == 6) + for mock in instances['instances']: + mock['current'] = instances_prices[mock['id']]['current'] + mock['best'] = instances_prices[mock['id']]['best'] + for instance in reports.instances: + if instance.id == mock['id']: + assert(instance.current == mock['current']) + assert(instance.best == mock['best']) + assert(out == expected) -def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): +def test_reports_csv(capsys, monkeypatch, ec2_resource, ec2_client, + process_ec2): instances = { 'instances': [{ 'id': 'i-912a4392', @@ -621,7 +1248,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): 'best': 0.3892, }, } - expected = open('tests/aws/report_running_expected.txt', 'r').read() + expected = open('tests/aws/report_running_expected_csv.txt', 'r').read() monkeypatch.setattr('boto3.resource', ec2_resource) ec2_resource.set_responses(instances) @@ -633,7 +1260,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): ) process_ec2.set_responses(prices) - reports = accloudtant.aws.reports.Reports() + reports = accloudtant.aws.reports.Reports(output_format='csv') print(reports) out, err = capsys.readouterr() @@ -646,3 +1273,4 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): assert(instance.current == mock['current']) assert(instance.best == mock['best']) assert(out == expected) +
CSV as output format The table format is great to see the data in the terminal, but to facilytate the import into other tools, CSV is a best (and simple) choice.
0.0
b662c13380e9e5c42232e51ef3ef059c679ad5e9
[ "tests/aws/test_reports.py::test_reports_table", "tests/aws/test_reports.py::test_reports_csv" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2016-08-04 19:57:34+00:00
apache-2.0
2,793
ifosch__accloudtant-81
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index 4e19b2d..2073f28 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -62,7 +62,7 @@ class Instance(object): @property def name(self): names = [tag for tag in self.tags if tag['Key'] == 'Name'] - if names is None: + if len(names) == 0: return '' else: return names[0]['Value'] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e6661b7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +boto3==1.1.4 +botocore==1.2.10 +click==4.1 +requests==2.8.1 +tabulate==0.7.5
ifosch/accloudtant
9dd6000060b4bddfa5366ef3102fe7d42371d514
diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py index d90e2c5..a016f7b 100644 --- a/tests/aws/test_instance.py +++ b/tests/aws/test_instance.py @@ -73,6 +73,57 @@ def test_instance(): assert(instance.best == 0.293) +def test_unnamed_instance(): + az = 'us-east-1b' + region = 'us-east-1' + instance_data = { + 'id': 'i-1840273e', + 'tags': [], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': az, + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'RHEL Linux', }, + } + + + ec2_instance = MockEC2Instance(instance_data) + instance = accloudtant.aws.instance.Instance(ec2_instance) + + assert(instance.id == ec2_instance.id) + assert(instance.reserved == 'No') + assert(instance.name == '') + assert(instance.size == ec2_instance.instance_type) + assert(instance.availability_zone == az) + assert(instance.region == region) + assert(instance.operating_system == 'Red Hat Enterprise Linux') + assert(instance.key == 'rhel') + assert(instance.state == ec2_instance.state['Name']) + assert(instance.current == 0.0) + assert(instance.best == 0.0) + + with pytest.raises(ValueError): + instance.reserved = 'Maybe' + + instance.current = 0.392 + instance.best = 0.293 + + assert(instance.current == 0.392) + assert(instance.best == 0.293) + + def test_guess_os(): instance_data_win = { 'id': 'i-912a4392',
Missing requirements.txt file I wanted to run accloudtant inside Docker using `FROM python:2.7-onbuild`. This is the output of `docker build`: ``` # Executing 3 build triggers... Step 1 : COPY requirements.txt /usr/src/app/ lstat requirements.txt: no such file or directory ``` More info on how *onbuild* works https://hub.docker.com/_/python/
0.0
9dd6000060b4bddfa5366ef3102fe7d42371d514
[ "tests/aws/test_instance.py::test_unnamed_instance" ]
[ "tests/aws/test_instance.py::test_instance", "tests/aws/test_instance.py::test_guess_os", "tests/aws/test_instance.py::test_match_reserved_instance" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2016-05-29 14:55:32+00:00
apache-2.0
2,794
ifosch__accloudtant-82
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index 4e19b2d..2073f28 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -62,7 +62,7 @@ class Instance(object): @property def name(self): names = [tag for tag in self.tags if tag['Key'] == 'Name'] - if names is None: + if len(names) == 0: return '' else: return names[0]['Value']
ifosch/accloudtant
9dd6000060b4bddfa5366ef3102fe7d42371d514
diff --git a/tests/aws/test_instance.py b/tests/aws/test_instance.py index d90e2c5..a016f7b 100644 --- a/tests/aws/test_instance.py +++ b/tests/aws/test_instance.py @@ -73,6 +73,57 @@ def test_instance(): assert(instance.best == 0.293) +def test_unnamed_instance(): + az = 'us-east-1b' + region = 'us-east-1' + instance_data = { + 'id': 'i-1840273e', + 'tags': [], + 'instance_type': 'r2.8xlarge', + 'placement': { + 'AvailabilityZone': az, + }, + 'state': { + 'Name': 'running', + }, + 'launch_time': datetime.datetime( + 2015, + 10, + 22, + 14, + 15, + 10, + tzinfo=tzutc() + ), + 'console_output': {'Output': 'RHEL Linux', }, + } + + + ec2_instance = MockEC2Instance(instance_data) + instance = accloudtant.aws.instance.Instance(ec2_instance) + + assert(instance.id == ec2_instance.id) + assert(instance.reserved == 'No') + assert(instance.name == '') + assert(instance.size == ec2_instance.instance_type) + assert(instance.availability_zone == az) + assert(instance.region == region) + assert(instance.operating_system == 'Red Hat Enterprise Linux') + assert(instance.key == 'rhel') + assert(instance.state == ec2_instance.state['Name']) + assert(instance.current == 0.0) + assert(instance.best == 0.0) + + with pytest.raises(ValueError): + instance.reserved = 'Maybe' + + instance.current = 0.392 + instance.best = 0.293 + + assert(instance.current == 0.392) + assert(instance.best == 0.293) + + def test_guess_os(): instance_data_win = { 'id': 'i-912a4392',
Fails with Python 3 My system have Python 3 installed by default (Archlinux). This is the output of `accloudtant report`: ``` Traceback (most recent call last): File "/usr/bin/accloudtant", line 22, in <module> cli() File "/usr/lib/python3.5/site-packages/click/core.py", line 716, in __call__ return self.main(*args, **kwargs) File "/usr/lib/python3.5/site-packages/click/core.py", line 696, in main rv = self.invoke(ctx) File "/usr/lib/python3.5/site-packages/click/core.py", line 1060, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/lib/python3.5/site-packages/click/core.py", line 889, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/lib/python3.5/site-packages/click/core.py", line 534, in invoke return callback(*args, **kwargs) File "/usr/bin/accloudtant", line 19, in report click.echo(Reports()) File "/usr/lib/python3.5/site-packages/click/utils.py", line 221, in echo message = text_type(message) File "/usr/lib/python3.5/site-packages/accloudtant/aws/reports.py", line 69, in __repr__ instance.name, File "/usr/lib/python3.5/site-packages/accloudtant/aws/instance.py", line 68, in name return names[0]['Value'] IndexError: list index out of range ``` I can't verify that it works well on Python 2 so fell free to close this issue and open a new one if the problem is not caused by the Python version.
0.0
9dd6000060b4bddfa5366ef3102fe7d42371d514
[ "tests/aws/test_instance.py::test_unnamed_instance" ]
[ "tests/aws/test_instance.py::test_instance", "tests/aws/test_instance.py::test_guess_os", "tests/aws/test_instance.py::test_match_reserved_instance" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-05-29 14:55:50+00:00
apache-2.0
2,795
ifosch__accloudtant-88
diff --git a/accloudtant/aws/instance.py b/accloudtant/aws/instance.py index d83c3dc..f360c03 100644 --- a/accloudtant/aws/instance.py +++ b/accloudtant/aws/instance.py @@ -28,6 +28,9 @@ class Instance(object): 'best': 0.0, } + def __repr__(self): + return "<accloudtant.aws.instance.Instance id={}>".format(self.id) + @property def current(self): return self._prices['current'] diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index 0bbbeb9..e8f2fc9 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -25,9 +25,26 @@ class Reports(object): def __init__(self): ec2 = boto3.resource('ec2') ec2_client = boto3.client('ec2') + instances_filters = [{ + 'Name': 'instance-state-name', + 'Values': ['running', ], + }, ] + reserved_instances_filters = [{ + 'Name': 'state', + 'Values': ['active', ], + }, ] try: - self.instances = [Instance(i) for i in ec2.instances.all()] - self.reserved_instances = ec2_client.describe_reserved_instances() + self.instances = [ + Instance(i) + for i in ec2.instances.filter(Filters=instances_filters) + ] + # self.instances = [Instance(i) for i in ec2.instances.all()] + self.reserved_instances = ec2_client.\ + describe_reserved_instances( + Filters=reserved_instances_filters + ) + # self.reserved_instances = ec2_client + # .describe_reserved_instances() except exceptions.NoCredentialsError: print("Error: no AWS credentials found", file=sys.stderr) sys.exit(1)
ifosch/accloudtant
79e3cf915208ffd58a63412ffc87bd48f8bfb2dd
diff --git a/tests/aws/conftest.py b/tests/aws/conftest.py index 0594830..5a97b58 100644 --- a/tests/aws/conftest.py +++ b/tests/aws/conftest.py @@ -65,6 +65,14 @@ def ec2_resource(): for instance in self.instances: yield MockEC2Instance(instance) + def filter(self, Filters=None): + if Filters is None: + self.all() + if Filters[0]['Name'] == 'instance-state-name': + for instance in self.instances: + if instance['state']['Name'] in Filters[0]['Values']: + yield MockEC2Instance(instance) + class MockEC2Resource(object): def __init__(self, responses): self.responses = responses @@ -94,7 +102,19 @@ def ec2_client(): def describe_instances(self): return self.instances - def describe_reserved_instances(self): + def describe_reserved_instances(self, Filters=None): + final_reserved = {'ReservedInstances': []} + if Filters is None: + final_reserved = self.reserved + else: + filter = Filters[0] + if filter['Name'] == 'state': + final_reserved['ReservedInstances'] = [ + reserved_instance + for reserved_instance + in self.reserved['ReservedInstances'] + if reserved_instance['State'] not in filter['Values'] + ] return self.reserved class MockEC2ClientCall(object): diff --git a/tests/aws/report_running_expected.txt b/tests/aws/report_running_expected.txt new file mode 100644 index 0000000..befecd0 --- /dev/null +++ b/tests/aws/report_running_expected.txt @@ -0,0 +1,8 @@ +Id Name Type AZ OS State Launch time Reserved Current hourly price Renewed hourly price +---------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- ---------------------- ---------------------- +i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes 0.5121 0.3894 +i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes 0.3894 0.3794 +i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes 0.5225 0.389 +i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892 diff --git a/tests/aws/test_reports.py b/tests/aws/test_reports.py index 35fd236..d0f6793 100644 --- a/tests/aws/test_reports.py +++ b/tests/aws/test_reports.py @@ -17,6 +17,10 @@ from dateutil.tz import tzutc import accloudtant.aws.reports +def get_future_date(years=1): + return datetime.datetime.now() + datetime.timedelta(years) + + def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): instances = { 'instances': [{ @@ -232,16 +236,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - 494000, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', @@ -266,16 +261,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - 494000, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233321', @@ -300,15 +286,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233322', @@ -333,15 +311,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): tzinfo=tzutc() ), 'RecurringCharges': [], - 'End': datetime.datetime( - 2016, - 6, - 5, - 6, - 20, - 10, - tzinfo=tzutc() - ), + 'End': get_future_date(), 'CurrencyCode': 'USD', 'OfferingType': 'Medium Utilization', 'ReservedInstancesId': '46a408c7-c33d-422d-af59-28df12233320', @@ -421,7 +391,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): }, }, }, - 'od': '0.767', + 'od': '0.867', 'memoryGiB': '15', 'vCPU': '8', }, @@ -618,7 +588,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): 'best': 0.3892, }, } - expected = open('tests/aws/report_expected.txt', 'r').read() + expected = open('tests/aws/report_running_expected.txt', 'r').read() monkeypatch.setattr('boto3.resource', ec2_resource) ec2_resource.set_responses(instances) @@ -634,6 +604,7 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): print(reports) out, err = capsys.readouterr() + assert(len(reports.instances) == 6) for mock in instances['instances']: mock['current'] = instances_prices[mock['id']]['current'] mock['best'] = instances_prices[mock['id']]['best'] @@ -641,5 +612,4 @@ def test_reports(capsys, monkeypatch, ec2_resource, ec2_client, process_ec2): if instance.id == mock['id']: assert(instance.current == mock['current']) assert(instance.best == mock['best']) - print(out) assert(out == expected)
Iterate over appropriate subsets for performance improvement When generating reports, the code iterates over all instances, and all reserved instances, to get the links between these, the report should iterate over running instances and active reserved instances, only.
0.0
79e3cf915208ffd58a63412ffc87bd48f8bfb2dd
[ "tests/aws/test_reports.py::test_reports" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2016-06-24 12:10:46+00:00
apache-2.0
2,796
ihabunek__pdf417-py-5
diff --git a/.travis.yml b/.travis.yml index a05962b..c5b0492 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,13 +3,15 @@ language: python python: - "2.6" - "2.7" - - "3.2" - "3.3" - "3.4" - "3.5" + - "3.6" - "nightly" install: + # pillow 4 doesn't support py2.6 + - pip install "pillow<4.0.0" - pip install -e . script: py.test diff --git a/README.rst b/README.rst index 98cbb6d..a67bea8 100644 --- a/README.rst +++ b/README.rst @@ -59,6 +59,19 @@ Usage overview: svg = render_svg(codes) # ElementTree object svg.write("barcode.svg") + +Supports strings (unicode in py2) and byte arrays (str in py2): + +.. code-block:: python + + # These two inputs encode to the same code words + encode(u"love 💔") + encode(b"love \xf0\x9f\x92\x94") + + # Default encoding is UTF-8, but you can specify your own + encode(u"love 💔", encoding="utf-8") + + Encoding data ------------- diff --git a/pdf417gen/compaction.py b/pdf417gen/compaction.py index ba401a4..05bde6a 100644 --- a/pdf417gen/compaction.py +++ b/pdf417gen/compaction.py @@ -13,7 +13,8 @@ def compact_numbers(data): Rate compaction: 2.9 bytes per code word """ def compact_chunk(chunk): - value = int("1" + chunk) + number = "".join([chr(x) for x in chunk]) + value = int("1" + number) return to_base(value, 900) compacted_chunks = [compact_chunk(chunk) for chunk in chunks(data, size=44)] @@ -31,7 +32,7 @@ def compact_text_interim(data): def get_submode(char): if char not in CHARACTERS_LOOKUP: - raise ValueError("Cannot encode char: " + char) + raise ValueError("Cannot encode char: {}".format(char)) submodes = CHARACTERS_LOOKUP[char].keys() @@ -41,7 +42,7 @@ def compact_text_interim(data): if submode in submodes: return submode - raise ValueError("Cannot encode char: " + char) + raise ValueError("Cannot encode char: {}".format(char)) # By default, encoding starts with uppercase submode submode = Submode.UPPER @@ -103,7 +104,8 @@ def compact_bytes(data): The chunk is encoded to 5 code words by changing the base from 256 to 900. """ - digits = [ord(i) for i in chunk] + + digits = [i for i in chunk] return switch_base(digits, 256, 900) def compact_incomplete_chunk(chunk): @@ -111,7 +113,7 @@ def compact_bytes(data): The chunk is encoded to 6 code words leaving the base unchanged. """ - return [ord(i) for i in chunk] + return [i for i in chunk] compacted_chunks = [compact_chunk(chunk) for chunk in chunks(data, size=6)] @@ -151,7 +153,7 @@ def compact(data): # Default compaction mode is Text (does not require an initial switch code) function = compact_text - chunk = "" + chunk = [] for char in data: new_function = get_optimal_compactor_fn(char) @@ -159,9 +161,9 @@ def compact(data): if chunk: yield chunk, function - chunk = "" + chunk = [] function = new_function - chunk += char + chunk.append(char) if chunk: yield chunk, function @@ -171,7 +173,7 @@ def compact(data): def get_optimal_compactor_fn(char): - if 48 <= ord(char) <= 57: + if 48 <= char <= 57: return compact_numbers if char in CHARACTERS_LOOKUP: diff --git a/pdf417gen/data.py b/pdf417gen/data.py index 2cf3211..fb59703 100644 --- a/pdf417gen/data.py +++ b/pdf417gen/data.py @@ -5,103 +5,103 @@ MIXED = 'MIXED' PUNCT = 'PUNCT' CHARACTERS_LOOKUP = { - "'": {PUNCT: 28}, - ' ': {UPPER: 26, LOWER: 26, MIXED: 26}, - '!': {PUNCT: 10}, - '#': {MIXED: 15}, - '$': {MIXED: 18, PUNCT: 18}, - '%': {MIXED: 21}, - '&': {MIXED: 10}, - '(': {PUNCT: 23}, - ')': {PUNCT: 24}, - '*': {MIXED: 22, PUNCT: 22}, - '+': {MIXED: 20}, - ',': {MIXED: 13, PUNCT: 13}, - '-': {MIXED: 16, PUNCT: 16}, - '.': {MIXED: 17, PUNCT: 17}, - '/': {MIXED: 19, PUNCT: 19}, - '0': {MIXED: 0}, - '1': {MIXED: 1}, - '2': {MIXED: 2}, - '3': {MIXED: 3}, - '4': {MIXED: 4}, - '5': {MIXED: 5}, - '6': {MIXED: 6}, - '7': {MIXED: 7}, - '8': {MIXED: 8}, - '9': {MIXED: 9}, - ':': {MIXED: 14, PUNCT: 14}, - ';': {PUNCT: 0}, - '<': {PUNCT: 1}, - '=': {MIXED: 23}, - '>': {PUNCT: 2}, - '?': {PUNCT: 25}, - '@': {PUNCT: 3}, - '[': {PUNCT: 4}, - '\\': {PUNCT: 5}, - '\n': {PUNCT: 15}, - '\r': {MIXED: 11, PUNCT: 11}, - '\t': {MIXED: 12, PUNCT: 12}, - ']': {PUNCT: 6}, - '^': {MIXED: 24}, - '_': {PUNCT: 7}, - '`': {PUNCT: 8}, - 'a': {LOWER: 0}, - 'A': {UPPER: 0}, - 'b': {LOWER: 1}, - 'B': {UPPER: 1}, - 'c': {LOWER: 2}, - 'C': {UPPER: 2}, - 'd': {LOWER: 3}, - 'D': {UPPER: 3}, - 'e': {LOWER: 4}, - 'E': {UPPER: 4}, - 'f': {LOWER: 5}, - 'F': {UPPER: 5}, - 'g': {LOWER: 6, PUNCT: 20}, - 'G': {UPPER: 6}, - 'h': {LOWER: 7}, - 'H': {UPPER: 7}, - 'i': {LOWER: 8}, - 'I': {UPPER: 8}, - 'j': {LOWER: 9}, - 'J': {UPPER: 9}, - 'k': {LOWER: 10}, - 'K': {UPPER: 10}, - 'l': {LOWER: 11}, - 'L': {UPPER: 11}, - 'm': {LOWER: 12}, - 'M': {UPPER: 12}, - 'n': {LOWER: 13}, - 'N': {UPPER: 13}, - 'o': {LOWER: 14}, - 'O': {UPPER: 14}, - 'p': {LOWER: 15}, - 'P': {UPPER: 15}, - 'q': {LOWER: 16}, - 'Q': {UPPER: 16}, - 'r': {LOWER: 17}, - 'R': {UPPER: 17}, - 's': {LOWER: 18}, - 'S': {UPPER: 18}, - 't': {LOWER: 19}, - 'T': {UPPER: 19}, - 'u': {LOWER: 20}, - 'U': {UPPER: 20}, - 'v': {LOWER: 21}, - 'V': {UPPER: 21}, - 'w': {LOWER: 22}, - 'W': {UPPER: 22}, - 'x': {LOWER: 23}, - 'X': {UPPER: 23}, - 'y': {LOWER: 24}, - 'Y': {UPPER: 24}, - 'z': {LOWER: 25}, - 'Z': {UPPER: 25}, - '{': {PUNCT: 26}, - '|': {PUNCT: 21}, - '}': {PUNCT: 27}, - '~': {PUNCT: 9}, + 9: {MIXED: 12, PUNCT: 12}, # \t + 10: {PUNCT: 15}, # \n + 13: {MIXED: 11, PUNCT: 11}, # \r + 32: {UPPER: 26, LOWER: 26, MIXED: 26}, # SPACE + 33: {PUNCT: 10}, # ! + 35: {MIXED: 15}, # # + 36: {MIXED: 18, PUNCT: 18}, # $ + 37: {MIXED: 21}, # % + 38: {MIXED: 10}, # & + 39: {PUNCT: 28}, # ' + 40: {PUNCT: 23}, # ( + 41: {PUNCT: 24}, # ) + 42: {MIXED: 22, PUNCT: 22}, # * + 43: {MIXED: 20}, # + + 44: {MIXED: 13, PUNCT: 13}, # , + 45: {MIXED: 16, PUNCT: 16}, # - + 46: {MIXED: 17, PUNCT: 17}, # . + 47: {MIXED: 19, PUNCT: 19}, # / + 48: {MIXED: 0}, # 0 + 49: {MIXED: 1}, # 1 + 50: {MIXED: 2}, # 2 + 51: {MIXED: 3}, # 3 + 52: {MIXED: 4}, # 4 + 53: {MIXED: 5}, # 5 + 54: {MIXED: 6}, # 6 + 55: {MIXED: 7}, # 7 + 56: {MIXED: 8}, # 8 + 57: {MIXED: 9}, # 9 + 58: {MIXED: 14, PUNCT: 14}, # : + 59: {PUNCT: 0}, # ; + 60: {PUNCT: 1}, # < + 61: {MIXED: 23}, # = + 62: {PUNCT: 2}, # > + 63: {PUNCT: 25}, # ? + 64: {PUNCT: 3}, # @ + 65: {UPPER: 0}, # A + 66: {UPPER: 1}, # B + 67: {UPPER: 2}, # C + 68: {UPPER: 3}, # D + 69: {UPPER: 4}, # E + 70: {UPPER: 5}, # F + 71: {UPPER: 6}, # G + 72: {UPPER: 7}, # H + 73: {UPPER: 8}, # I + 74: {UPPER: 9}, # J + 75: {UPPER: 10}, # K + 76: {UPPER: 11}, # L + 77: {UPPER: 12}, # M + 78: {UPPER: 13}, # N + 79: {UPPER: 14}, # O + 80: {UPPER: 15}, # P + 81: {UPPER: 16}, # Q + 82: {UPPER: 17}, # R + 83: {UPPER: 18}, # S + 84: {UPPER: 19}, # T + 85: {UPPER: 20}, # U + 86: {UPPER: 21}, # V + 87: {UPPER: 22}, # W + 88: {UPPER: 23}, # X + 89: {UPPER: 24}, # Y + 90: {UPPER: 25}, # Z + 91: {PUNCT: 4}, # [ + 92: {PUNCT: 5}, # \ + 93: {PUNCT: 6}, # ] + 94: {MIXED: 24}, # ^ + 95: {PUNCT: 7}, # _ + 96: {PUNCT: 8}, # ` + 97: {LOWER: 0}, # a + 98: {LOWER: 1}, # b + 99: {LOWER: 2}, # c + 100: {LOWER: 3}, # d + 101: {LOWER: 4}, # e + 102: {LOWER: 5}, # f + 103: {LOWER: 6, PUNCT: 20}, # g + 104: {LOWER: 7}, # h + 105: {LOWER: 8}, # i + 106: {LOWER: 9}, # j + 107: {LOWER: 10}, # k + 108: {LOWER: 11}, # l + 109: {LOWER: 12}, # m + 110: {LOWER: 13}, # n + 111: {LOWER: 14}, # o + 112: {LOWER: 15}, # p + 113: {LOWER: 16}, # q + 114: {LOWER: 17}, # r + 115: {LOWER: 18}, # s + 116: {LOWER: 19}, # t + 117: {LOWER: 20}, # u + 118: {LOWER: 21}, # v + 119: {LOWER: 22}, # w + 120: {LOWER: 23}, # x + 121: {LOWER: 24}, # y + 122: {LOWER: 25}, # z + 123: {PUNCT: 26}, # { + 124: {PUNCT: 21}, # | + 125: {PUNCT: 27}, # } + 126: {PUNCT: 9}, # ~ } # Switch codes between submodes diff --git a/pdf417gen/encoding.py b/pdf417gen/encoding.py index 7e7b05b..23f9451 100644 --- a/pdf417gen/encoding.py +++ b/pdf417gen/encoding.py @@ -2,10 +2,10 @@ from __future__ import division import math -from .codes import map_code_word -from .compaction import compact -from .error_correction import compute_error_correction_code_words -from .util import chunks +from pdf417gen.codes import map_code_word +from pdf417gen.compaction import compact +from pdf417gen.error_correction import compute_error_correction_code_words +from pdf417gen.util import chunks, to_bytes START_CHARACTER = 0x1fea8 STOP_CHARACTER = 0x3fa29 @@ -19,8 +19,11 @@ MAX_CODE_WORDS = 928 MIN_ROWS = 3 MAX_ROWS = 90 +# Encoding to use when given a string and encoding is not specified +DEFAULT_ENCODING = 'utf-8' -def encode(data, columns=6, security_level=2): + +def encode(data, columns=6, security_level=2, encoding=DEFAULT_ENCODING): if columns < 1 or columns > 30: raise ValueError("'columns' must be between 1 and 30. Given: %r" % columns) @@ -29,8 +32,11 @@ def encode(data, columns=6, security_level=2): num_cols = columns # Nomenclature + # Prepare input + data_bytes = to_bytes(data, encoding) + # Convert data to code words and split into rows - code_words = encode_high(data, num_cols, security_level) + code_words = encode_high(data_bytes, num_cols, security_level) rows = list(chunks(code_words, num_cols)) return list(encode_rows(rows, num_cols, security_level)) diff --git a/pdf417gen/util.py b/pdf417gen/util.py index 6e8d648..2d60d28 100644 --- a/pdf417gen/util.py +++ b/pdf417gen/util.py @@ -1,8 +1,10 @@ from __future__ import division +from builtins import bytes, str + def from_base(digits, base): - return sum([v * (base ** (len(digits) - k - 1)) for k, v in enumerate(digits)]) + return sum(v * (base ** (len(digits) - k - 1)) for k, v in enumerate(digits)) def to_base(value, base): @@ -23,3 +25,13 @@ def chunks(data, size): """Generator which chunks data into 6 bytes batches""" for i in range(0, len(data), size): yield data[i:i+size] + + +def to_bytes(input, encoding='utf-8'): + if isinstance(input, bytes): + return bytes(input) + + if isinstance(input, str): + return bytes(input, encoding) + + raise ValueError("Invalid input, expected string or bytes") diff --git a/setup.py b/setup.py index 5c0f1f0..df9c459 100644 --- a/setup.py +++ b/setup.py @@ -24,9 +24,6 @@ setup( 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.0', - 'Programming Language :: Python :: 3.1', - 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5',
ihabunek/pdf417-py
d921ef72f562176e74855550c316a173859e1b99
diff --git a/tests/test_compaction.py b/tests/test_compaction.py index f9036d0..e3db65c 100644 --- a/tests/test_compaction.py +++ b/tests/test_compaction.py @@ -1,58 +1,56 @@ -from pdf417gen.compaction import compact, compact_bytes, compact_numbers, compact_text, compact_text_interim - - -# def test_byte_encoder_can_encode(): -# enc = ByteEncoder() -# # Can encode any byte from 0 to 255 -# for x in range(0, 255): -# assert enc.can_encode(chr(x)) - +from pdf417gen.encoding import to_bytes +from pdf417gen.compaction import ( + compact, compact_bytes, compact_numbers, compact_text, compact_text_interim) def test_byte_compactor(): - assert list(compact_bytes("alcool")) == [163, 238, 432, 766, 244] - assert list(compact_bytes("alcoolique")) == [163, 238, 432, 766, 244, 105, 113, 117, 101] - + def do_compact(str): + return list(compact_bytes(to_bytes(str))) -# def test_text_encoder_can_encode(): -# enc = TextEncoder() -# # Can encode ASCII 9, 10, 13, 32, 33 and 35-126 -# # TODO: should be able to encode double quote (ASCII 34), but doesn't currently -# for x in range(0, 255): -# can_encode = x in [9, 10, 13, 32, 33] or x in range(35, 127) -# assert enc.can_encode(chr(x)) == can_encode + assert do_compact("alcool") == [163, 238, 432, 766, 244] + assert do_compact("alcoolique") == [163, 238, 432, 766, 244, 105, 113, 117, 101] def test_text_compactor_interim(): + def do_compact(str): + return list(compact_text_interim(to_bytes(str))) + # Upper transitions - assert compact_text_interim("Ff") == [5, 27, 5] - assert compact_text_interim("F#") == [5, 28, 15] - assert compact_text_interim("F!") == [5, 28, 25, 10] + assert do_compact("Ff") == [5, 27, 5] + assert do_compact("F#") == [5, 28, 15] + assert do_compact("F!") == [5, 28, 25, 10] # Lower transitions - assert compact_text_interim("fF") == [27, 5, 28, 28, 5] - assert compact_text_interim("f#") == [27, 5, 28, 15] - assert compact_text_interim("f!") == [27, 5, 28, 25, 10] + assert do_compact("fF") == [27, 5, 28, 28, 5] + assert do_compact("f#") == [27, 5, 28, 15] + assert do_compact("f!") == [27, 5, 28, 25, 10] def test_text_compactor(): - assert compact_text("Super ") == [567, 615, 137, 809] - assert compact_text("Super !") == [567, 615, 137, 808, 760] + def do_compact(str): + return list(compact_text(to_bytes(str))) + + assert do_compact("Super ") == [567, 615, 137, 809] + assert do_compact("Super !") == [567, 615, 137, 808, 760] def test_numbers_compactor(): - assert list(compact_numbers("01234")) == [112, 434] + numbers = [ord(x) for x in "01234"] + assert list(compact_numbers(numbers)) == [112, 434] def test_compact(): + def do_compact(str): + return list(compact(to_bytes(str))) + # When starting with text, the first code word does not need to be the switch - assert list(compact("ABC123")) == [1, 89, 902, 1, 223] + assert do_compact("ABC123") == [1, 89, 902, 1, 223] # When starting with numbers, we do need to switch - assert list(compact("123ABC")) == [902, 1, 223, 900, 1, 89] + assert do_compact("123ABC") == [902, 1, 223, 900, 1, 89] # Also with bytes - assert list(compact("\x0B")) == [901, 11] + assert do_compact(b"\x0B") == [901, 11] # Alternate bytes switch code when number of bytes is divisble by 6 - assert list(compact("\x0B\x0B\x0B\x0B\x0B\x0B")) == [924, 18, 455, 694, 754, 291] + assert do_compact(b"\x0B\x0B\x0B\x0B\x0B\x0B") == [924, 18, 455, 694, 754, 291] diff --git a/tests/test_encode.py b/tests/test_encode.py index 6d2b5d1..756f99b 100644 --- a/tests/test_encode.py +++ b/tests/test_encode.py @@ -1,4 +1,6 @@ -from pdf417gen.encoding import encode, encode_high +# -*- coding: utf-8 -*- + +from pdf417gen.encoding import encode, encode_high, to_bytes TEST_DATA = '\n'.join([ 'HRVHUB30', @@ -34,7 +36,7 @@ def test_encode_high(): 570, 805, 26, 30, 536, 314, 104, 634, 865, 479, 900, 713, 846, 93, 59, 313, 515, 294, 844] - assert encode_high(TEST_DATA, 6, 2) == expected + assert encode_high(to_bytes(TEST_DATA), 6, 2) == expected def test_encode_low(): @@ -69,3 +71,17 @@ def test_encode_low(): ] assert list(encode(TEST_DATA, 6, 2)) == expected + + +def test_encode_unicode(): + # These two should encode to the same string + uc = u"love 💔" + by = b"love \xf0\x9f\x92\x94" + + expected = [ + [130728, 120256, 108592, 115526, 126604, 103616, 66594, 126094, 128318, 260649], + [130728, 125456, 83916, 107396, 83872, 97968, 77702, 98676, 128352, 260649], + [130728, 86496, 128114, 90190, 98038, 72124, 72814, 81040, 86256, 260649]] + + assert encode(uc) == expected + assert encode(by) == expected
Python3 isn't supported Hi I found support declaration in setup.py. But it is impossible to encode something like b'\x01'
0.0
d921ef72f562176e74855550c316a173859e1b99
[ "tests/test_compaction.py::test_byte_compactor", "tests/test_compaction.py::test_text_compactor_interim", "tests/test_compaction.py::test_text_compactor", "tests/test_compaction.py::test_numbers_compactor", "tests/test_compaction.py::test_compact", "tests/test_encode.py::test_encode_high", "tests/test_encode.py::test_encode_low", "tests/test_encode.py::test_encode_unicode" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-02-11 13:04:11+00:00
mit
2,797
ikalchev__HAP-python-243
diff --git a/pyhap/camera.py b/pyhap/camera.py index 5a6fca8..155aad9 100644 --- a/pyhap/camera.py +++ b/pyhap/camera.py @@ -682,8 +682,8 @@ class Camera(Accessory): SETUP_TYPES['ADDRESS'], res_address_tlv, SETUP_TYPES['VIDEO_SRTP_PARAM'], video_srtp_tlv, SETUP_TYPES['AUDIO_SRTP_PARAM'], audio_srtp_tlv, - SETUP_TYPES['VIDEO_SSRC'], video_ssrc, - SETUP_TYPES['AUDIO_SSRC'], audio_ssrc, + SETUP_TYPES['VIDEO_SSRC'], struct.pack('<I', video_ssrc), + SETUP_TYPES['AUDIO_SSRC'], struct.pack('<I', audio_ssrc), to_base64=True) self.sessions[session_id] = { diff --git a/pyhap/hap_server.py b/pyhap/hap_server.py index ae863e5..abef1be 100644 --- a/pyhap/hap_server.py +++ b/pyhap/hap_server.py @@ -893,6 +893,8 @@ class HAPServer(socketserver.ThreadingMixIn, except (OSError, socket.timeout) as e: self._handle_sock_timeout(client_address, e) logger.debug('Connection timeout') + except Exception as e: + logger.debug('finish_request: %s', e, exc_info=True) finally: logger.debug('Cleaning connection to %s', client_address) conn_sock = self.connections.pop(client_address, None)
ikalchev/HAP-python
feba43826d144e439a92eb8260863a6cea96b7fa
diff --git a/tests/test_camera.py b/tests/test_camera.py index f3424d7..c25fa88 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -76,7 +76,7 @@ def test_setup_endpoints(mock_driver): .get_characteristic('SetupEndpoints') setup_endpoints.client_update_value(set_endpoint_req) - assert setup_endpoints.get_value() == set_endpoint_res + assert setup_endpoints.get_value()[:171] == set_endpoint_res[:171] def test_set_selected_stream_start_stop(mock_driver):
Unable to encode TLV value for camera When trying to create a camera I'm getting this exception: ``` [hap_server] Exception in set_characteristics: object of type 'int' has no len() Traceback (most recent call last): File "/home/homekit/camera_test/venv/lib/python3.7/site-packages/pyhap/hap_server.py", line 559, in handle_set_characteristics self.client_address) File "/home/homekit/camera_test/venv/lib/python3.7/site-packages/pyhap/accessory_driver.py", line 660, in set_characteristics char.client_update_value(cq[HAP_REPR_VALUE], client_addr) File "/home/homekit/camera_test/venv/lib/python3.7/site-packages/pyhap/characteristic.py", line 215, in client_update_value self.setter_callback(value) File "/home/homekit/camera_test/venv/lib/python3.7/site-packages/pyhap/camera.py", line 694, in set_endpoints to_base64=True) File "/home/homekit/camera_test/venv/lib/python3.7/site-packages/pyhap/tlv.py", line 27, in encode total_length = len(data) ``` I think I can see how this has happened in camera.py as tlv.encode is (I think) expecting to receive bytes, but it's being passed video_ssrc/audo_ssrc which are integers. ``` video_ssrc = int.from_bytes(os.urandom(3), byteorder="big") audio_ssrc = int.from_bytes(os.urandom(3), byteorder="big") <snip> response_tlv = tlv.encode( SETUP_TYPES['SESSION_ID'], session_id.bytes, SETUP_TYPES['STATUS'], SETUP_STATUS['SUCCESS'], SETUP_TYPES['ADDRESS'], res_address_tlv, SETUP_TYPES['VIDEO_SRTP_PARAM'], video_srtp_tlv, SETUP_TYPES['AUDIO_SRTP_PARAM'], audio_srtp_tlv, SETUP_TYPES['VIDEO_SSRC'], video_ssrc, SETUP_TYPES['AUDIO_SSRC'], audio_ssrc, to_base64=True) ``` This used to work though so I'm a bit confused about what has changed! I'm using python 3.7.5 and HAP-python==2.8.2
0.0
feba43826d144e439a92eb8260863a6cea96b7fa
[ "tests/test_camera.py::test_setup_endpoints" ]
[ "tests/test_camera.py::test_init", "tests/test_camera.py::test_set_selected_stream_start_stop" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-04-18 13:14:15+00:00
apache-2.0
2,798
ikalchev__HAP-python-335
diff --git a/pyhap/accessory.py b/pyhap/accessory.py index 4896c32..b59eb73 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -368,7 +368,7 @@ class Bridge(Accessory): async def run(self): """Schedule tasks for each of the accessories' run method.""" for acc in self.accessories.values(): - await self.driver.async_add_job(acc.run) + self.driver.async_add_job(acc.run) async def stop(self): """Calls stop() on all contained accessories."""
ikalchev/HAP-python
0974827fef61c287351855c49f95dfacfd6237de
diff --git a/tests/test_accessory.py b/tests/test_accessory.py index c4eebe0..7989eeb 100644 --- a/tests/test_accessory.py +++ b/tests/test_accessory.py @@ -1,4 +1,5 @@ """Tests for pyhap.accessory.""" +import asyncio from io import StringIO from unittest.mock import patch @@ -6,6 +7,7 @@ import pytest from pyhap import accessory from pyhap.accessory import Accessory, Bridge +from pyhap.accessory_driver import AccessoryDriver from pyhap.const import ( CATEGORY_CAMERA, CATEGORY_TARGET_CONTROLLER, @@ -22,6 +24,21 @@ from . import AsyncMock # ##################### +class TestAccessory(Accessory): + """An accessory that keeps track of if its stopped.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._stopped = False + + async def stop(self): + self._stopped = True + + @property + def stopped(self): + return self._stopped + + def test_acc_init(mock_driver): Accessory(mock_driver, "Test Accessory") @@ -383,15 +400,27 @@ def test_to_hap(mock_driver): @pytest.mark.asyncio -async def test_bridge_run_stop(mock_driver): - mock_driver.async_add_job = AsyncMock() - bridge = Bridge(mock_driver, "Test Bridge") - acc = Accessory(mock_driver, "Test Accessory", aid=2) - assert acc.available is True - bridge.add_accessory(acc) - acc2 = Accessory(mock_driver, "Test Accessory 2") - bridge.add_accessory(acc2) +async def test_bridge_run_stop(): + with patch( + "pyhap.accessory_driver.HAPServer.async_stop", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.HAPServer.async_start", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.Zeroconf" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.persist" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.load" + ): + driver = AccessoryDriver(loop=asyncio.get_event_loop()) + bridge = Bridge(driver, "Test Bridge") + acc = TestAccessory(driver, "Test Accessory", aid=2) + assert acc.available is True + bridge.add_accessory(acc) + acc2 = TestAccessory(driver, "Test Accessory 2") + bridge.add_accessory(acc2) - await bridge.run() - assert mock_driver.async_add_job.called - await bridge.stop() + await bridge.run() + await bridge.stop() + assert acc.stopped is True + assert acc2.stopped is True diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index 39f163a..34dd942 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -39,6 +39,38 @@ CHAR_PROPS = { } +class AsyncIntervalAccessory(Accessory): + """An accessory increments a counter at interval.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._counter = 0 + + @Accessory.run_at_interval(0.001) # Run this method every 0.001 seconds + async def run(self): + self._counter += 1 + + @property + def counter(self): + return self._counter + + +class SyncIntervalAccessory(Accessory): + """An accessory increments a counter at interval.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._counter = 0 + + @Accessory.run_at_interval(0.001) # Run this method every 0.001 seconds + def run(self): # pylint: disable=invalid-overridden-method + self._counter += 1 + + @property + def counter(self): + return self._counter + + class UnavailableAccessory(Accessory): """An accessory that is not available.""" @@ -670,3 +702,67 @@ async def test_call_async_add_job_with_callback(driver): await asyncio.sleep(0) await asyncio.sleep(0) assert called is True + + [email protected] +async def test_bridge_with_multiple_async_run_at_interval_accessories(): + with patch( + "pyhap.accessory_driver.HAPServer.async_stop", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.HAPServer.async_start", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.Zeroconf" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.persist" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.load" + ): + driver = AccessoryDriver(loop=asyncio.get_event_loop()) + bridge = Bridge(driver, "mybridge") + acc = AsyncIntervalAccessory(driver, "TestAcc", aid=2) + acc2 = AsyncIntervalAccessory(driver, "TestAcc2", aid=3) + acc3 = AsyncIntervalAccessory(driver, "TestAcc3", aid=4) + bridge.add_accessory(acc) + bridge.add_accessory(acc2) + bridge.add_accessory(acc3) + driver.add_accessory(bridge) + driver.start_service() + await asyncio.sleep(0.5) + assert not driver.loop.is_closed() + await driver.async_stop() + + assert acc.counter > 2 + assert acc2.counter > 2 + assert acc3.counter > 2 + + [email protected] +async def test_bridge_with_multiple_sync_run_at_interval_accessories(): + with patch( + "pyhap.accessory_driver.HAPServer.async_stop", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.HAPServer.async_start", new_callable=AsyncMock + ), patch( + "pyhap.accessory_driver.Zeroconf" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.persist" + ), patch( + "pyhap.accessory_driver.AccessoryDriver.load" + ): + driver = AccessoryDriver(loop=asyncio.get_event_loop()) + bridge = Bridge(driver, "mybridge") + acc = SyncIntervalAccessory(driver, "TestAcc", aid=2) + acc2 = SyncIntervalAccessory(driver, "TestAcc2", aid=3) + acc3 = SyncIntervalAccessory(driver, "TestAcc3", aid=4) + bridge.add_accessory(acc) + bridge.add_accessory(acc2) + bridge.add_accessory(acc3) + driver.add_accessory(bridge) + driver.start_service() + await asyncio.sleep(0.5) + assert not driver.loop.is_closed() + await driver.async_stop() + + assert acc.counter > 2 + assert acc2.counter > 2 + assert acc3.counter > 2 diff --git a/tests/test_hap_server.py b/tests/test_hap_server.py index 8941878..062042c 100644 --- a/tests/test_hap_server.py +++ b/tests/test_hap_server.py @@ -43,6 +43,9 @@ async def test_we_can_connect(): assert server.connections == {} _, port = sock.getsockname() _, writer = await asyncio.open_connection("127.0.0.1", port) + # flush out any call_soon + for _ in range(3): + await asyncio.sleep(0) assert server.connections != {} server.async_stop() writer.close() diff --git a/tests/test_tlv.py b/tests/test_tlv.py index 28260c6..8e9f300 100644 --- a/tests/test_tlv.py +++ b/tests/test_tlv.py @@ -1,6 +1,7 @@ """Tests for pyhap.tlv.""" import pytest + from pyhap import tlv
HAP-Python 3.4.0 breaks bridge with multiple accessories I have a bridge that consists of two accessories: - Temperature & humidity sensor - Motion sensor Everything was working okay with HAP-Python 3.3.0, the behavior described in ikalchev/HAP-python#327 notwithstanding. However, after upgrading to HAP-Python 3.4.0, my motion sensor stopped working. I have an `run()` method defined for each accessory, like below, where it outputs something to the log each time the method is invoked. ```python @Accessory.run_at_interval(5) async def run(self): ... ``` My `get_bridge()` method looks like this: ```python def get_bridge(driver): ''' Call this method to get a Bridge instead of a standalone accessory. ''' bridge = Bridge(driver, 'Study HAP-Python Bridge') bridge.set_info_service( ... ) temp_humid_sensor = TemperatureAndHumiditySensor(driver, 'Temperature & Humidity Sensor') bridge.add_accessory(temp_humid_sensor) motion_sensor = MotionSensor(driver, 'Motion Sensor') bridge.add_accessory(motion_sensor) return bridge ``` So I should see some log entry from each accessory every 5 seconds or so when `run()` is invoked. But with the code as-is, I only see my output from the `temp_humid_sensor` accessory. I still see `DEBUG` log chatter talking about the motion sensor, but nothing from log entry orchestrated in its `run()` method. If I comment out the two lines with the `temp_humid_sensor` and restart the service, then I will see the output from my motion sensor accessory. Also, if I uncomment the two lines and downgrade to HAP-Python 3.3.0, then I once again see output from both accessories every 5 seconds. I will stick with HAP-Python 3.3.0 for now.
0.0
0974827fef61c287351855c49f95dfacfd6237de
[ "tests/test_accessory_driver.py::test_bridge_with_multiple_async_run_at_interval_accessories", "tests/test_accessory_driver.py::test_bridge_with_multiple_sync_run_at_interval_accessories" ]
[ "tests/test_accessory.py::test_acc_init", "tests/test_accessory.py::test_acc_publish_no_broker", "tests/test_accessory.py::test_acc_set_primary_service", "tests/test_accessory.py::test_acc_add_preload_service_without_chars", "tests/test_accessory.py::test_acc_add_preload_service_with_chars", "tests/test_accessory.py::test_bridge_init", "tests/test_accessory.py::test_bridge_add_accessory", "tests/test_accessory.py::test_bridge_n_add_accessory_bridge_aid", "tests/test_accessory.py::test_bridge_n_add_accessory_dup_aid", "tests/test_accessory.py::test_setup_message_without_qr_code", "tests/test_accessory.py::test_set_info_service", "tests/test_accessory.py::test_set_info_service_empty", "tests/test_accessory.py::test_set_info_service_invalid_serial", "tests/test_accessory.py::test_get_characteristic", "tests/test_accessory.py::test_cannot_add_bridge_to_bridge", "tests/test_accessory.py::test_to_hap", "tests/test_accessory.py::test_bridge_run_stop", "tests/test_accessory_driver.py::test_auto_add_aid_mac", "tests/test_accessory_driver.py::test_not_standalone_aid", "tests/test_accessory_driver.py::test_persist_load", "tests/test_accessory_driver.py::test_persist_cannot_write", "tests/test_accessory_driver.py::test_external_zeroconf", "tests/test_accessory_driver.py::test_service_callbacks", "tests/test_accessory_driver.py::test_service_callbacks_partial_failure", "tests/test_accessory_driver.py::test_mixing_service_char_callbacks_partial_failure", "tests/test_accessory_driver.py::test_start_from_sync", "tests/test_accessory_driver.py::test_start_stop_sync_acc", "tests/test_accessory_driver.py::test_start_stop_async_acc", "tests/test_accessory_driver.py::test_start_from_async_stop_from_executor", "tests/test_accessory_driver.py::test_start_without_accessory", "tests/test_accessory_driver.py::test_send_events", "tests/test_accessory_driver.py::test_async_subscribe_client_topic", "tests/test_accessory_driver.py::test_start_service_and_update_config", "tests/test_accessory_driver.py::test_call_add_job_with_none", "tests/test_accessory_driver.py::test_call_async_add_job_with_coroutine", "tests/test_accessory_driver.py::test_call_async_add_job_with_callback", "tests/test_hap_server.py::test_we_can_start_stop", "tests/test_hap_server.py::test_we_can_connect", "tests/test_hap_server.py::test_idle_connection_cleanup", "tests/test_hap_server.py::test_push_event", "tests/test_tlv.py::test_tlv_round_trip", "tests/test_tlv.py::test_tlv_invalid_pairs" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-03-08 07:21:06+00:00
apache-2.0
2,799
ikalchev__HAP-python-360
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 9478080..579fa74 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.6, 3.7, 3.8, 3.9, "3.10.0-alpha.5"] + python-version: [3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v1 diff --git a/pyhap/accessory.py b/pyhap/accessory.py index b59eb73..3acc3ce 100644 --- a/pyhap/accessory.py +++ b/pyhap/accessory.py @@ -283,7 +283,7 @@ class Accessory: # Driver - def publish(self, value, sender, sender_client_addr=None): + def publish(self, value, sender, sender_client_addr=None, immediate=False): """Append AID and IID of the sender and forward it to the driver. Characteristics call this method to send updates. @@ -299,7 +299,7 @@ class Accessory: HAP_REPR_IID: self.iid_manager.get_iid(sender), HAP_REPR_VALUE: value, } - self.driver.publish(acc_data, sender_client_addr) + self.driver.publish(acc_data, sender_client_addr, immediate) class Bridge(Accessory): diff --git a/pyhap/accessory_driver.py b/pyhap/accessory_driver.py index 8ca9540..fa67658 100644 --- a/pyhap/accessory_driver.py +++ b/pyhap/accessory_driver.py @@ -467,7 +467,7 @@ class AccessoryDriver: for topic in client_topics: self.async_subscribe_client_topic(client, topic, subscribe=False) - def publish(self, data, sender_client_addr=None): + def publish(self, data, sender_client_addr=None, immediate=False): """Publishes an event to the client. The publishing occurs only if the current client is subscribed to the topic for @@ -482,14 +482,14 @@ class AccessoryDriver: return if threading.current_thread() == self.tid: - self.async_send_event(topic, data, sender_client_addr) + self.async_send_event(topic, data, sender_client_addr, immediate) return self.loop.call_soon_threadsafe( - self.async_send_event, topic, data, sender_client_addr + self.async_send_event, topic, data, sender_client_addr, immediate ) - def async_send_event(self, topic, data, sender_client_addr): + def async_send_event(self, topic, data, sender_client_addr, immediate): """Send an event to a client. Must be called in the event loop @@ -513,8 +513,8 @@ class AccessoryDriver: client_addr, ) continue - logger.debug("Sending event to client: %s", client_addr) - pushed = self.http_server.push_event(data, client_addr) + logger.debug("Sending event to client: %s, immediate: %s", client_addr, immediate) + pushed = self.http_server.push_event(data, client_addr, immediate) if not pushed: logger.debug( "Could not send event to %s, probably stale socket.", client_addr diff --git a/pyhap/characteristic.py b/pyhap/characteristic.py index 8693923..3d7a020 100644 --- a/pyhap/characteristic.py +++ b/pyhap/characteristic.py @@ -6,6 +6,9 @@ a temperature measuring or a device status. """ import logging +from uuid import UUID + + from pyhap.const import ( HAP_PERMISSION_READ, HAP_REPR_DESC, @@ -78,6 +81,20 @@ PROP_VALID_VALUES = "ValidValues" PROP_NUMERIC = (PROP_MAX_VALUE, PROP_MIN_VALUE, PROP_MIN_STEP, PROP_UNIT) +CHAR_BUTTON_EVENT = UUID("00000126-0000-1000-8000-0026BB765291") +CHAR_PROGRAMMABLE_SWITCH_EVENT = UUID("00000073-0000-1000-8000-0026BB765291") + + +IMMEDIATE_NOTIFY = { + CHAR_BUTTON_EVENT, # Button Event + CHAR_PROGRAMMABLE_SWITCH_EVENT, # Programmable Switch Event +} + +# Special case, Programmable Switch Event always have a null value +ALWAYS_NULL = { + CHAR_PROGRAMMABLE_SWITCH_EVENT, # Programmable Switch Event +} + class CharacteristicError(Exception): """Generic exception class for characteristic errors.""" @@ -138,6 +155,9 @@ class Characteristic: def _get_default_value(self): """Return default value for format.""" + if self.type_id in ALWAYS_NULL: + return None + if self.properties.get(PROP_VALID_VALUES): return min(self.properties[PROP_VALID_VALUES].values()) @@ -198,6 +218,10 @@ class Characteristic: if valid_values: self.properties[PROP_VALID_VALUES] = valid_values + if self.type_id in ALWAYS_NULL: + self.value = None + return + try: self.value = self.to_valid_value(self.value) except ValueError: @@ -224,9 +248,12 @@ class Characteristic: """ logger.debug("set_value: %s to %s", self.display_name, value) value = self.to_valid_value(value) + changed = self.value != value self.value = value - if should_notify and self.broker: + if changed and should_notify and self.broker: self.notify() + if self.type_id in ALWAYS_NULL: + self.value = None def client_update_value(self, value, sender_client_addr=None): """Called from broker for value change in Home app. @@ -239,11 +266,15 @@ class Characteristic: value, sender_client_addr, ) + changed = self.value != value self.value = value - self.notify(sender_client_addr) + if changed: + self.notify(sender_client_addr) if self.setter_callback: # pylint: disable=not-callable self.setter_callback(value) + if self.type_id in ALWAYS_NULL: + self.value = None def notify(self, sender_client_addr=None): """Notify clients about a value change. Sends the value. @@ -251,7 +282,8 @@ class Characteristic: .. seealso:: accessory.publish .. seealso:: accessory_driver.publish """ - self.broker.publish(self.value, self, sender_client_addr) + immediate = self.type_id in IMMEDIATE_NOTIFY + self.broker.publish(self.value, self, sender_client_addr, immediate) # pylint: disable=invalid-name def to_HAP(self): diff --git a/pyhap/hap_protocol.py b/pyhap/hap_protocol.py index 623c5d9..a84b2ac 100644 --- a/pyhap/hap_protocol.py +++ b/pyhap/hap_protocol.py @@ -9,9 +9,12 @@ import time from cryptography.exceptions import InvalidTag import h11 +from pyhap.accessory import get_topic +from pyhap.const import HAP_REPR_AID, HAP_REPR_IID + from .hap_crypto import HAPCrypto -from .hap_handler import HAPResponse, HAPServerHandler from .hap_event import create_hap_event +from .hap_handler import HAPResponse, HAPServerHandler logger = logging.getLogger(__name__) @@ -23,6 +26,8 @@ HIGH_WRITE_BUFFER_SIZE = 2 ** 19 # reopen homekit. IDLE_CONNECTION_TIMEOUT_SECONDS = 90 * 60 * 60 +EVENT_COALESCE_TIME_WINDOW = 0.5 + class HAPServerProtocol(asyncio.Protocol): """A asyncio.Protocol implementing the HAP protocol.""" @@ -42,6 +47,7 @@ class HAPServerProtocol(asyncio.Protocol): self.last_activity = None self.hap_crypto = None + self._event_timer = None self._event_queue = [] def connection_lost(self, exc: Exception) -> None: @@ -90,10 +96,15 @@ class HAPServerProtocol(asyncio.Protocol): del self.connections[self.peername] self.transport.close() - def queue_event(self, data: dict) -> None: + def queue_event(self, data: dict, immediate: bool) -> None: """Queue an event for sending.""" self._event_queue.append(data) - self.loop.call_soon(self._process_events) + if immediate: + self.loop.call_soon(self._send_events) + elif not self._event_timer: + self._event_timer = self.loop.call_later( + EVENT_COALESCE_TIME_WINDOW, self._send_events + ) def send_response(self, response: HAPResponse) -> None: """Send a HAPResponse object.""" @@ -162,17 +173,31 @@ class HAPServerProtocol(asyncio.Protocol): if self.conn.our_state is h11.MUST_CLOSE: self.finish_and_close() return - self._send_events() except h11.ProtocolError as protocol_ex: self._handle_invalid_conn_state(protocol_ex) def _send_events(self): """Send any pending events.""" + if self._event_timer: + self._event_timer.cancel() + self._event_timer = None if not self._event_queue: return - self.write(create_hap_event(self._event_queue)) + subscribed_events = self._event_queue_with_active_subscriptions() + if subscribed_events: + self.write(create_hap_event(subscribed_events)) self._event_queue = [] + def _event_queue_with_active_subscriptions(self): + """Remove any topics that have been unsubscribed after the event was generated.""" + topics = self.accessory_driver.topics + return [ + event + for event in self._event_queue + if self.peername + in topics.get(get_topic(event[HAP_REPR_AID], event[HAP_REPR_IID]), []) + ] + def _process_one_event(self) -> bool: """Process one http event.""" event = self.conn.next_event() diff --git a/pyhap/hap_server.py b/pyhap/hap_server.py index 28d2587..5016355 100644 --- a/pyhap/hap_server.py +++ b/pyhap/hap_server.py @@ -70,7 +70,7 @@ class HAPServer: self.server.close() self.connections.clear() - def push_event(self, data, client_addr): + def push_event(self, data, client_addr, immediate=False): """Queue an event to the current connection with the provided data. :param data: The charateristic changes @@ -86,5 +86,5 @@ class HAPServer: if hap_server_protocol is None: logger.debug("No socket for %s", client_addr) return False - hap_server_protocol.queue_event(data) + hap_server_protocol.queue_event(data, immediate) return True
ikalchev/HAP-python
1124babe01ca8276fd77cdd4cc328a34c5c7bf75
diff --git a/tests/conftest.py b/tests/conftest.py index 957924d..20476b5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -49,7 +49,7 @@ class MockDriver: def __init__(self): self.loader = Loader() - def publish(self, data, client_addr=None): + def publish(self, data, client_addr=None, immediate=False): pass def add_job(self, target, *args): # pylint: disable=no-self-use diff --git a/tests/test_accessory.py b/tests/test_accessory.py index 23a032d..2c20d06 100644 --- a/tests/test_accessory.py +++ b/tests/test_accessory.py @@ -12,6 +12,7 @@ from pyhap.const import ( CATEGORY_CAMERA, CATEGORY_TARGET_CONTROLLER, CATEGORY_TELEVISION, + HAP_REPR_VALUE, STANDALONE_AID, ) from pyhap.service import Service @@ -460,3 +461,18 @@ async def test_bridge_run_stop(): await bridge.stop() assert acc.stopped is True assert acc2.stopped is True + + +def test_acc_with_(mock_driver): + """Test ProgrammableSwitchEvent is always None.""" + acc = Accessory(mock_driver, "Test Accessory") + serv_stateless_switch = acc.add_preload_service("StatelessProgrammableSwitch") + char_doorbell_detected_switch = serv_stateless_switch.configure_char( + "ProgrammableSwitchEvent", + value=0, + valid_values={"SinglePress": 0}, + ) + char_doorbell_detected_switch.client_update_value(0) + assert char_doorbell_detected_switch.to_HAP()[HAP_REPR_VALUE] is None + char_doorbell_detected_switch.client_update_value(None) + assert char_doorbell_detected_switch.to_HAP()[HAP_REPR_VALUE] is None diff --git a/tests/test_accessory_driver.py b/tests/test_accessory_driver.py index dc1db1d..a07281f 100644 --- a/tests/test_accessory_driver.py +++ b/tests/test_accessory_driver.py @@ -555,7 +555,7 @@ def test_send_events(driver): class HapServerMock: pushed_events = set() - def push_event(self, bytedata, client_addr): + def push_event(self, bytedata, client_addr, immediate): self.pushed_events.add((bytedata, client_addr)) if client_addr == "client2": return False @@ -567,7 +567,7 @@ def test_send_events(driver): driver.http_server = HapServerMock() driver.loop = LoopMock() driver.topics = {"mocktopic": {"client1", "client2", "client3"}} - driver.async_send_event("mocktopic", "bytedata", "client1") + driver.async_send_event("mocktopic", "bytedata", "client1", True) # Only client2 and client3 get the event when client1 sent it assert driver.http_server.get_pushed_events() == { diff --git a/tests/test_characteristic.py b/tests/test_characteristic.py index 2d6e871..4882de8 100644 --- a/tests/test_characteristic.py +++ b/tests/test_characteristic.py @@ -1,5 +1,5 @@ """Tests for pyhap.characteristic.""" -from unittest.mock import ANY, Mock, patch +from unittest.mock import ANY, MagicMock, Mock, patch from uuid import uuid1 import pytest @@ -8,6 +8,7 @@ from pyhap.characteristic import ( HAP_FORMAT_DEFAULTS, HAP_FORMAT_INT, HAP_PERMISSION_READ, + CHAR_PROGRAMMABLE_SWITCH_EVENT, Characteristic, ) @@ -123,6 +124,62 @@ def test_set_value(): assert char.value == 3 assert mock_notify.call_count == 1 + # No change should not generate another notify + char.set_value(3) + assert char.value == 3 + assert mock_notify.call_count == 1 + + +def test_set_value_immediate(): + """Test setting the value of a characteristic generates immediate notify.""" + char = Characteristic( + display_name="Switch Event", + type_id=CHAR_PROGRAMMABLE_SWITCH_EVENT, + properties=PROPERTIES.copy(), + ) + assert char.value is None + + publish_mock = Mock() + char.broker = Mock(publish=publish_mock) + + char.set_value(0) + assert char.value is None + publish_mock.assert_called_with(0, char, None, True) + + char.set_value(1) + assert char.value is None + publish_mock.assert_called_with(1, char, None, True) + + +def test_switch_event_always_serializes_to_null_via_set_value(): + """Test that the switch event char is always null.""" + char = Characteristic( + display_name="Switch Event", + type_id=CHAR_PROGRAMMABLE_SWITCH_EVENT, + properties=PROPERTIES.copy(), + ) + assert char.value is None + char.broker = MagicMock() + + assert char.to_HAP()["value"] is None + char.set_value(1) + assert char.to_HAP()["value"] is None + + +def test_switch_event_always_serializes_to_null_via_client_update_value(): + """Test that the switch event char is always null.""" + char = Characteristic( + display_name="Switch Event", + type_id=CHAR_PROGRAMMABLE_SWITCH_EVENT, + properties=PROPERTIES.copy(), + ) + assert char.value is None + char.broker = MagicMock() + + assert char.to_HAP()["value"] is None + char.client_update_value(1) + assert char.to_HAP()["value"] is None + def test_client_update_value(): """Test updating the characteristic value with call from the driver.""" @@ -143,6 +200,27 @@ def test_client_update_value(): char.client_update_value(9, "mock_client_addr") assert char.value == 9 mock_notify.assert_called_once_with("mock_client_addr") + assert len(mock_notify.mock_calls) == 1 + + # Same value, do not call again + char.client_update_value(9, "mock_client_addr") + assert char.value == 9 + assert len(mock_notify.mock_calls) == 1 + + # New value, should notify + char.client_update_value(12, "mock_client_addr") + assert char.value == 12 + assert len(mock_notify.mock_calls) == 2 + + # Same value, do not call again + char.client_update_value(12, "mock_client_addr") + assert char.value == 12 + assert len(mock_notify.mock_calls) == 2 + + # New value, should notify + char.client_update_value(9, "mock_client_addr") + assert char.value == 9 + assert len(mock_notify.mock_calls) == 3 def test_notify(): @@ -155,11 +233,11 @@ def test_notify(): with patch.object(char, "broker") as mock_broker: char.notify() - mock_broker.publish.assert_called_with(2, char, None) + mock_broker.publish.assert_called_with(2, char, None, False) with patch.object(char, "broker") as mock_broker: char.notify("mock_client_addr") - mock_broker.publish.assert_called_with(2, char, "mock_client_addr") + mock_broker.publish.assert_called_with(2, char, "mock_client_addr", False) def test_to_HAP_numberic(): diff --git a/tests/test_hap_server.py b/tests/test_hap_server.py index 58b3457..e13a836 100644 --- a/tests/test_hap_server.py +++ b/tests/test_hap_server.py @@ -83,7 +83,7 @@ async def test_idle_connection_cleanup(): async def test_push_event(driver): """Test we can create and send an event.""" addr_info = ("1.2.3.4", 1234) - server = hap_server.HAPServer(addr_info, driver) + server = hap_server.HAPServer(("127.0.01", 5555), driver) server.loop = asyncio.get_event_loop() hap_events = [] @@ -94,17 +94,58 @@ async def test_push_event(driver): server.loop, server.connections, server.accessory_handler ) hap_server_protocol.write = _save_event + hap_server_protocol.peername = addr_info + server.accessory_handler.topics["1.33"] = {addr_info} + server.accessory_handler.topics["2.33"] = {addr_info} + server.accessory_handler.topics["3.33"] = {addr_info} - assert server.push_event({"aid": 1}, addr_info) is False + assert server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info) is False await asyncio.sleep(0) server.connections[addr_info] = hap_server_protocol - assert server.push_event({"aid": 1}, addr_info) is True - assert server.push_event({"aid": 2}, addr_info) is True - assert server.push_event({"aid": 3}, addr_info) is True + assert ( + server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info, True) + is True + ) + assert ( + server.push_event({"aid": 2, "iid": 33, "value": False}, addr_info, True) + is True + ) + assert ( + server.push_event({"aid": 3, "iid": 33, "value": False}, addr_info, True) + is True + ) await asyncio.sleep(0) assert hap_events == [ - b"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: 51\r\n\r\n" - b'{"characteristics":[{"aid":1},{"aid":2},{"aid":3}]}' + b"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: 120\r\n\r\n" + b'{"characteristics":[{"aid":1,"iid":33,"value":false},' + b'{"aid":2,"iid":33,"value":false},{"aid":3,"iid":33,"value":false}]}' + ] + + hap_events = [] + assert ( + server.push_event({"aid": 1, "iid": 33, "value": False}, addr_info, False) + is True + ) + assert ( + server.push_event({"aid": 2, "iid": 33, "value": False}, addr_info, False) + is True + ) + assert ( + server.push_event({"aid": 3, "iid": 33, "value": False}, addr_info, False) + is True + ) + + await asyncio.sleep(0) + assert hap_events == [] + + # Ensure that a the event is not sent if its unsubscribed during + # the coalesce delay + server.accessory_handler.topics["1.33"].remove(addr_info) + + await asyncio.sleep(0.55) + assert hap_events == [ + b"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: 87\r\n\r\n" + b'{"characteristics":[{"aid":2,"iid":33,"value":false},{"aid":3,"iid":33,"value":false}]}' ]
Events are sent for characteristics that have not changed When `client_update_value` or `set_value` is called an event is generated even when the internal state hasn't changed. For cameras motion sensors this can result in 100x of events per hour per camera
0.0
1124babe01ca8276fd77cdd4cc328a34c5c7bf75
[ "tests/test_accessory.py::test_acc_init", "tests/test_accessory.py::test_acc_publish_no_broker", "tests/test_accessory.py::test_acc_set_primary_service", "tests/test_accessory.py::test_acc_add_preload_service_without_chars", "tests/test_accessory.py::test_acc_add_preload_service_with_chars", "tests/test_accessory.py::test_bridge_init", "tests/test_accessory.py::test_bridge_add_accessory", "tests/test_accessory.py::test_bridge_n_add_accessory_bridge_aid", "tests/test_accessory.py::test_bridge_n_add_accessory_dup_aid", "tests/test_accessory.py::test_setup_message_without_qr_code", "tests/test_accessory.py::test_set_info_service", "tests/test_accessory.py::test_set_info_service_empty", "tests/test_accessory.py::test_set_info_service_invalid_serial", "tests/test_accessory.py::test_get_characteristic", "tests/test_accessory.py::test_cannot_add_bridge_to_bridge", "tests/test_accessory.py::test_to_hap", "tests/test_accessory.py::test_bridge_run_stop", "tests/test_accessory.py::test_acc_with_", "tests/test_accessory_driver.py::test_auto_add_aid_mac", "tests/test_accessory_driver.py::test_not_standalone_aid", "tests/test_accessory_driver.py::test_persist_load", "tests/test_accessory_driver.py::test_persist_cannot_write", "tests/test_accessory_driver.py::test_external_zeroconf", "tests/test_accessory_driver.py::test_service_callbacks", "tests/test_accessory_driver.py::test_service_callbacks_partial_failure", "tests/test_accessory_driver.py::test_mixing_service_char_callbacks_partial_failure", "tests/test_accessory_driver.py::test_start_from_sync", "tests/test_accessory_driver.py::test_start_stop_sync_acc", "tests/test_accessory_driver.py::test_start_stop_async_acc", "tests/test_accessory_driver.py::test_start_from_async_stop_from_executor", "tests/test_accessory_driver.py::test_start_without_accessory", "tests/test_accessory_driver.py::test_send_events", "tests/test_accessory_driver.py::test_async_subscribe_client_topic", "tests/test_accessory_driver.py::test_mdns_name_sanity[--h", "tests/test_accessory_driver.py::test_mdns_name_sanity[--H", "tests/test_accessory_driver.py::test_mdns_name_sanity[-", "tests/test_accessory_driver.py::test_start_service_and_update_config", "tests/test_accessory_driver.py::test_call_add_job_with_none", "tests/test_accessory_driver.py::test_call_async_add_job_with_coroutine", "tests/test_accessory_driver.py::test_call_async_add_job_with_callback", "tests/test_accessory_driver.py::test_bridge_with_multiple_async_run_at_interval_accessories", "tests/test_accessory_driver.py::test_bridge_with_multiple_sync_run_at_interval_accessories", "tests/test_characteristic.py::test_repr", "tests/test_characteristic.py::test_default_value", "tests/test_characteristic.py::test_get_default_value", "tests/test_characteristic.py::test_to_valid_value", "tests/test_characteristic.py::test_override_properties_properties", "tests/test_characteristic.py::test_override_properties_valid_values", "tests/test_characteristic.py::test_override_properties_error", "tests/test_characteristic.py::test_set_value", "tests/test_characteristic.py::test_set_value_immediate", "tests/test_characteristic.py::test_switch_event_always_serializes_to_null_via_set_value", "tests/test_characteristic.py::test_switch_event_always_serializes_to_null_via_client_update_value", "tests/test_characteristic.py::test_client_update_value", "tests/test_characteristic.py::test_notify", "tests/test_characteristic.py::test_to_HAP_numberic", "tests/test_characteristic.py::test_to_HAP_valid_values", "tests/test_characteristic.py::test_to_HAP_string", "tests/test_characteristic.py::test_to_HAP_bool", "tests/test_characteristic.py::test_from_dict", "tests/test_hap_server.py::test_we_can_start_stop", "tests/test_hap_server.py::test_we_can_connect", "tests/test_hap_server.py::test_idle_connection_cleanup", "tests/test_hap_server.py::test_push_event" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-24 04:48:18+00:00
apache-2.0
2,800
ikalchev__HAP-python-458
diff --git a/pyhap/hap_handler.py b/pyhap/hap_handler.py index 103cdc1..399bfcc 100644 --- a/pyhap/hap_handler.py +++ b/pyhap/hap_handler.py @@ -606,6 +606,13 @@ class HAPServerHandler: data = tlv.encode(HAP_TLV_TAGS.SEQUENCE_NUM, HAP_TLV_STATES.M4) self._send_tlv_pairing_response(data) + + if client_uuid not in self.state.uuid_to_bytes: + # We are missing the raw bytes for this client, so we need to + # add them to the state and persist so list pairings works. + self.state.uuid_to_bytes[client_uuid] = client_username + self.accessory_handler.async_persist() + assert self.response is not None # nosec self.response.shared_key = self.enc_context["shared_key"] self.is_encrypted = True
ikalchev/HAP-python
d9243b6abfbde59c03560b10f4a926a39ab1e1e2
diff --git a/tests/test_hap_handler.py b/tests/test_hap_handler.py index 52b2ff7..75cd0d4 100644 --- a/tests/test_hap_handler.py +++ b/tests/test_hap_handler.py @@ -57,7 +57,7 @@ def test_list_pairings_unencrypted(driver: AccessoryDriver): } -def test_list_pairings(driver): +def test_list_pairings(driver: AccessoryDriver): """Verify an encrypted list pairings request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -117,7 +117,7 @@ def test_list_pairings_multiple(driver: AccessoryDriver): } -def test_add_pairing_admin(driver): +def test_add_pairing_admin(driver: AccessoryDriver): """Verify an encrypted add pairing request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -148,7 +148,7 @@ def test_add_pairing_admin(driver): assert driver.state.is_admin(CLIENT2_UUID) -def test_add_pairing_user(driver): +def test_add_pairing_user(driver: AccessoryDriver): """Verify an encrypted add pairing request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -221,7 +221,7 @@ def test_add_pairing_user(driver): assert not driver.state.is_admin(CLIENT2_UUID) -def test_remove_pairing(driver): +def test_remove_pairing(driver: AccessoryDriver): """Verify an encrypted remove pairing request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -272,7 +272,7 @@ def test_remove_pairing(driver): assert driver.state.paired is False -def test_non_admin_pairings_request(driver): +def test_non_admin_pairings_request(driver: AccessoryDriver): """Verify only admins can access pairings.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -296,7 +296,7 @@ def test_non_admin_pairings_request(driver): } -def test_invalid_pairings_request(driver): +def test_invalid_pairings_request(driver: AccessoryDriver): """Verify an encrypted invalid pairings request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -317,7 +317,7 @@ def test_invalid_pairings_request(driver): handler.handle_pairings() -def test_pair_verify_one(driver): +def test_pair_verify_one(driver: AccessoryDriver): """Verify an unencrypted pair verify one.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -344,7 +344,7 @@ def test_pair_verify_one(driver): ) -def test_pair_verify_one_not_paired(driver): +def test_pair_verify_one_not_paired(driver: AccessoryDriver): """Verify an unencrypted pair verify one.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -369,7 +369,7 @@ def test_pair_verify_one_not_paired(driver): } -def test_pair_verify_two_invaild_state(driver): +def test_pair_verify_two_invalid_state(driver: AccessoryDriver): """Verify an unencrypted pair verify two.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -413,7 +413,7 @@ def test_pair_verify_two_invaild_state(driver): } -def test_pair_verify_two_missing_signature(driver): +def test_pair_verify_two_missing_signature(driver: AccessoryDriver): """Verify a pair verify two with a missing signature.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -466,7 +466,90 @@ def test_pair_verify_two_missing_signature(driver): } -def test_pair_verify_two_success(driver): +def test_pair_verify_two_success_raw_uuid_bytes_missing(driver: AccessoryDriver): + """Verify a pair verify two populated missing raw bytes.""" + driver.add_accessory(Accessory(driver, "TestAcc")) + client_private_key = ed25519.Ed25519PrivateKey.generate() + client_public_key = client_private_key.public_key() + + client_public_key_bytes = client_public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + handler = hap_handler.HAPServerHandler(driver, "peername") + handler.is_encrypted = False + driver.pair(CLIENT_UUID_BYTES, client_public_key_bytes, HAP_PERMISSIONS.ADMIN) + + # We used to not save the raw bytes of the username, so we need to + # remove the entry to simulate that. + del driver.state.uuid_to_bytes[CLIENT_UUID] + + assert CLIENT_UUID in driver.state.paired_clients + + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M1, + hap_handler.HAP_TLV_TAGS.PUBLIC_KEY, + client_public_key_bytes, + ) + handler.handle_pair_verify() + + tlv_objects = tlv.decode(response.body) + + assert ( + tlv_objects[hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM] + == hap_handler.HAP_TLV_STATES.M2 + ) + raw_accessory_public_key = tlv_objects[hap_handler.HAP_TLV_TAGS.PUBLIC_KEY] + + server_public_key: x25519.X25519PublicKey = handler.enc_context["public_key"] + expected_raw_public_key = server_public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + assert raw_accessory_public_key == expected_raw_public_key + + assert client_public_key_bytes == handler.enc_context["client_public"] + + material = client_public_key_bytes + CLIENT_UUID_BYTES + raw_accessory_public_key + client_proof = client_private_key.sign(material) + + unencrypted_data = tlv.encode( + hap_handler.HAP_TLV_TAGS.USERNAME, + CLIENT_UUID_BYTES, + hap_handler.HAP_TLV_TAGS.PROOF, + client_proof, + ) + cipher = ChaCha20Poly1305(handler.enc_context["pre_session_key"]) + encrypted_data = cipher.encrypt( + hap_handler.HAPServerHandler.PVERIFY_2_NONCE, bytes(unencrypted_data), b"" + ) + + response = hap_handler.HAPResponse() + handler.response = response + handler.request_body = tlv.encode( + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM, + hap_handler.HAP_TLV_STATES.M3, + hap_handler.HAP_TLV_TAGS.ENCRYPTED_DATA, + encrypted_data, + ) + handler.handle_pair_verify() + + tlv_objects = tlv.decode(response.body) + + assert tlv_objects == { + hap_handler.HAP_TLV_TAGS.SEQUENCE_NUM: hap_handler.HAP_TLV_STATES.M4, + } + assert handler.is_encrypted is True + assert handler.client_uuid == CLIENT_UUID + # Verify we saved the raw bytes of the username + assert driver.state.uuid_to_bytes[CLIENT_UUID] == CLIENT_UUID_BYTES + + +def test_pair_verify_two_success(driver: AccessoryDriver): """Verify a pair verify two.""" driver.add_accessory(Accessory(driver, "TestAcc")) client_private_key = ed25519.Ed25519PrivateKey.generate() @@ -480,6 +563,7 @@ def test_pair_verify_two_success(driver): handler = hap_handler.HAPServerHandler(driver, "peername") handler.is_encrypted = False driver.pair(CLIENT_UUID_BYTES, client_public_key_bytes, HAP_PERMISSIONS.ADMIN) + assert CLIENT_UUID in driver.state.paired_clients response = hap_handler.HAPResponse() @@ -540,9 +624,10 @@ def test_pair_verify_two_success(driver): } assert handler.is_encrypted is True assert handler.client_uuid == CLIENT_UUID + assert driver.state.uuid_to_bytes[CLIENT_UUID] == CLIENT_UUID_BYTES -def test_invalid_pairing_request(driver): +def test_invalid_pairing_request(driver: AccessoryDriver): """Verify an unencrypted pair verify with an invalid sequence fails.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -563,7 +648,7 @@ def test_invalid_pairing_request(driver): handler.handle_pair_verify() -def test_handle_set_handle_set_characteristics_unencrypted(driver): +def test_handle_set_handle_set_characteristics_unencrypted(driver: AccessoryDriver): """Verify an unencrypted set_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -582,7 +667,7 @@ def test_handle_set_handle_set_characteristics_unencrypted(driver): assert response.status_code == 401 -def test_handle_set_handle_set_characteristics_encrypted(driver): +def test_handle_set_handle_set_characteristics_encrypted(driver: AccessoryDriver): """Verify an encrypted set_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -602,7 +687,9 @@ def test_handle_set_handle_set_characteristics_encrypted(driver): assert response.body == b"" -def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare(driver): +def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics with a missing prepare.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -624,7 +711,9 @@ def test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare(dri assert b"-70410" in response.body -def test_handle_set_handle_set_characteristics_encrypted_with_prepare(driver): +def test_handle_set_handle_set_characteristics_encrypted_with_prepare( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics with a prepare.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -654,7 +743,9 @@ def test_handle_set_handle_set_characteristics_encrypted_with_prepare(driver): assert response.body == b"" -def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare(driver): +def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics with multiple prepares.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -690,7 +781,7 @@ def test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare(d assert response.body == b"" -def test_handle_set_handle_encrypted_with_invalid_prepare(driver): +def test_handle_set_handle_encrypted_with_invalid_prepare(driver: AccessoryDriver): """Verify an encrypted set_characteristics with a prepare missing the ttl.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -710,7 +801,9 @@ def test_handle_set_handle_encrypted_with_invalid_prepare(driver): assert response.body == b'{"status":-70410}' -def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl(driver): +def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics with a prepare expired.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -740,7 +833,9 @@ def test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl(driver assert b"-70410" in response.body -def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid(driver): +def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics with wrong pid.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -770,7 +865,7 @@ def test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid(driver): assert b"-70410" in response.body -def test_handle_set_handle_prepare_not_encrypted(driver): +def test_handle_set_handle_prepare_not_encrypted(driver: AccessoryDriver): """Verify an non-encrypted set_characteristics with a prepare.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -789,7 +884,9 @@ def test_handle_set_handle_prepare_not_encrypted(driver): assert response.status_code == 401 -def test_handle_set_handle_set_characteristics_encrypted_with_exception(driver): +def test_handle_set_handle_set_characteristics_encrypted_with_exception( + driver: AccessoryDriver, +): """Verify an encrypted set_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -814,7 +911,7 @@ def test_handle_set_handle_set_characteristics_encrypted_with_exception(driver): assert b"-70402" in response.body -def test_handle_snapshot_encrypted_non_existant_accessory(driver): +def test_handle_snapshot_encrypted_non_existant_accessory(driver: AccessoryDriver): """Verify an encrypted snapshot with non-existant accessory.""" bridge = Bridge(driver, "Test Bridge") driver.add_accessory(bridge) @@ -829,7 +926,7 @@ def test_handle_snapshot_encrypted_non_existant_accessory(driver): handler.handle_resource() -def test_attempt_to_pair_when_already_paired(driver): +def test_attempt_to_pair_when_already_paired(driver: AccessoryDriver): """Verify we respond with unavailable if already paired.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -853,7 +950,7 @@ def test_attempt_to_pair_when_already_paired(driver): } -def test_handle_get_characteristics_encrypted(driver): +def test_handle_get_characteristics_encrypted(driver: AccessoryDriver): """Verify an encrypted get_characteristics.""" acc = Accessory(driver, "TestAcc", aid=1) assert acc.aid == 1 @@ -890,7 +987,7 @@ def test_handle_get_characteristics_encrypted(driver): assert decoded_response["characteristics"][0]["status"] == -70402 -def test_invalid_pairing_two(driver): +def test_invalid_pairing_two(driver: AccessoryDriver): """Verify we respond with error with invalid request.""" driver.add_accessory(Accessory(driver, "TestAcc")) @@ -919,7 +1016,7 @@ def test_invalid_pairing_two(driver): } -def test_invalid_pairing_three(driver): +def test_invalid_pairing_three(driver: AccessoryDriver): """Verify we respond with error with invalid request.""" driver.add_accessory(Accessory(driver, "TestAcc"))
Stopped working after upgrading to iOS 17 I have configured a bridge and a single door accessory in home assistant. They stopped working after updating to iOS 17 my AppleTV & iPhone. I removed them both from iOS home app and from Home Assistant and tried to reconfigure them as before, but pairing never succeeds. After some minutes, the iPhone shows a message saying that accessory is not reachable and fails. I am trying to gather the messages from the logs but I recommend avoid upgrading to latest iOS version!
0.0
d9243b6abfbde59c03560b10f4a926a39ab1e1e2
[ "tests/test_hap_handler.py::test_pair_verify_two_success_raw_uuid_bytes_missing" ]
[ "tests/test_hap_handler.py::test_response", "tests/test_hap_handler.py::test_list_pairings_unencrypted", "tests/test_hap_handler.py::test_list_pairings", "tests/test_hap_handler.py::test_list_pairings_multiple", "tests/test_hap_handler.py::test_add_pairing_admin", "tests/test_hap_handler.py::test_add_pairing_user", "tests/test_hap_handler.py::test_remove_pairing", "tests/test_hap_handler.py::test_non_admin_pairings_request", "tests/test_hap_handler.py::test_invalid_pairings_request", "tests/test_hap_handler.py::test_pair_verify_one", "tests/test_hap_handler.py::test_pair_verify_one_not_paired", "tests/test_hap_handler.py::test_pair_verify_two_invalid_state", "tests/test_hap_handler.py::test_pair_verify_two_missing_signature", "tests/test_hap_handler.py::test_pair_verify_two_success", "tests/test_hap_handler.py::test_invalid_pairing_request", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_unencrypted", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_pid_missing_prepare", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_with_prepare", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_with_multiple_prepare", "tests/test_hap_handler.py::test_handle_set_handle_encrypted_with_invalid_prepare", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_with_expired_ttl", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_with_wrong_pid", "tests/test_hap_handler.py::test_handle_set_handle_prepare_not_encrypted", "tests/test_hap_handler.py::test_handle_set_handle_set_characteristics_encrypted_with_exception", "tests/test_hap_handler.py::test_handle_snapshot_encrypted_non_existant_accessory", "tests/test_hap_handler.py::test_attempt_to_pair_when_already_paired", "tests/test_hap_handler.py::test_handle_get_characteristics_encrypted", "tests/test_hap_handler.py::test_invalid_pairing_two", "tests/test_hap_handler.py::test_invalid_pairing_three" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-10-05 10:58:51+00:00
apache-2.0
2,801
ikalnytskyi__picobox-79
diff --git a/docs/index.rst b/docs/index.rst index eff5e2b..12c0e27 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -358,6 +358,15 @@ Release Notes backward incompatible changes will be released along with bumping major version component. +4.1.0 +````` + +(unreleased) + +* Fix a bug when a coroutine function wrapped with ``@picobox.pass_()`` + lost its coroutine function marker, i.e. ``inspect.iscoroutinefunction()`` + returned ``False``. + 4.0.0 ````` diff --git a/pyproject.toml b/pyproject.toml index d3c2d2d..1fdcd19 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,7 +35,7 @@ Bugs = "https://github.com/ikalnytskyi/picobox/issues" source = "vcs" [tool.hatch.envs.test] -dependencies = ["pytest", "flask"] +dependencies = ["pytest", "pytest-asyncio", "flask"] scripts.run = "python -m pytest --strict-markers {args:-vv}" [tool.hatch.envs.lint] diff --git a/src/picobox/_box.py b/src/picobox/_box.py index 3c5aaca..77bed5a 100644 --- a/src/picobox/_box.py +++ b/src/picobox/_box.py @@ -187,7 +187,7 @@ class Box: return fn @functools.wraps(fn) - def wrapper(*args, **kwargs): + def fn_with_dependencies(*args, **kwargs): signature = inspect.signature(fn) arguments = signature.bind_partial(*args, **kwargs) @@ -203,6 +203,14 @@ class Box: kwargs[as_] = self.get(key) return fn(*args, **kwargs) + if inspect.iscoroutinefunction(fn): + + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + return await fn_with_dependencies(*args, **kwargs) + else: + wrapper = fn_with_dependencies + wrapper.__dependencies__ = [(key, as_)] return wrapper
ikalnytskyi/picobox
fbc02ea61d8c65588e9c74724611715920711728
diff --git a/tests/test_box.py b/tests/test_box.py index 9b7cfb4..f37cb4b 100644 --- a/tests/test_box.py +++ b/tests/test_box.py @@ -386,6 +386,27 @@ def test_box_pass_method(args, kwargs, rv, boxclass): assert Foo(*args, **kwargs).x == rv [email protected]() [email protected]( + ("args", "kwargs", "rv"), + [ + ((1,), {}, 1), + ((), {"x": 1}, 1), + ((), {}, 42), + ], +) +async def test_box_pass_coroutine(args, kwargs, rv, boxclass): + testbox = boxclass() + testbox.put("x", 42) + + @testbox.pass_("x") + async def co(x): + return x + + assert inspect.iscoroutinefunction(co) + assert await co(*args, **kwargs) == rv + + @pytest.mark.parametrize( ("args", "kwargs", "rv"), [ @@ -490,6 +511,28 @@ def test_box_pass_optimization_complex(boxclass, request): assert len(fn()) == 3 [email protected]() +async def test_box_pass_optimization_async(boxclass, request): + testbox = boxclass() + testbox.put("a", 1) + testbox.put("b", 1) + testbox.put("d", 1) + + @testbox.pass_("a") + @testbox.pass_("b") + @testbox.pass_("d", as_="c") + async def fn(a, b, c): + backtrace = list( + itertools.dropwhile( + lambda frame: frame[2] != request.function.__name__, + traceback.extract_stack(), + ) + ) + return backtrace[1:-1] + + assert len(await fn()) == 1 + + def test_chainbox_put_changes_box(): testbox = picobox.Box() testchainbox = picobox.ChainBox(testbox) diff --git a/tests/test_stack.py b/tests/test_stack.py index a6be870..3570268 100644 --- a/tests/test_stack.py +++ b/tests/test_stack.py @@ -1,5 +1,6 @@ """Test picobox's stack interface.""" +import inspect import itertools import sys import traceback @@ -449,6 +450,28 @@ def test_box_pass_method(boxclass, teststack, args, kwargs, rv): assert Foo(*args, **kwargs).x == rv [email protected]() [email protected]( + ("args", "kwargs", "rv"), + [ + ((1,), {}, 1), + ((), {"x": 1}, 1), + ((), {}, 42), + ], +) +async def test_box_pass_coroutine(boxclass, teststack, args, kwargs, rv): + testbox = boxclass() + testbox.put("x", 42) + + @teststack.pass_("x") + async def co(x): + return x + + with teststack.push(testbox): + assert inspect.iscoroutinefunction(co) + assert await co(*args, **kwargs) == rv + + @pytest.mark.parametrize( ("args", "kwargs", "rv"), [ @@ -567,6 +590,29 @@ def test_box_pass_optimization_complex(boxclass, teststack, request): assert len(fn()) == 3 [email protected]() +async def test_box_pass_optimization_async(boxclass, teststack, request): + testbox = boxclass() + testbox.put("a", 1) + testbox.put("b", 1) + testbox.put("d", 1) + + @teststack.pass_("a") + @teststack.pass_("b") + @teststack.pass_("d", as_="c") + async def fn(a, b, c): + backtrace = list( + itertools.dropwhile( + lambda frame: frame[2] != request.function.__name__, + traceback.extract_stack(), + ) + ) + return backtrace[1:-1] + + with teststack.push(testbox): + assert len(await fn()) == 1 + + def test_chainbox_put_changes_box(teststack): testbox = picobox.Box() testchainbox = picobox.ChainBox(testbox)
Add coroutine functions support to `pass_` decorator Currently the `picobox.pass_()` decorator can be successfully applied to coroutine functions, and such a coroutine function can be successfully used. For instance, the following code works as expected: ```python @picobox.pass_("database_session") async def get_movies_by_name(name: str, database_conn: DatabaseSession) -> list[Movie]: return await database_conn.query(...) # ... await get_movies_by_name("The Batman") ``` The `get_movies_by_name` coroutine function, however, lose its coroutine function marker, which may lead to undesired consequences when used with frameworks or libraries that support both sync and async interface, and use `inspect.iscoroutinefunction()` to properly dispatch its execution (e.g. `Starlette`). ```python >>> inspect.iscoroutinefunction(get_movies_by_name) False ```
0.0
fbc02ea61d8c65588e9c74724611715920711728
[ "tests/test_box.py::test_box_pass_coroutine[Box-args0-kwargs0-1]", "tests/test_box.py::test_box_pass_coroutine[Box-args1-kwargs1-1]", "tests/test_box.py::test_box_pass_coroutine[Box-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_coroutine[ChainBox-args0-kwargs0-1]", "tests/test_box.py::test_box_pass_coroutine[ChainBox-args1-kwargs1-1]", "tests/test_box.py::test_box_pass_coroutine[ChainBox-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_optimization_async[Box]", "tests/test_box.py::test_box_pass_optimization_async[ChainBox]", "tests/test_stack.py::test_box_pass_coroutine[Box-teststack0-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_coroutine[Box-teststack0-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_coroutine[Box-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_coroutine[Box-picobox-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_coroutine[Box-picobox-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_coroutine[Box-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-teststack0-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-teststack0-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-picobox-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-picobox-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_coroutine[ChainBox-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_optimization_async[Box-teststack0]", "tests/test_stack.py::test_box_pass_optimization_async[Box-picobox]", "tests/test_stack.py::test_box_pass_optimization_async[ChainBox-teststack0]", "tests/test_stack.py::test_box_pass_optimization_async[ChainBox-picobox]" ]
[ "tests/test_box.py::test_box_put_key[Box-42_0]", "tests/test_box.py::test_box_put_key[Box-42_1]", "tests/test_box.py::test_box_put_key[Box-42.42]", "tests/test_box.py::test_box_put_key[Box-True]", "tests/test_box.py::test_box_put_key[Box-None]", "tests/test_box.py::test_box_put_key[Box-hashable_value5]", "tests/test_box.py::test_box_put_key[Box-hashable_value6]", "tests/test_box.py::test_box_put_key[ChainBox-42_0]", "tests/test_box.py::test_box_put_key[ChainBox-42_1]", "tests/test_box.py::test_box_put_key[ChainBox-42.42]", "tests/test_box.py::test_box_put_key[ChainBox-True]", "tests/test_box.py::test_box_put_key[ChainBox-None]", "tests/test_box.py::test_box_put_key[ChainBox-hashable_value5]", "tests/test_box.py::test_box_put_key[ChainBox-hashable_value6]", "tests/test_box.py::test_box_put_value[Box-42_0]", "tests/test_box.py::test_box_put_value[Box-42_1]", "tests/test_box.py::test_box_put_value[Box-42.42]", "tests/test_box.py::test_box_put_value[Box-True]", "tests/test_box.py::test_box_put_value[Box-None]", "tests/test_box.py::test_box_put_value[Box-any_value5]", "tests/test_box.py::test_box_put_value[Box-any_value6]", "tests/test_box.py::test_box_put_value[Box-any_value7]", "tests/test_box.py::test_box_put_value[Box-any_value8]", "tests/test_box.py::test_box_put_value[Box-any_value9]", "tests/test_box.py::test_box_put_value[Box-<lambda>]", "tests/test_box.py::test_box_put_value[ChainBox-42_0]", "tests/test_box.py::test_box_put_value[ChainBox-42_1]", "tests/test_box.py::test_box_put_value[ChainBox-42.42]", "tests/test_box.py::test_box_put_value[ChainBox-True]", "tests/test_box.py::test_box_put_value[ChainBox-None]", "tests/test_box.py::test_box_put_value[ChainBox-any_value5]", "tests/test_box.py::test_box_put_value[ChainBox-any_value6]", "tests/test_box.py::test_box_put_value[ChainBox-any_value7]", "tests/test_box.py::test_box_put_value[ChainBox-any_value8]", "tests/test_box.py::test_box_put_value[ChainBox-any_value9]", "tests/test_box.py::test_box_put_value[ChainBox-<lambda>]", "tests/test_box.py::test_box_put_factory[Box]", "tests/test_box.py::test_box_put_factory[ChainBox]", "tests/test_box.py::test_box_put_factory_singleton_scope[Box]", "tests/test_box.py::test_box_put_factory_singleton_scope[ChainBox]", "tests/test_box.py::test_box_put_factory_custom_scope[Box]", "tests/test_box.py::test_box_put_factory_custom_scope[ChainBox]", "tests/test_box.py::test_box_put_factory_dependency[Box]", "tests/test_box.py::test_box_put_factory_dependency[ChainBox]", "tests/test_box.py::test_box_put_value_factory_required[Box]", "tests/test_box.py::test_box_put_value_factory_required[ChainBox]", "tests/test_box.py::test_box_put_value_and_factory[Box]", "tests/test_box.py::test_box_put_value_and_factory[ChainBox]", "tests/test_box.py::test_box_put_value_and_scope[Box]", "tests/test_box.py::test_box_put_value_and_scope[ChainBox]", "tests/test_box.py::test_box_get_keyerror[Box]", "tests/test_box.py::test_box_get_keyerror[ChainBox]", "tests/test_box.py::test_box_get_default[Box]", "tests/test_box.py::test_box_get_default[ChainBox]", "tests/test_box.py::test_box_pass_a[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_a[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_a[Box-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_a[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_a[Box-args4-kwargs4-15]", "tests/test_box.py::test_box_pass_a[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_a[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_a[ChainBox-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_a[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_a[ChainBox-args4-kwargs4-15]", "tests/test_box.py::test_box_pass_b[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_b[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_b[Box-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_b[Box-args3-kwargs3-14]", "tests/test_box.py::test_box_pass_b[Box-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_b[Box-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_b[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_b[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_b[ChainBox-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_b[ChainBox-args3-kwargs3-14]", "tests/test_box.py::test_box_pass_b[ChainBox-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_b[ChainBox-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_c[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_c[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_c[Box-args2-kwargs2-13]", "tests/test_box.py::test_box_pass_c[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_c[Box-args4-kwargs4-13]", "tests/test_box.py::test_box_pass_c[Box-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_c[Box-args6-kwargs6-13]", "tests/test_box.py::test_box_pass_c[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_c[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_c[ChainBox-args2-kwargs2-13]", "tests/test_box.py::test_box_pass_c[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_c[ChainBox-args4-kwargs4-13]", "tests/test_box.py::test_box_pass_c[ChainBox-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_c[ChainBox-args6-kwargs6-13]", "tests/test_box.py::test_box_pass_c_default[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_c_default[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_c_default[Box-args2-kwargs2-13]", "tests/test_box.py::test_box_pass_c_default[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_c_default[Box-args4-kwargs4-13]", "tests/test_box.py::test_box_pass_c_default[Box-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_c_default[Box-args6-kwargs6-13]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args2-kwargs2-13]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args4-kwargs4-13]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_c_default[ChainBox-args6-kwargs6-13]", "tests/test_box.py::test_box_pass_ab[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_ab[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_ab[Box-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_ab[Box-args3-kwargs3-104]", "tests/test_box.py::test_box_pass_ab[Box-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_ab[Box-args5-kwargs5-104]", "tests/test_box.py::test_box_pass_ab[Box-args6-kwargs6-15]", "tests/test_box.py::test_box_pass_ab[Box-args7-kwargs7-113]", "tests/test_box.py::test_box_pass_ab[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_ab[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_ab[ChainBox-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_ab[ChainBox-args3-kwargs3-104]", "tests/test_box.py::test_box_pass_ab[ChainBox-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_ab[ChainBox-args5-kwargs5-104]", "tests/test_box.py::test_box_pass_ab[ChainBox-args6-kwargs6-15]", "tests/test_box.py::test_box_pass_ab[ChainBox-args7-kwargs7-113]", "tests/test_box.py::test_box_pass_bc[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_bc[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_bc[Box-args2-kwargs2-103]", "tests/test_box.py::test_box_pass_bc[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_bc[Box-args4-kwargs4-103]", "tests/test_box.py::test_box_pass_bc[Box-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_bc[Box-args6-kwargs6-111]", "tests/test_box.py::test_box_pass_bc[Box-args7-kwargs7-6]", "tests/test_box.py::test_box_pass_bc[Box-args8-kwargs8-103]", "tests/test_box.py::test_box_pass_bc[Box-args9-kwargs9-14]", "tests/test_box.py::test_box_pass_bc[Box-args10-kwargs10-111]", "tests/test_box.py::test_box_pass_bc[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_bc[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_bc[ChainBox-args2-kwargs2-103]", "tests/test_box.py::test_box_pass_bc[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_bc[ChainBox-args4-kwargs4-103]", "tests/test_box.py::test_box_pass_bc[ChainBox-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_bc[ChainBox-args6-kwargs6-111]", "tests/test_box.py::test_box_pass_bc[ChainBox-args7-kwargs7-6]", "tests/test_box.py::test_box_pass_bc[ChainBox-args8-kwargs8-103]", "tests/test_box.py::test_box_pass_bc[ChainBox-args9-kwargs9-14]", "tests/test_box.py::test_box_pass_bc[ChainBox-args10-kwargs10-111]", "tests/test_box.py::test_box_pass_ac[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_ac[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_ac[Box-args2-kwargs2-103]", "tests/test_box.py::test_box_pass_ac[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_ac[Box-args4-kwargs4-103]", "tests/test_box.py::test_box_pass_ac[Box-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_ac[Box-args6-kwargs6-103]", "tests/test_box.py::test_box_pass_ac[Box-args7-kwargs7-15]", "tests/test_box.py::test_box_pass_ac[Box-args8-kwargs8-112]", "tests/test_box.py::test_box_pass_ac[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_ac[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_ac[ChainBox-args2-kwargs2-103]", "tests/test_box.py::test_box_pass_ac[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_ac[ChainBox-args4-kwargs4-103]", "tests/test_box.py::test_box_pass_ac[ChainBox-args5-kwargs5-6]", "tests/test_box.py::test_box_pass_ac[ChainBox-args6-kwargs6-103]", "tests/test_box.py::test_box_pass_ac[ChainBox-args7-kwargs7-15]", "tests/test_box.py::test_box_pass_ac[ChainBox-args8-kwargs8-112]", "tests/test_box.py::test_box_pass_abc[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_abc[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_abc[Box-args2-kwargs2-1003]", "tests/test_box.py::test_box_pass_abc[Box-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_abc[Box-args4-kwargs4-1003]", "tests/test_box.py::test_box_pass_abc[Box-args5-kwargs5-104]", "tests/test_box.py::test_box_pass_abc[Box-args6-kwargs6-1101]", "tests/test_box.py::test_box_pass_abc[Box-args7-kwargs7-6]", "tests/test_box.py::test_box_pass_abc[Box-args8-kwargs8-1003]", "tests/test_box.py::test_box_pass_abc[Box-args9-kwargs9-104]", "tests/test_box.py::test_box_pass_abc[Box-args10-kwargs10-1101]", "tests/test_box.py::test_box_pass_abc[Box-args11-kwargs11-1110]", "tests/test_box.py::test_box_pass_abc[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_abc[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_abc[ChainBox-args2-kwargs2-1003]", "tests/test_box.py::test_box_pass_abc[ChainBox-args3-kwargs3-6]", "tests/test_box.py::test_box_pass_abc[ChainBox-args4-kwargs4-1003]", "tests/test_box.py::test_box_pass_abc[ChainBox-args5-kwargs5-104]", "tests/test_box.py::test_box_pass_abc[ChainBox-args6-kwargs6-1101]", "tests/test_box.py::test_box_pass_abc[ChainBox-args7-kwargs7-6]", "tests/test_box.py::test_box_pass_abc[ChainBox-args8-kwargs8-1003]", "tests/test_box.py::test_box_pass_abc[ChainBox-args9-kwargs9-104]", "tests/test_box.py::test_box_pass_abc[ChainBox-args10-kwargs10-1101]", "tests/test_box.py::test_box_pass_abc[ChainBox-args11-kwargs11-1110]", "tests/test_box.py::test_box_pass_d_as_b[Box-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_d_as_b[Box-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_d_as_b[Box-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_d_as_b[Box-args3-kwargs3-14]", "tests/test_box.py::test_box_pass_d_as_b[Box-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_d_as_b[Box-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args0-kwargs0-6]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args1-kwargs1-6]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args2-kwargs2-6]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args3-kwargs3-14]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args4-kwargs4-6]", "tests/test_box.py::test_box_pass_d_as_b[ChainBox-args5-kwargs5-14]", "tests/test_box.py::test_box_pass_method[Box-args0-kwargs0-1]", "tests/test_box.py::test_box_pass_method[Box-args1-kwargs1-1]", "tests/test_box.py::test_box_pass_method[Box-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_method[ChainBox-args0-kwargs0-1]", "tests/test_box.py::test_box_pass_method[ChainBox-args1-kwargs1-1]", "tests/test_box.py::test_box_pass_method[ChainBox-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_key_type[Box-args0-kwargs0-41]", "tests/test_box.py::test_box_pass_key_type[Box-args1-kwargs1-41]", "tests/test_box.py::test_box_pass_key_type[Box-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_key_type[ChainBox-args0-kwargs0-41]", "tests/test_box.py::test_box_pass_key_type[ChainBox-args1-kwargs1-41]", "tests/test_box.py::test_box_pass_key_type[ChainBox-args2-kwargs2-42]", "tests/test_box.py::test_box_pass_unexpected_argument[Box]", "tests/test_box.py::test_box_pass_unexpected_argument[ChainBox]", "tests/test_box.py::test_box_pass_keyerror[Box]", "tests/test_box.py::test_box_pass_keyerror[ChainBox]", "tests/test_box.py::test_box_pass_optimization[Box]", "tests/test_box.py::test_box_pass_optimization[ChainBox]", "tests/test_box.py::test_box_pass_optimization_complex[Box]", "tests/test_box.py::test_box_pass_optimization_complex[ChainBox]", "tests/test_box.py::test_chainbox_put_changes_box", "tests/test_box.py::test_chainbox_get_chained", "tests/test_box.py::test_chainbox_isinstance_box", "tests/test_box.py::test_chainbox_box_interface[get]", "tests/test_box.py::test_chainbox_box_interface[pass_]", "tests/test_box.py::test_chainbox_box_interface[put]", "tests/test_stack.py::test_box_put_key[Box-teststack0-42_0]", "tests/test_stack.py::test_box_put_key[Box-teststack0-42_1]", "tests/test_stack.py::test_box_put_key[Box-teststack0-42.42]", "tests/test_stack.py::test_box_put_key[Box-teststack0-True]", "tests/test_stack.py::test_box_put_key[Box-teststack0-None]", "tests/test_stack.py::test_box_put_key[Box-teststack0-hashable_value5]", "tests/test_stack.py::test_box_put_key[Box-teststack0-hashable_value6]", "tests/test_stack.py::test_box_put_key[Box-picobox-42_0]", "tests/test_stack.py::test_box_put_key[Box-picobox-42_1]", "tests/test_stack.py::test_box_put_key[Box-picobox-42.42]", "tests/test_stack.py::test_box_put_key[Box-picobox-True]", "tests/test_stack.py::test_box_put_key[Box-picobox-None]", "tests/test_stack.py::test_box_put_key[Box-picobox-hashable_value5]", "tests/test_stack.py::test_box_put_key[Box-picobox-hashable_value6]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-42_0]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-42_1]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-42.42]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-True]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-None]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-hashable_value5]", "tests/test_stack.py::test_box_put_key[ChainBox-teststack0-hashable_value6]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-42_0]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-42_1]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-42.42]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-True]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-None]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-hashable_value5]", "tests/test_stack.py::test_box_put_key[ChainBox-picobox-hashable_value6]", "tests/test_stack.py::test_box_put_value[Box-teststack0-42_0]", "tests/test_stack.py::test_box_put_value[Box-teststack0-42_1]", "tests/test_stack.py::test_box_put_value[Box-teststack0-42.42]", "tests/test_stack.py::test_box_put_value[Box-teststack0-True]", "tests/test_stack.py::test_box_put_value[Box-teststack0-None]", "tests/test_stack.py::test_box_put_value[Box-teststack0-any_value5]", "tests/test_stack.py::test_box_put_value[Box-teststack0-any_value6]", "tests/test_stack.py::test_box_put_value[Box-teststack0-any_value7]", "tests/test_stack.py::test_box_put_value[Box-teststack0-any_value8]", "tests/test_stack.py::test_box_put_value[Box-teststack0-any_value9]", "tests/test_stack.py::test_box_put_value[Box-teststack0-<lambda>]", "tests/test_stack.py::test_box_put_value[Box-picobox-42_0]", "tests/test_stack.py::test_box_put_value[Box-picobox-42_1]", "tests/test_stack.py::test_box_put_value[Box-picobox-42.42]", "tests/test_stack.py::test_box_put_value[Box-picobox-True]", "tests/test_stack.py::test_box_put_value[Box-picobox-None]", "tests/test_stack.py::test_box_put_value[Box-picobox-any_value5]", "tests/test_stack.py::test_box_put_value[Box-picobox-any_value6]", "tests/test_stack.py::test_box_put_value[Box-picobox-any_value7]", "tests/test_stack.py::test_box_put_value[Box-picobox-any_value8]", "tests/test_stack.py::test_box_put_value[Box-picobox-any_value9]", "tests/test_stack.py::test_box_put_value[Box-picobox-<lambda>]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-42_0]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-42_1]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-42.42]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-True]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-None]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-any_value5]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-any_value6]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-any_value7]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-any_value8]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-any_value9]", "tests/test_stack.py::test_box_put_value[ChainBox-teststack0-<lambda>]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-42_0]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-42_1]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-42.42]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-True]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-None]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-any_value5]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-any_value6]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-any_value7]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-any_value8]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-any_value9]", "tests/test_stack.py::test_box_put_value[ChainBox-picobox-<lambda>]", "tests/test_stack.py::test_box_put_factory[Box-teststack0]", "tests/test_stack.py::test_box_put_factory[Box-picobox]", "tests/test_stack.py::test_box_put_factory[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_factory[ChainBox-picobox]", "tests/test_stack.py::test_box_put_factory_singleton_scope[Box-teststack0]", "tests/test_stack.py::test_box_put_factory_singleton_scope[Box-picobox]", "tests/test_stack.py::test_box_put_factory_singleton_scope[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_factory_singleton_scope[ChainBox-picobox]", "tests/test_stack.py::test_box_put_factory_dependency[Box-teststack0]", "tests/test_stack.py::test_box_put_factory_dependency[Box-picobox]", "tests/test_stack.py::test_box_put_factory_dependency[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_factory_dependency[ChainBox-picobox]", "tests/test_stack.py::test_box_put_value_factory_required[Box-teststack0]", "tests/test_stack.py::test_box_put_value_factory_required[Box-picobox]", "tests/test_stack.py::test_box_put_value_factory_required[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_value_factory_required[ChainBox-picobox]", "tests/test_stack.py::test_box_put_value_and_factory[Box-teststack0]", "tests/test_stack.py::test_box_put_value_and_factory[Box-picobox]", "tests/test_stack.py::test_box_put_value_and_factory[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_value_and_factory[ChainBox-picobox]", "tests/test_stack.py::test_box_put_value_and_scope[Box-teststack0]", "tests/test_stack.py::test_box_put_value_and_scope[Box-picobox]", "tests/test_stack.py::test_box_put_value_and_scope[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_value_and_scope[ChainBox-picobox]", "tests/test_stack.py::test_box_put_runtimeerror[Box-teststack0]", "tests/test_stack.py::test_box_put_runtimeerror[Box-picobox]", "tests/test_stack.py::test_box_put_runtimeerror[ChainBox-teststack0]", "tests/test_stack.py::test_box_put_runtimeerror[ChainBox-picobox]", "tests/test_stack.py::test_box_get_value[Box-teststack0-42_0]", "tests/test_stack.py::test_box_get_value[Box-teststack0-42_1]", "tests/test_stack.py::test_box_get_value[Box-teststack0-42.42]", "tests/test_stack.py::test_box_get_value[Box-teststack0-True]", "tests/test_stack.py::test_box_get_value[Box-teststack0-None]", "tests/test_stack.py::test_box_get_value[Box-teststack0-any_value5]", "tests/test_stack.py::test_box_get_value[Box-teststack0-any_value6]", "tests/test_stack.py::test_box_get_value[Box-teststack0-any_value7]", "tests/test_stack.py::test_box_get_value[Box-teststack0-any_value8]", "tests/test_stack.py::test_box_get_value[Box-teststack0-any_value9]", "tests/test_stack.py::test_box_get_value[Box-teststack0-<lambda>]", "tests/test_stack.py::test_box_get_value[Box-picobox-42_0]", "tests/test_stack.py::test_box_get_value[Box-picobox-42_1]", "tests/test_stack.py::test_box_get_value[Box-picobox-42.42]", "tests/test_stack.py::test_box_get_value[Box-picobox-True]", "tests/test_stack.py::test_box_get_value[Box-picobox-None]", "tests/test_stack.py::test_box_get_value[Box-picobox-any_value5]", "tests/test_stack.py::test_box_get_value[Box-picobox-any_value6]", "tests/test_stack.py::test_box_get_value[Box-picobox-any_value7]", "tests/test_stack.py::test_box_get_value[Box-picobox-any_value8]", "tests/test_stack.py::test_box_get_value[Box-picobox-any_value9]", "tests/test_stack.py::test_box_get_value[Box-picobox-<lambda>]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-42_0]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-42_1]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-42.42]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-True]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-None]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-any_value5]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-any_value6]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-any_value7]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-any_value8]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-any_value9]", "tests/test_stack.py::test_box_get_value[ChainBox-teststack0-<lambda>]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-42_0]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-42_1]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-42.42]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-True]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-None]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-any_value5]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-any_value6]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-any_value7]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-any_value8]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-any_value9]", "tests/test_stack.py::test_box_get_value[ChainBox-picobox-<lambda>]", "tests/test_stack.py::test_box_get_keyerror[Box-teststack0]", "tests/test_stack.py::test_box_get_keyerror[Box-picobox]", "tests/test_stack.py::test_box_get_keyerror[ChainBox-teststack0]", "tests/test_stack.py::test_box_get_keyerror[ChainBox-picobox]", "tests/test_stack.py::test_box_get_default[Box-teststack0]", "tests/test_stack.py::test_box_get_default[Box-picobox]", "tests/test_stack.py::test_box_get_default[ChainBox-teststack0]", "tests/test_stack.py::test_box_get_default[ChainBox-picobox]", "tests/test_stack.py::test_box_get_from_top[Box-teststack0-kwargs0]", "tests/test_stack.py::test_box_get_from_top[Box-teststack0-kwargs1]", "tests/test_stack.py::test_box_get_from_top[Box-picobox-kwargs0]", "tests/test_stack.py::test_box_get_from_top[Box-picobox-kwargs1]", "tests/test_stack.py::test_box_get_from_top[ChainBox-teststack0-kwargs0]", "tests/test_stack.py::test_box_get_from_top[ChainBox-teststack0-kwargs1]", "tests/test_stack.py::test_box_get_from_top[ChainBox-picobox-kwargs0]", "tests/test_stack.py::test_box_get_from_top[ChainBox-picobox-kwargs1]", "tests/test_stack.py::test_box_get_from_top_chain[Box-teststack0]", "tests/test_stack.py::test_box_get_from_top_chain[Box-picobox]", "tests/test_stack.py::test_box_get_from_top_chain[ChainBox-teststack0]", "tests/test_stack.py::test_box_get_from_top_chain[ChainBox-picobox]", "tests/test_stack.py::test_box_get_runtimeerror[teststack0]", "tests/test_stack.py::test_box_get_runtimeerror[picobox]", "tests/test_stack.py::test_box_pass_a[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_a[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_a[Box-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_a[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_a[Box-teststack0-args4-kwargs4-15]", "tests/test_stack.py::test_box_pass_a[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_a[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_a[Box-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_a[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_a[Box-picobox-args4-kwargs4-15]", "tests/test_stack.py::test_box_pass_a[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-teststack0-args4-kwargs4-15]", "tests/test_stack.py::test_box_pass_a[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_a[ChainBox-picobox-args4-kwargs4-15]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_b[Box-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_b[Box-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_b[ChainBox-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c[Box-teststack0-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c[Box-picobox-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-teststack0-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c[ChainBox-picobox-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c_default[Box-teststack0-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c_default[Box-picobox-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-teststack0-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args2-kwargs2-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args4-kwargs4-13]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_c_default[ChainBox-picobox-args6-kwargs6-13]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args3-kwargs3-104]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args6-kwargs6-15]", "tests/test_stack.py::test_box_pass_ab[Box-teststack0-args7-kwargs7-113]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args3-kwargs3-104]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args6-kwargs6-15]", "tests/test_stack.py::test_box_pass_ab[Box-picobox-args7-kwargs7-113]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args3-kwargs3-104]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args6-kwargs6-15]", "tests/test_stack.py::test_box_pass_ab[ChainBox-teststack0-args7-kwargs7-113]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args3-kwargs3-104]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args6-kwargs6-15]", "tests/test_stack.py::test_box_pass_ab[ChainBox-picobox-args7-kwargs7-113]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args6-kwargs6-111]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args8-kwargs8-103]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args9-kwargs9-14]", "tests/test_stack.py::test_box_pass_bc[Box-teststack0-args10-kwargs10-111]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args6-kwargs6-111]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args8-kwargs8-103]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args9-kwargs9-14]", "tests/test_stack.py::test_box_pass_bc[Box-picobox-args10-kwargs10-111]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args6-kwargs6-111]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args8-kwargs8-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args9-kwargs9-14]", "tests/test_stack.py::test_box_pass_bc[ChainBox-teststack0-args10-kwargs10-111]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args6-kwargs6-111]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args8-kwargs8-103]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args9-kwargs9-14]", "tests/test_stack.py::test_box_pass_bc[ChainBox-picobox-args10-kwargs10-111]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args6-kwargs6-103]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args7-kwargs7-15]", "tests/test_stack.py::test_box_pass_ac[Box-teststack0-args8-kwargs8-112]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args6-kwargs6-103]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args7-kwargs7-15]", "tests/test_stack.py::test_box_pass_ac[Box-picobox-args8-kwargs8-112]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args6-kwargs6-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args7-kwargs7-15]", "tests/test_stack.py::test_box_pass_ac[ChainBox-teststack0-args8-kwargs8-112]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args2-kwargs2-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args4-kwargs4-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args5-kwargs5-6]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args6-kwargs6-103]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args7-kwargs7-15]", "tests/test_stack.py::test_box_pass_ac[ChainBox-picobox-args8-kwargs8-112]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args2-kwargs2-1003]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args4-kwargs4-1003]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args6-kwargs6-1101]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args8-kwargs8-1003]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args9-kwargs9-104]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args10-kwargs10-1101]", "tests/test_stack.py::test_box_pass_abc[Box-teststack0-args11-kwargs11-1110]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args2-kwargs2-1003]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args4-kwargs4-1003]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args6-kwargs6-1101]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args8-kwargs8-1003]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args9-kwargs9-104]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args10-kwargs10-1101]", "tests/test_stack.py::test_box_pass_abc[Box-picobox-args11-kwargs11-1110]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args2-kwargs2-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args4-kwargs4-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args6-kwargs6-1101]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args8-kwargs8-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args9-kwargs9-104]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args10-kwargs10-1101]", "tests/test_stack.py::test_box_pass_abc[ChainBox-teststack0-args11-kwargs11-1110]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args2-kwargs2-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args3-kwargs3-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args4-kwargs4-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args5-kwargs5-104]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args6-kwargs6-1101]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args7-kwargs7-6]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args8-kwargs8-1003]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args9-kwargs9-104]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args10-kwargs10-1101]", "tests/test_stack.py::test_box_pass_abc[ChainBox-picobox-args11-kwargs11-1110]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_d_as_b[Box-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-teststack0-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args0-kwargs0-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args1-kwargs1-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args2-kwargs2-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args3-kwargs3-14]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args4-kwargs4-6]", "tests/test_stack.py::test_box_pass_d_as_b[ChainBox-picobox-args5-kwargs5-14]", "tests/test_stack.py::test_box_pass_method[Box-teststack0-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_method[Box-teststack0-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_method[Box-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_method[Box-picobox-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_method[Box-picobox-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_method[Box-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_method[ChainBox-teststack0-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_method[ChainBox-teststack0-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_method[ChainBox-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_method[ChainBox-picobox-args0-kwargs0-1]", "tests/test_stack.py::test_box_pass_method[ChainBox-picobox-args1-kwargs1-1]", "tests/test_stack.py::test_box_pass_method[ChainBox-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_key_type[Box-teststack0-args0-kwargs0-41]", "tests/test_stack.py::test_box_pass_key_type[Box-teststack0-args1-kwargs1-41]", "tests/test_stack.py::test_box_pass_key_type[Box-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_key_type[Box-picobox-args0-kwargs0-41]", "tests/test_stack.py::test_box_pass_key_type[Box-picobox-args1-kwargs1-41]", "tests/test_stack.py::test_box_pass_key_type[Box-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-teststack0-args0-kwargs0-41]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-teststack0-args1-kwargs1-41]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-teststack0-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-picobox-args0-kwargs0-41]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-picobox-args1-kwargs1-41]", "tests/test_stack.py::test_box_pass_key_type[ChainBox-picobox-args2-kwargs2-42]", "tests/test_stack.py::test_box_pass_unexpected_argument[Box-teststack0]", "tests/test_stack.py::test_box_pass_unexpected_argument[Box-picobox]", "tests/test_stack.py::test_box_pass_unexpected_argument[ChainBox-teststack0]", "tests/test_stack.py::test_box_pass_unexpected_argument[ChainBox-picobox]", "tests/test_stack.py::test_box_pass_keyerror[Box-teststack0]", "tests/test_stack.py::test_box_pass_keyerror[Box-picobox]", "tests/test_stack.py::test_box_pass_keyerror[ChainBox-teststack0]", "tests/test_stack.py::test_box_pass_keyerror[ChainBox-picobox]", "tests/test_stack.py::test_box_pass_runtimeerror[teststack0]", "tests/test_stack.py::test_box_pass_runtimeerror[picobox]", "tests/test_stack.py::test_box_pass_optimization[Box-teststack0]", "tests/test_stack.py::test_box_pass_optimization[Box-picobox]", "tests/test_stack.py::test_box_pass_optimization[ChainBox-teststack0]", "tests/test_stack.py::test_box_pass_optimization[ChainBox-picobox]", "tests/test_stack.py::test_box_pass_optimization_complex[Box-teststack0]", "tests/test_stack.py::test_box_pass_optimization_complex[Box-picobox]", "tests/test_stack.py::test_box_pass_optimization_complex[ChainBox-teststack0]", "tests/test_stack.py::test_box_pass_optimization_complex[ChainBox-picobox]", "tests/test_stack.py::test_chainbox_put_changes_box[teststack0]", "tests/test_stack.py::test_chainbox_put_changes_box[picobox]", "tests/test_stack.py::test_chainbox_get_chained[teststack0]", "tests/test_stack.py::test_chainbox_get_chained[picobox]", "tests/test_stack.py::test_stack_isolated[Box]", "tests/test_stack.py::test_stack_isolated[ChainBox]", "tests/test_stack.py::test_push_pop_as_regular_functions[teststack0]", "tests/test_stack.py::test_push_pop_as_regular_functions[picobox]", "tests/test_stack.py::test_pop_empty_stack[teststack0]", "tests/test_stack.py::test_pop_empty_stack[picobox]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-27 01:12:27+00:00
mit
2,802
ikamensh__flynt-163
diff --git a/src/flynt/cli.py b/src/flynt/cli.py index f61f21d..67132db 100644 --- a/src/flynt/cli.py +++ b/src/flynt/cli.py @@ -7,7 +7,7 @@ import warnings from typing import List, Optional from flynt import __version__ -from flynt.api import fstringify, fstringify_code_by_line, fstringify_content +from flynt.api import fstringify, fstringify_content from flynt.pyproject_finder import find_pyproject_toml, parse_pyproject_toml from flynt.state import State @@ -179,20 +179,17 @@ def run_flynt_cli(arglist: Optional[List[str]] = None) -> int: level=(logging.DEBUG if args.verbose else logging.CRITICAL), ) - state = State( - aggressive=args.aggressive, - quiet=args.quiet, - dry_run=args.dry_run, - ) + state = state_from_args(args) if args.verbose: logging.getLogger("flynt").setLevel(logging.DEBUG) if args.string: - converted, _ = fstringify_code_by_line( - " ".join(args.src), - state=state, + content = " ".join(args.src) + result = fstringify_content( + content, + state, ) - print(converted) + print(result.content if result else content) return 0 if "-" in args.src: if len(args.src) > 1: @@ -222,6 +219,7 @@ def run_flynt_cli(arglist: Optional[List[str]] = None) -> int: ) parser.set_defaults(**cfg) args = parser.parse_args(arglist) + state = state_from_args(args) if not args.quiet: print(salutation) if args.verbose: @@ -234,3 +232,17 @@ def run_flynt_cli(arglist: Optional[List[str]] = None) -> int: fail_on_changes=args.fail_on_change, state=state, ) + + +def state_from_args(args) -> State: + return State( + aggressive=args.aggressive, + dry_run=args.dry_run, + len_limit=args.line_length, + multiline=(not args.no_multiline), + quiet=args.quiet, + transform_concat=args.transform_concats, + transform_format=args.transform_format, + transform_join=args.transform_joins, + transform_percent=args.transform_percent, + )
ikamensh/flynt
5b071580192a78694280da0681e07b5262801c4e
diff --git a/test/integration/test_cli.py b/test/integration/test_cli.py index a513f00..f91afd2 100644 --- a/test/integration/test_cli.py +++ b/test/integration/test_cli.py @@ -1,5 +1,6 @@ import io import os +import sys import pytest @@ -84,6 +85,26 @@ def test_cli_string_unquoted(capsys, code_in, code_out): assert err == "" [email protected](sys.version_info < (3, 8), reason="requires python3.8 or higher") +def test_cli_string_supports_flags(capsys): + """ + Tests a --string invocation also does additional transformations. + + See https://github.com/ikamensh/flynt/issues/162 + """ + return_code = run_flynt_cli( + [ + "-tc", + "--string", + "test_string = 'This' + ' ' + 'may' + ' ' + 'not' + ' ' + 'work'", + ] + ) + assert return_code == 0 + out, err = capsys.readouterr() + assert out.strip() == 'test_string = f"This may not work"' + assert err == "" + + @pytest.mark.parametrize("code_in, code_out", valid_snippets) def test_cli_stdin(monkeypatch, capsys, code_in, code_out): """
Transform concatenation does not work with "--string" Version/Dist information: `Python 3.10.6` `Bash v5.1.16(1)-release` `Ubuntu 22.04` `x86_64` Expected behavior is achieved when reading from a python file. `cat test.py`: ``` #!/bin/env python test_string = 'This' + ' ' + 'may ' + ' ' + 'not' + ' ' + 'work' ``` ```flynt -tc t.py```: ``` test_string = f"This may not work" ``` ```flynt -tc --string "test_string = 'This' + ' ' + 'may' + ' ' + 'not' + ' ' + 'work'"``` Expected result: ``` test_string = f"This may not work" ``` Actual result: ``` test_string = 'This' + ' ' + 'may' + ' ' + 'not' + ' ' + 'work' ``` Flynt does not report any errors or missed opportunities. It is simply not recognized. Passing it in from an array, using < <(...) , with escaped double quotes, etc., still does not produce the expected behavior.
0.0
5b071580192a78694280da0681e07b5262801c4e
[ "test/integration/test_cli.py::test_cli_string_supports_flags" ]
[ "test/integration/test_cli.py::test_cli_no_args", "test/integration/test_cli.py::test_cli_version", "test/integration/test_cli.py::test_cli_string_quoted['{}'.format(x)", "test/integration/test_cli.py::test_cli_string_quoted[['{}={}'.format(key,", "test/integration/test_cli.py::test_cli_string_quoted[[\"{}={}\".format(key,", "test/integration/test_cli.py::test_cli_string_quoted[This", "test/integration/test_cli.py::test_cli_string_unquoted['{}'.format(x)", "test/integration/test_cli.py::test_cli_string_unquoted[['{}={}'.format(key,", "test/integration/test_cli.py::test_cli_string_unquoted[[\"{}={}\".format(key,", "test/integration/test_cli.py::test_cli_string_unquoted[This", "test/integration/test_cli.py::test_cli_stdin['{}'.format(x)", "test/integration/test_cli.py::test_cli_stdin[['{}={}'.format(key,", "test/integration/test_cli.py::test_cli_stdin[[\"{}={}\".format(key,", "test/integration/test_cli.py::test_cli_dry_run[all_named.py]", "test/integration/test_cli.py::test_cli_dry_run[first_string.py]", "test/integration/test_cli.py::test_cli_dry_run[percent_dict.py]", "test/integration/test_cli.py::test_cli_dry_run[multiline_limit.py]" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-01-06 16:30:37+00:00
mit
2,803
ikamensh__flynt-189
diff --git a/pyproject.toml b/pyproject.toml index 22220a9..9bbd0af 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,7 +83,7 @@ max-branches = 18 max-statements = 67 [tool.ruff.per-file-ignores] -"test/*" = ["I"] +"test/*" = ["I", "S"] "test/integration/*" = [ "F523", "F821", diff --git a/src/flynt/__init__.py b/src/flynt/__init__.py index 5f94a49..0019830 100644 --- a/src/flynt/__init__.py +++ b/src/flynt/__init__.py @@ -2,7 +2,7 @@ from old "%-formatted" and .format(...) strings into Python 3.6+'s f-strings. Learn more about f-strings at https://www.python.org/dev/peps/pep-0498/""" -__version__ = "1.0.0" +__version__ = "1.0.1" from flynt.cli import main diff --git a/src/flynt/static_join/transformer.py b/src/flynt/static_join/transformer.py index 7314b1a..8e86896 100644 --- a/src/flynt/static_join/transformer.py +++ b/src/flynt/static_join/transformer.py @@ -42,6 +42,10 @@ class JoinTransformer(ast.NodeTransformer): def transform_join(tree: ast.AST, *args, **kwargs) -> Tuple[str, bool]: jt = JoinTransformer() - jt.visit(tree) - new_code = fixup_transformed(tree) - return new_code, jt.counter > 0 + new_tree = jt.visit(tree) + changed = jt.counter > 0 + if changed: + new_code = fixup_transformed(new_tree) + else: + new_code = "" + return new_code, changed diff --git a/src/flynt/string_concat/transformer.py b/src/flynt/string_concat/transformer.py index 31fadb3..8276c3c 100644 --- a/src/flynt/string_concat/transformer.py +++ b/src/flynt/string_concat/transformer.py @@ -65,6 +65,9 @@ def transform_concat(tree: ast.AST, *args, **kwargs) -> Tuple[str, bool]: ft = ConcatTransformer() new = ft.visit(tree) - new_code = fixup_transformed(new) - - return new_code, ft.counter > 0 + changed = ft.counter > 0 + if changed: + new_code = fixup_transformed(new) + else: + new_code = "" + return new_code, changed diff --git a/src/flynt/utils/utils.py b/src/flynt/utils/utils.py index 7db23ef..a97b21b 100644 --- a/src/flynt/utils/utils.py +++ b/src/flynt/utils/utils.py @@ -101,7 +101,18 @@ def ast_string_node(string: str) -> ast.Str: return ast.Str(s=string) +def check_is_string_node(tree: ast.AST): + """Raise an exception is tree doesn't represent a string""" + if isinstance(tree, ast.Module): + tree = tree.body[0] + if isinstance(tree, ast.Expr): + tree = tree.value + assert isinstance(tree, (ast.JoinedStr, ast.Str)), f"found {type(tree)}" + + def fixup_transformed(tree: ast.AST, quote_type: Optional[str] = None) -> str: + """Given a transformed string / fstring ast node, transform it to a string.""" + # check_is_string_node(tree) il = FstrInliner() il.visit(tree) new_code = ast_to_string(tree) @@ -112,6 +123,7 @@ def fixup_transformed(tree: ast.AST, quote_type: Optional[str] = None) -> str: new_code = set_quote_type(new_code, quote_type) new_code = new_code.replace("\n", "\\n") new_code = new_code.replace("\t", "\\t") + # ast.parse(new_code) return new_code
ikamensh/flynt
c573f8b05cfb6ffe1f92bb72bf59d3851a81cbc1
diff --git a/test/test_edits.py b/test/test_edits.py index 93e327f..cefda7d 100644 --- a/test/test_edits.py +++ b/test/test_edits.py @@ -663,3 +663,12 @@ def test_literal_direct(state: State): out, count = code_editor.fstringify_code_by_line(s_in, state) assert count == 1 assert out == expected_out + + +def test_joins(): + + s_in = """';'.join(['a', 'b', 'c'])""" + expected_out = '"a;b;c"' + out, count = code_editor.fstringify_static_joins(s_in, State()) + assert count > 0 + assert out == expected_out
transform-joins breaks code Here's my flynt output: ``` Running flynt v.1.0.0 Using config file at /asdf/qwer/pyproject.toml Using following options: Namespace(verbose=True, quiet=False, no_multiline=False, line_length=88, dry_run=True, stdout=False, string=False, transform_percent=True, transform_format=True, transform_concats=True, transform_joins=True, fail_on_change=False, aggressive=False, exclude=None, src=['.dev/bug.py'], version=False) Running flynt in dry-run mode. No files will be changed. --- /asdf/qwer/bug.py +++ @@ -1,2 +1,2 @@ -';'.join(['a', 'b', 'c']) +";\"\"\".join(['a', 'b', 'c" fstringifying /asdf/qwer/bug.py...modified Flynt run has finished. Stats: Execution time: 0.003s Files checked: 1 Files modified: 1 Character count reduction: 25 (96.15%) Per expression type: No old style (`%`) expressions attempted. No `.format(...)` calls attempted. No concatenations attempted. Static string joins attempted: 1/1 (100.0%) F-string expressions created: 1 _-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_. Please run your tests before committing. Did flynt get a perfect conversion? give it a star at: ~ https://github.com/ikamensh/flynt ~ Thank you for using flynt. Upgrade more projects and recommend it to your colleagues! ``` Python version is 3.11.3
0.0
c573f8b05cfb6ffe1f92bb72bf59d3851a81cbc1
[ "test/test_edits.py::test_joins" ]
[ "test/test_edits.py::test_timestamp", "test/test_edits.py::test_ifexpr", "test/test_edits.py::test_binop", "test/test_edits.py::test_call", "test/test_edits.py::test_string_specific_len", "test/test_edits.py::test_dont_wrap_len", "test/test_edits.py::test_string_in_string_single", "test/test_edits.py::test_percent_tuple", "test/test_edits.py::test_part_of_concat", "test/test_edits.py::test_one_string", "test/test_edits.py::test_nonatomic", "test/test_edits.py::test_noqa", "test/test_edits.py::test_noqa_other", "test/test_edits.py::test_multiline", "test/test_edits.py::test_conversion", "test/test_edits.py::test_invalid_conversion", "test/test_edits.py::test_invalid_conversion_names", "test/test_edits.py::test_dangerous_tuple", "test/test_edits.py::test_percent_newline", "test/test_edits.py::test_format_newline", "test/test_edits.py::test_format_tab", "test/test_edits.py::test_indented", "test/test_edits.py::test_line_split", "test/test_edits.py::test_line_split_single_line", "test/test_edits.py::test_line_split_kw", "test/test_edits.py::test_openpyxl", "test/test_edits.py::test_double_percent_2", "test/test_edits.py::test_str_in_str", "test/test_edits.py::test_str_in_str_single_quote", "test/test_edits.py::test_chain_fmt", "test/test_edits.py::test_chain_fmt_3", "test/test_edits.py::test_empty_line", "test/test_edits.py::test_dict_perc", "test/test_edits.py::test_legacy_unicode", "test/test_edits.py::test_double_percent_no_prob", "test/test_edits.py::test_percent_dict", "test/test_edits.py::test_percent_dict_fmt", "test/test_edits.py::test_double_percent_dict", "test/test_edits.py::test_percent_dict_reused_key_noop", "test/test_edits.py::test_percent_dict_reused_key_aggressive", "test/test_edits.py::test_percent_dict_name", "test/test_edits.py::test_percent_dict_names", "test/test_edits.py::test_percent_attr", "test/test_edits.py::test_percent_dict_prefix", "test/test_edits.py::test_legacy_fmtspec", "test/test_edits.py::test_str_in_str_curly", "test/test_edits.py::test_str_in_str_methods", "test/test_edits.py::test_decimal_precision", "test/test_edits.py::test_width_spec", "test/test_edits.py::test_equiv_expressions_repr", "test/test_edits.py::test_equiv_expressions_hex", "test/test_edits.py::test_equiv_expressions_s", "test/test_edits.py::test_concat", "test/test_edits.py::test_concat_two_sides", "test/test_edits.py::test_integers_equivalence[0-e]", "test/test_edits.py::test_integers_equivalence[0-g]", "test/test_edits.py::test_integers_equivalence[0-d]", "test/test_edits.py::test_integers_equivalence[0-i]", "test/test_edits.py::test_integers_equivalence[0-x]", "test/test_edits.py::test_integers_equivalence[0-X]", "test/test_edits.py::test_integers_equivalence[0-u]", "test/test_edits.py::test_integers_equivalence[11-e]", "test/test_edits.py::test_integers_equivalence[11-g]", "test/test_edits.py::test_integers_equivalence[11-d]", "test/test_edits.py::test_integers_equivalence[11-i]", "test/test_edits.py::test_integers_equivalence[11-x]", "test/test_edits.py::test_integers_equivalence[11-X]", "test/test_edits.py::test_integers_equivalence[11-u]", "test/test_edits.py::test_integers_equivalence[7-e]", "test/test_edits.py::test_integers_equivalence[7-g]", "test/test_edits.py::test_integers_equivalence[7-d]", "test/test_edits.py::test_integers_equivalence[7-i]", "test/test_edits.py::test_integers_equivalence[7-x]", "test/test_edits.py::test_integers_equivalence[7-X]", "test/test_edits.py::test_integers_equivalence[7-u]", "test/test_edits.py::test_floats_equivalence[3.33333333-e]", "test/test_edits.py::test_floats_equivalence[3.33333333-g]", "test/test_edits.py::test_floats_equivalence[3.33333333-f]", "test/test_edits.py::test_floats_equivalence[1.5e-43-e]", "test/test_edits.py::test_floats_equivalence[1.5e-43-g]", "test/test_edits.py::test_floats_equivalence[1.5e-43-f]", "test/test_edits.py::test_floats_equivalence[3.142854-e]", "test/test_edits.py::test_floats_equivalence[3.142854-g]", "test/test_edits.py::test_floats_equivalence[3.142854-f]", "test/test_edits.py::test_floats_precision_equiv[3.33333333-.02f]", "test/test_edits.py::test_floats_precision_equiv[3.33333333-.01e]", "test/test_edits.py::test_floats_precision_equiv[3.33333333-.04g]", "test/test_edits.py::test_floats_precision_equiv[3.33333333-05f]", "test/test_edits.py::test_floats_precision_equiv[1.5e-43-.02f]", "test/test_edits.py::test_floats_precision_equiv[1.5e-43-.01e]", "test/test_edits.py::test_floats_precision_equiv[1.5e-43-.04g]", "test/test_edits.py::test_floats_precision_equiv[1.5e-43-05f]", "test/test_edits.py::test_floats_precision_equiv[3.142854-.02f]", "test/test_edits.py::test_floats_precision_equiv[3.142854-.01e]", "test/test_edits.py::test_floats_precision_equiv[3.142854-.04g]", "test/test_edits.py::test_floats_precision_equiv[3.142854-05f]", "test/test_edits.py::test_multiline_tuple", "test/test_edits.py::test_kv_loop", "test/test_edits.py::test_unknown_mod_percend_dictionary", "test/test_edits.py::test_mixed_quote_types", "test/test_edits.py::test_mixed_quote_types_unsafe", "test/test_edits.py::test_super_call", "test/test_edits.py::test_escaped_mix", "test/test_edits.py::test_escaped_mix_double", "test/test_edits.py::test_112", "test/test_edits.py::test_112_simple", "test/test_edits.py::test_110", "test/test_edits.py::test_110_nonaggr", "test/test_edits.py::test_literal_direct" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-28 09:45:50+00:00
mit
2,804
ilevkivskyi__com2ann-21
diff --git a/src/com2ann.py b/src/com2ann.py index b1683e3..166672e 100644 --- a/src/com2ann.py +++ b/src/com2ann.py @@ -459,6 +459,7 @@ def wrap_function_header(header: str) -> List[str]: parts: List[str] = [] next_part = '' nested = 0 + complete = False # Did we split all the arguments inside (...)? indent: Optional[int] = None for i, c in enumerate(header): @@ -468,7 +469,9 @@ def wrap_function_header(header: str) -> List[str]: indent = i + 1 if c in ')]}': nested -= 1 - if c == ',' and nested == 1: + if not nested: + complete = True + if c == ',' and nested == 1 and not complete: next_part += c parts.append(next_part) next_part = ''
ilevkivskyi/com2ann
bb8a37fa473060623ff4589b3cf3f4ebf4f1eb09
diff --git a/src/test_com2ann.py b/src/test_com2ann.py index fafb71c..6cef088 100644 --- a/src/test_com2ann.py +++ b/src/test_com2ann.py @@ -411,6 +411,19 @@ class FunctionTestCase(BaseTestCase): *fake_receipts: str) -> None: pass """, False, False, 10) + self.check( + """ + def embezzle(self, account, funds=MANY, *fake_receipts): + # type: (str, int, *str) -> Dict[str, Dict[str, int]] + pass + """, + """ + def embezzle(self, + account: str, + funds: int = MANY, + *fake_receipts: str) -> Dict[str, Dict[str, int]]: + pass + """, False, False, 10) def test_decorator_body(self) -> None: self.check(
When using --wrap-signatures, return annotations with commas also get wrapped For example: ```python def func(arg1: SomeVeryLongType1, arg2: SomeVeryLongType2) -> Dict[str, int]: ... ``` This is not a syntax error, but looks ugly.
0.0
bb8a37fa473060623ff4589b3cf3f4ebf4f1eb09
[ "src/test_com2ann.py::FunctionTestCase::test_wrap_lines" ]
[ "src/test_com2ann.py::AssignTestCase::test_basics", "src/test_com2ann.py::AssignTestCase::test_coding_kept", "src/test_com2ann.py::AssignTestCase::test_comment_on_separate_line", "src/test_com2ann.py::AssignTestCase::test_complete_tuple", "src/test_com2ann.py::AssignTestCase::test_complex_targets", "src/test_com2ann.py::AssignTestCase::test_continuation_using_parens", "src/test_com2ann.py::AssignTestCase::test_drop_Ellipsis", "src/test_com2ann.py::AssignTestCase::test_drop_None", "src/test_com2ann.py::AssignTestCase::test_literal_types", "src/test_com2ann.py::AssignTestCase::test_multi_line_assign", "src/test_com2ann.py::AssignTestCase::test_multi_line_tuple_value", "src/test_com2ann.py::AssignTestCase::test_newline", "src/test_com2ann.py::AssignTestCase::test_parenthesized_lhs", "src/test_com2ann.py::AssignTestCase::test_pattern", "src/test_com2ann.py::AssignTestCase::test_type_ignore", "src/test_com2ann.py::AssignTestCase::test_uneven_spacing", "src/test_com2ann.py::AssignTestCase::test_wrong", "src/test_com2ann.py::FunctionTestCase::test_async_single", "src/test_com2ann.py::FunctionTestCase::test_combined_annotations_multi", "src/test_com2ann.py::FunctionTestCase::test_combined_annotations_single", "src/test_com2ann.py::FunctionTestCase::test_complex_kinds", "src/test_com2ann.py::FunctionTestCase::test_decorator_body", "src/test_com2ann.py::FunctionTestCase::test_literal_type", "src/test_com2ann.py::FunctionTestCase::test_self_argument", "src/test_com2ann.py::FunctionTestCase::test_single", "src/test_com2ann.py::LineReportingTestCase::test_confusing_function_comments", "src/test_com2ann.py::LineReportingTestCase::test_invalid_function_comments", "src/test_com2ann.py::LineReportingTestCase::test_simple_assign", "src/test_com2ann.py::LineReportingTestCase::test_simple_function", "src/test_com2ann.py::LineReportingTestCase::test_unsupported_assigns", "src/test_com2ann.py::LineReportingTestCase::test_unsupported_statements", "src/test_com2ann.py::ForAndWithTestCase::test_async_for", "src/test_com2ann.py::ForAndWithTestCase::test_async_with", "src/test_com2ann.py::ForAndWithTestCase::test_for", "src/test_com2ann.py::ForAndWithTestCase::test_with", "src/test_com2ann.py::FutureImportTestCase::test_added_future_import", "src/test_com2ann.py::FutureImportTestCase::test_not_added_future_import" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-06-12 01:01:12+00:00
mit
2,805
ilevkivskyi__com2ann-35
diff --git a/src/com2ann.py b/src/com2ann.py index b3a892e..9e853bd 100644 --- a/src/com2ann.py +++ b/src/com2ann.py @@ -467,7 +467,8 @@ def process_assign(comment: AssignData, data: FileData, # We perform the tasks in order from larger line/columns to smaller ones # to avoid shuffling the line column numbers in following code. # First remove the type comment. - if re.search(TYPE_COM, lines[rv_end]): + match = re.search(TYPE_COM, lines[rv_end]) + if match and not match.group(1).lstrip().startswith('ignore'): lines[rv_end] = strip_type_comment(lines[rv_end]) else: # Special case: type comment moved to a separate continuation line.
ilevkivskyi/com2ann
ce7583b5a98ee5b9dbeb8a8cef4239893e230291
diff --git a/src/test_com2ann.py b/src/test_com2ann.py index 2b93328..37236ec 100644 --- a/src/test_com2ann.py +++ b/src/test_com2ann.py @@ -228,6 +228,23 @@ class AssignTestCase(BaseTestCase): | {other} ) """) + self.check( + """ + foo = object() + + bar = ( + # Comment which explains why this ignored + foo.quox # type: ignore[attribute] + ) # type: Mapping[str, Distribution] + """, + """ + foo = object() + + bar: Mapping[str, Distribution] = ( + # Comment which explains why this ignored + foo.quox # type: ignore[attribute] + ) + """) def test_with_for(self) -> None: self.check(
Type comment left in place when expression is type ignored Thanks for this tool, it's really useful :) If you have code like this: ``` python foo = object() bar = ( # Comment which explains why this ignored foo.quox # type: ignore[attribute] ) # type: Mapping[str, Distribution] ``` Then after running `com2ann` you end up with: ``` python foo = object() bar: Mapping[str, int] = ( # Comment which explains why this ignored foo.quox # type: ignore[attribute] ) # type: Mapping[str, int] ``` which `mypy` then complains about due to the double signature. The intermediate (explanatory) comment doesn't seem to be related, though the `type: ignore` comment is.
0.0
ce7583b5a98ee5b9dbeb8a8cef4239893e230291
[ "src/test_com2ann.py::AssignTestCase::test_continuation_using_parens" ]
[ "src/test_com2ann.py::AssignTestCase::test_basics", "src/test_com2ann.py::AssignTestCase::test_coding_kept", "src/test_com2ann.py::AssignTestCase::test_comment_on_separate_line", "src/test_com2ann.py::AssignTestCase::test_complete_tuple", "src/test_com2ann.py::AssignTestCase::test_complex_targets", "src/test_com2ann.py::AssignTestCase::test_drop_Ellipsis", "src/test_com2ann.py::AssignTestCase::test_drop_None", "src/test_com2ann.py::AssignTestCase::test_literal_types", "src/test_com2ann.py::AssignTestCase::test_multi_line_assign", "src/test_com2ann.py::AssignTestCase::test_multi_line_tuple_value", "src/test_com2ann.py::AssignTestCase::test_newline", "src/test_com2ann.py::AssignTestCase::test_parenthesized_lhs", "src/test_com2ann.py::AssignTestCase::test_pattern", "src/test_com2ann.py::AssignTestCase::test_type_ignore", "src/test_com2ann.py::AssignTestCase::test_uneven_spacing", "src/test_com2ann.py::AssignTestCase::test_with_for", "src/test_com2ann.py::AssignTestCase::test_wrong", "src/test_com2ann.py::FunctionTestCase::test_async_single", "src/test_com2ann.py::FunctionTestCase::test_combined_annotations_multi", "src/test_com2ann.py::FunctionTestCase::test_combined_annotations_single", "src/test_com2ann.py::FunctionTestCase::test_complex_kinds", "src/test_com2ann.py::FunctionTestCase::test_decorator_body", "src/test_com2ann.py::FunctionTestCase::test_keyword_only_args", "src/test_com2ann.py::FunctionTestCase::test_literal_type", "src/test_com2ann.py::FunctionTestCase::test_next_line_comment", "src/test_com2ann.py::FunctionTestCase::test_self_argument", "src/test_com2ann.py::FunctionTestCase::test_single", "src/test_com2ann.py::FunctionTestCase::test_wrap_lines", "src/test_com2ann.py::FunctionTestCase::test_wrap_lines_error_code", "src/test_com2ann.py::LineReportingTestCase::test_confusing_function_comments", "src/test_com2ann.py::LineReportingTestCase::test_invalid_function_comments", "src/test_com2ann.py::LineReportingTestCase::test_simple_assign", "src/test_com2ann.py::LineReportingTestCase::test_simple_function", "src/test_com2ann.py::LineReportingTestCase::test_unsupported_assigns", "src/test_com2ann.py::LineReportingTestCase::test_unsupported_statements", "src/test_com2ann.py::ForAndWithTestCase::test_async_for", "src/test_com2ann.py::ForAndWithTestCase::test_async_with", "src/test_com2ann.py::ForAndWithTestCase::test_for", "src/test_com2ann.py::ForAndWithTestCase::test_with", "src/test_com2ann.py::FutureImportTestCase::test_added_future_import", "src/test_com2ann.py::FutureImportTestCase::test_not_added_future_import" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-03-07 09:17:05+00:00
mit
2,806
ilevkivskyi__com2ann-58
diff --git a/src/com2ann.py b/src/com2ann.py index 5e41a5f..f6d0f48 100644 --- a/src/com2ann.py +++ b/src/com2ann.py @@ -936,8 +936,8 @@ def main() -> None: options = Options(**args) for infile in infiles: - outfile = outfile or infile - process_single_entry(in_path=infile, out_path=outfile, options=options) + cur_outfile = outfile or infile + process_single_entry(in_path=infile, out_path=cur_outfile, options=options) if __name__ == '__main__':
ilevkivskyi/com2ann
6fa4c021c8b1cec27ccd8c900c0ddea7faab91bb
diff --git a/src/test_cli.py b/src/test_cli.py index 29f63ef..abec360 100644 --- a/src/test_cli.py +++ b/src/test_cli.py @@ -2,6 +2,7 @@ from __future__ import annotations import os import pathlib +from dataclasses import asdict from typing import Any, Callable, Iterable, TypedDict import pytest @@ -216,3 +217,42 @@ def test_process_single_entry__dir( options=options, ), ] + + [email protected] +def parse_cli_args( + test_path: pathlib.Path, + mocker: Any, + options: com2ann.Options, +) -> Any: + f1 = test_path / "f1.py" + f2 = test_path / "f2.py" + + f1.write_text("f1 = True") + f2.write_text("f2 = False") + + args = {'infiles': [f1, f2], 'outfile': None, **asdict(options)} + return mocker.patch("com2ann.parse_cli_args", return_value=args) + + +def test_process_multiple_input_files( + test_path: pathlib.Path, translate_file: Any, + mocker: Any, parse_cli_args: Any, + options: com2ann.Options +) -> None: + com2ann.main() + + assert translate_file.mock_calls == [ + mocker.call( + infile=str(test_path / "f1.py"), + outfile=str(test_path / "f1.py"), + options=options, + ), + mocker.call( + infile=str(test_path / "f2.py"), + outfile=str(test_path / "f2.py"), + options=options, + ), + ] + assert (test_path / "f1.py").read_text() == "f1 = True" + assert (test_path / "f2.py").read_text() == "f2 = False"
Multiple input files are generated to single file When a command is called with multiple files (ex. `com2ann f1.py f2.py`), then the first file (`f1.py`) is chosen as output for both files. This is especially problematic when `pre-commit` hook is used.
0.0
6fa4c021c8b1cec27ccd8c900c0ddea7faab91bb
[ "src/test_cli.py::test_process_multiple_input_files" ]
[ "src/test_cli.py::test_parse_cli_args__minimal", "src/test_cli.py::test_parse_cli_args__maximal", "src/test_cli.py::test_parse_cli_args__no_infile", "src/test_cli.py::test_parse_cli_args__missing_file", "src/test_cli.py::test_parse_cli_args__in_out_type_mismatch[file.py-dir]", "src/test_cli.py::test_parse_cli_args__in_out_type_mismatch[dir-file.py]", "src/test_cli.py::test_parse_cli_args__outfile_doesnt_exist", "src/test_cli.py::test_parse_cli_args__multiple_inputs_and_output", "src/test_cli.py::test_rebase_path", "src/test_cli.py::test_process_single_entry__file", "src/test_cli.py::test_process_single_entry__dir" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-08-28 21:32:47+00:00
mit
2,807
ilevkivskyi__typing_inspect-26
diff --git a/README.md b/README.md index 93ad929..4d9924b 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,8 @@ Currently provided functions (see functions docstrings for examples of usage): non-generic classes. * ``is_union_type(tp)``: Test if ``tp`` is a union type. +* ``is_optional_type(tp)``: + Test if ``tp`` is an optional type (either ``type(None)`` or a direct union to it such as in ``Optional[int]``). Nesting and ``TypeVar``s are not unfolded/inspected in this process. * ``is_typevar(tp)``: Test if ``tp`` represents a type variable. * ``is_classvar(tp)``: diff --git a/typing_inspect.py b/typing_inspect.py index 6dba71f..ee0de11 100644 --- a/typing_inspect.py +++ b/typing_inspect.py @@ -116,6 +116,27 @@ def is_tuple_type(tp): return type(tp) is TupleMeta +def is_optional_type(tp): + """Returns `True` if the type is `type(None)`, or is a direct `Union` to `type(None)`, such as `Optional[T]`. + + NOTE: this method inspects nested `Union` arguments but not `TypeVar` definitions (`bound`/`constraint`). So it + will return `False` if + - `tp` is a `TypeVar` bound, or constrained to, an optional type + - `tp` is a `Union` to a `TypeVar` bound or constrained to an optional type, + - `tp` refers to a *nested* `Union` containing an optional type or one of the above. + + Users wishing to check for optionality in types relying on type variables might wish to use this method in + combination with `get_constraints` and `get_bound` + """ + + if tp is type(None): + return True + elif is_union_type(tp): + return any(is_optional_type(tt) for tt in get_args(tp, evaluate=True)) + else: + return False + + def is_union_type(tp): """Test if the type is a union type. Examples:: @@ -322,6 +343,36 @@ def get_args(tp, evaluate=None): return () +def get_bound(tp): + """Returns the type bound to a `TypeVar` if any. It the type is not a `TypeVar`, a `TypeError` is raised + + Examples:: + + get_bound(TypeVar('T')) == None + get_bound(TypeVar('T', bound=int)) == int + """ + + if is_typevar(tp): + return getattr(tp, '__bound__', None) + else: + raise TypeError("type is not a `TypeVar`: " + str(tp)) + + +def get_constraints(tp): + """Returns the constraints of a `TypeVar` if any. It the type is not a `TypeVar`, a `TypeError` is raised + + Examples:: + + get_constraints(TypeVar('T')) == () + get_constraints(TypeVar('T', int, str)) == (int, str) + """ + + if is_typevar(tp): + return getattr(tp, '__constraints__', ()) + else: + raise TypeError("type is not a `TypeVar`: " + str(tp)) + + def get_generic_type(obj): """Get the generic type of an object if possible, or runtime class otherwise. Examples::
ilevkivskyi/typing_inspect
168fa6f7c5c55f720ce6282727211cf4cf6368f6
diff --git a/test_typing_inspect.py b/test_typing_inspect.py index f88c617..d499916 100644 --- a/test_typing_inspect.py +++ b/test_typing_inspect.py @@ -1,7 +1,8 @@ from typing_inspect import ( is_generic_type, is_callable_type, is_tuple_type, is_union_type, - is_typevar, is_classvar, get_origin, get_parameters, get_last_args, get_args, - get_generic_type, get_generic_bases, get_last_origin, typed_dict_keys, + is_optional_type, is_typevar, is_classvar, get_origin, get_parameters, + get_last_args, get_args, get_bound, get_constraints, get_generic_type, + get_generic_bases, get_last_origin, typed_dict_keys, ) from unittest import TestCase, main, skipIf, skipUnless from typing import ( @@ -30,10 +31,11 @@ if PY36: class IsUtilityTestCase(TestCase): def sample_test(self, fun, samples, nonsamples): + msg = "Error asserting that %s(%s) is %s" for s in samples: - self.assertTrue(fun(s)) + self.assertTrue(fun(s), msg=msg % (fun.__name__, str(s), 'True')) for s in nonsamples: - self.assertFalse(fun(s)) + self.assertFalse(fun(s), msg=msg % (fun.__name__, str(s), 'False')) def test_generic(self): T = TypeVar('T') @@ -68,6 +70,31 @@ class IsUtilityTestCase(TestCase): nonsamples = [int, Union[int, int], [], Iterable[Any]] self.sample_test(is_union_type, samples, nonsamples) + def test_optional_type(self): + T = TypeVar('T') + samples = [type(None), # none type + Optional[int], # direct union to none type 1 + Optional[T], # direct union to none type 2 + Optional[T][int], # direct union to none type 3 + Union[int, type(None)], # direct union to none type 4 + Union[str, T][type(None)] # direct union to none type 5 + ] + # nested unions are supported + samples += [Union[str, Optional[int]], # nested Union 1 + Union[T, str][Optional[int]], # nested Union 2 + ] + nonsamples = [int, Union[int, int], [], Iterable[Any], T, Union[T, str][int]] + # unfortunately current definition sets these ones as non samples too + S1 = TypeVar('S1', bound=Optional[int]) + S2 = TypeVar('S2', type(None), str) + S3 = TypeVar('S3', Optional[int], str) + S4 = TypeVar('S4', bound=Union[str, Optional[int]]) + nonsamples += [ + S1, S2, S3, # typevar bound or constrained to optional + Union[S1, int], S4 # combinations of the above + ] + self.sample_test(is_optional_type, samples, nonsamples) + def test_typevar(self): T = TypeVar('T') S_co = TypeVar('S_co', covariant=True) @@ -144,6 +171,18 @@ class GetUtilityTestCase(TestCase): (int, Tuple[Optional[int], Optional[int]])) self.assertEqual(get_args(Callable[[], T][int], evaluate=True), ([], int,)) + def test_bound(self): + T = TypeVar('T') + TB = TypeVar('TB', bound=int) + self.assertEqual(get_bound(T), None) + self.assertEqual(get_bound(TB), int) + + def test_constraints(self): + T = TypeVar('T') + TC = TypeVar('TC', int, str) + self.assertEqual(get_constraints(T), ()) + self.assertEqual(get_constraints(TC), (int, str)) + def test_generic_type(self): T = TypeVar('T') class Node(Generic[T]): pass
New method is_nonable(t) This method would return `True` if * t is the `NoneType` (`t is type(None)`) * t is a (possibly nested) `Union` to `NoneType` (this can be the result of using the `Optional` keyword or of an explicit `Union[type(None), ....]` * t is a `TypeVar` with either a `bound` or a `constraints` set, and one of them is nonable
0.0
168fa6f7c5c55f720ce6282727211cf4cf6368f6
[ "test_typing_inspect.py::IsUtilityTestCase::test_callable", "test_typing_inspect.py::IsUtilityTestCase::test_classvar", "test_typing_inspect.py::IsUtilityTestCase::test_optional_type", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::IsUtilityTestCase::test_typevar", "test_typing_inspect.py::IsUtilityTestCase::test_union", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_bound", "test_typing_inspect.py::GetUtilityTestCase::test_constraints", "test_typing_inspect.py::GetUtilityTestCase::test_generic_bases", "test_typing_inspect.py::GetUtilityTestCase::test_generic_type", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters", "test_typing_inspect.py::GetUtilityTestCase::test_typed_dict" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2018-09-11 13:53:33+00:00
mit
2,808
ilevkivskyi__typing_inspect-71
diff --git a/.travis.yml b/.travis.yml index 1fb80e9..6cf3061 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ matrix: fast_finish: true include: - python: 3.9 + - python: 3.9.1 - python: 3.8 - python: 3.7 - python: 3.6 diff --git a/typing_inspect.py b/typing_inspect.py index d3a0604..c11b856 100644 --- a/typing_inspect.py +++ b/typing_inspect.py @@ -8,10 +8,14 @@ Example usage:: # NOTE: This module must support Python 2.7 in addition to Python 3.x import sys +import types + from mypy_extensions import _TypedDictMeta as _TypedDictMeta_Mypy -if sys.version_info[:3] >= (3, 4, 0) and sys.version_info[:3] < (3, 9, 0): + +# See comments in typing_extensions source on why the switch is at 3.9.2 +if (3, 4, 0) <= sys.version_info[:3] < (3, 9, 2): from typing_extensions import _TypedDictMeta as _TypedDictMeta_TE -elif sys.version_info[:3] >= (3, 9, 0): +elif sys.version_info[:3] >= (3, 9, 2): # typing_extensions.TypedDict is a re-export from typing. from typing import _TypedDictMeta as _TypedDictMeta_TE else: @@ -35,7 +39,7 @@ if NEW_TYPING: from typing_extensions import Final, Literal if sys.version_info[:3] >= (3, 9, 0): from typing import _SpecialGenericAlias - typingGenericAlias = (_GenericAlias, _SpecialGenericAlias) + typingGenericAlias = (_GenericAlias, _SpecialGenericAlias, types.GenericAlias) else: typingGenericAlias = (_GenericAlias,) else: @@ -463,7 +467,7 @@ def get_args(tp, evaluate=None): if NEW_TYPING: if evaluate is not None and not evaluate: raise ValueError('evaluate can only be True in Python >= 3.7') - if isinstance(tp, _GenericAlias): + if isinstance(tp, typingGenericAlias): res = tp.__args__ if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: res = (list(res[:-1]), res[-1]) @@ -485,7 +489,7 @@ def get_args(tp, evaluate=None): # backport of union's subs_tree tree = _union_subs_tree(tp) elif is_generic_type(tp): - # backport of genericmeta's subs_tree + # backport of GenericMeta's subs_tree tree = _generic_subs_tree(tp) elif is_tuple_type(tp): # ad-hoc (inspired by union)
ilevkivskyi/typing_inspect
6dd6b38bc12bcbaf814fb0c69a801365b81e3611
diff --git a/test_typing_inspect.py b/test_typing_inspect.py index c5fc753..58a03ee 100644 --- a/test_typing_inspect.py +++ b/test_typing_inspect.py @@ -115,6 +115,7 @@ class Other(dict): """ PY36 = sys.version_info[:3] >= (3, 6, 0) +PY39 = sys.version_info[:3] >= (3, 9, 0) if PY36: exec(PY36_TESTS) @@ -131,6 +132,8 @@ class IsUtilityTestCase(TestCase): T = TypeVar('T') samples = [Generic, Generic[T], Iterable[int], Mapping, MutableMapping[T, List[int]], Sequence[Union[str, bytes]]] + if PY39: + samples.extend([list[int], dict[str, list[int]]]) nonsamples = [int, Union[int, str], Union[int, T], Callable[..., T], Optional, bytes, list] + CLASSVAR_GENERIC self.sample_test(is_generic_type, samples, nonsamples) @@ -149,6 +152,8 @@ class IsUtilityTestCase(TestCase): def test_tuple(self): samples = [Tuple, Tuple[str, int], Tuple[Iterable, ...]] + if PY39: + samples.append(tuple[int, str]) nonsamples = [int, tuple, 42, List[int], NamedTuple('N', [('x', int)])] self.sample_test(is_tuple_type, samples, nonsamples) if SUBCLASSABLE_TUPLES: @@ -301,6 +306,8 @@ class GetUtilityTestCase(TestCase): self.assertEqual(get_origin(ClassVar[int]), None) self.assertEqual(get_origin(Generic), Generic) self.assertEqual(get_origin(Generic[T]), Generic) + if PY39: + self.assertEqual(get_origin(list[int]), list) if GENERIC_TUPLE_PARAMETRIZABLE: tp = List[Tuple[T, T]][int] self.assertEqual(get_origin(tp), list if NEW_TYPING else List) @@ -323,6 +330,8 @@ class GetUtilityTestCase(TestCase): if EXISTING_UNIONS_SUBSCRIPTABLE: self.assertEqual(get_parameters(Union[S_co, Tuple[T, T]][int, U]), (U,)) self.assertEqual(get_parameters(Mapping[T, Tuple[S_co, T]]), (T, S_co)) + if PY39: + self.assertEqual(get_parameters(dict[int, T]), (T,)) @skipIf(NEW_TYPING, "Not supported in Python 3.7") def test_last_args(self): @@ -389,6 +398,11 @@ class GetUtilityTestCase(TestCase): self.assertEqual(get_args(Literal["value"], evaluate=True), ("value",)) self.assertEqual(get_args(Literal[1, 2, 3], evaluate=True), (1, 2, 3)) + if PY39: + self.assertEqual(get_args(list[int]), (int,)) + self.assertEqual(get_args(tuple[int, str]), (int, str)) + self.assertEqual(get_args(list[list[int]]), (list[int],)) + def test_bound(self): T = TypeVar('T') TB = TypeVar('TB', bound=int)
Support Python 3.9 typing_inspect doesn't really work with Python 3.9 right now. There are issues like #60 and #64, but a variety of things need to be updated. My initial survey (just guessing from poking at implementations; it would be better to have someone review/expand this list who is more intimately familiar with the code-level changes): * The typing module in 3.9 introduces a new "_BaseGenericAlias" class that might more correctly correspond to typing_inspect's current uses of "_GenericAlias." * Add support and tests for the new plain type hints (e.g. "list[int]" rather than "List[int]"). There seems to be a new "GenericAlias" class (that extends no other classes) for these kind of annotations. * Get the current test suite to pass under 3.9. * Add 3.9 to the travis config for regression testing. Any volunteers willing to give it a try? @ilevkivskyi - any additional guidance? What's wrong/missing in my above list?
0.0
6dd6b38bc12bcbaf814fb0c69a801365b81e3611
[ "test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters" ]
[ "test_typing_inspect.py::IsUtilityTestCase::test_callable", "test_typing_inspect.py::IsUtilityTestCase::test_classvar", "test_typing_inspect.py::IsUtilityTestCase::test_final_type", "test_typing_inspect.py::IsUtilityTestCase::test_is_forward_ref", "test_typing_inspect.py::IsUtilityTestCase::test_literal_type", "test_typing_inspect.py::IsUtilityTestCase::test_new_type", "test_typing_inspect.py::IsUtilityTestCase::test_optional_type", "test_typing_inspect.py::IsUtilityTestCase::test_typevar", "test_typing_inspect.py::IsUtilityTestCase::test_union", "test_typing_inspect.py::GetUtilityTestCase::test_bound", "test_typing_inspect.py::GetUtilityTestCase::test_constraints", "test_typing_inspect.py::GetUtilityTestCase::test_generic_bases", "test_typing_inspect.py::GetUtilityTestCase::test_generic_type", "test_typing_inspect.py::GetUtilityTestCase::test_get_forward_arg", "test_typing_inspect.py::GetUtilityTestCase::test_typed_dict_mypy_extension" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-06-05 21:55:52+00:00
mit
2,809
ilevkivskyi__typing_inspect-74
diff --git a/typing_inspect.py b/typing_inspect.py index c11b856..4c765e3 100644 --- a/typing_inspect.py +++ b/typing_inspect.py @@ -467,7 +467,8 @@ def get_args(tp, evaluate=None): if NEW_TYPING: if evaluate is not None and not evaluate: raise ValueError('evaluate can only be True in Python >= 3.7') - if isinstance(tp, typingGenericAlias): + # Note special aliases on Python 3.9 don't have __args__. + if isinstance(tp, typingGenericAlias) and hasattr(tp, '__args__'): res = tp.__args__ if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: res = (list(res[:-1]), res[-1])
ilevkivskyi/typing_inspect
d1d46f4c2429dd0a60f902fa7b728d67bb2d1582
diff --git a/test_typing_inspect.py b/test_typing_inspect.py index 58a03ee..7e9d432 100644 --- a/test_typing_inspect.py +++ b/test_typing_inspect.py @@ -402,6 +402,8 @@ class GetUtilityTestCase(TestCase): self.assertEqual(get_args(list[int]), (int,)) self.assertEqual(get_args(tuple[int, str]), (int, str)) self.assertEqual(get_args(list[list[int]]), (list[int],)) + # This would return (~T,) before Python 3.9. + self.assertEqual(get_args(List), ()) def test_bound(self): T = TypeVar('T')
Python 3.9 support breaks List There was a regression in release 0.7.0 from 0.6.0. Currently, ```python >>> from typing import List, Set >>> from typing_inspect import get_args >>> get_args(list[str]) # Yay this works! Great to see support for Python 3.9! (<class 'str'>,) >>> get_args(List) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/jessemichel/Dependencies/miniconda3/envs/py39/lib/python3.9/site-packages/typing_inspect.py", line 471, in get_args res = tp.__args__ File "/Users/jessemichel/Dependencies/miniconda3/envs/py39/lib/python3.9/typing.py", line 694, in __getattr__ raise AttributeError(attr) AttributeError: __args__ ``` Previously, ```python >>> get_args(List) (~T,) ``` I believe the fix would be changing this line: https://github.com/ilevkivskyi/typing_inspect/blob/d1d46f4c2429dd0a60f902fa7b728d67bb2d1582/typing_inspect.py#L471 to ```python res = tp.__args__ if hasattr(tp, '__args__') else () ```
0.0
d1d46f4c2429dd0a60f902fa7b728d67bb2d1582
[ "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated" ]
[ "test_typing_inspect.py::IsUtilityTestCase::test_callable", "test_typing_inspect.py::IsUtilityTestCase::test_classvar", "test_typing_inspect.py::IsUtilityTestCase::test_final_type", "test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_is_forward_ref", "test_typing_inspect.py::IsUtilityTestCase::test_literal_type", "test_typing_inspect.py::IsUtilityTestCase::test_new_type", "test_typing_inspect.py::IsUtilityTestCase::test_optional_type", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::IsUtilityTestCase::test_typevar", "test_typing_inspect.py::IsUtilityTestCase::test_union", "test_typing_inspect.py::GetUtilityTestCase::test_bound", "test_typing_inspect.py::GetUtilityTestCase::test_constraints", "test_typing_inspect.py::GetUtilityTestCase::test_generic_bases", "test_typing_inspect.py::GetUtilityTestCase::test_generic_type", "test_typing_inspect.py::GetUtilityTestCase::test_get_forward_arg", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_parameters", "test_typing_inspect.py::GetUtilityTestCase::test_typed_dict_mypy_extension" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-06-07 15:56:44+00:00
mit
2,810
ilevkivskyi__typing_inspect-94
diff --git a/typing_inspect.py b/typing_inspect.py index d786e96..0268b16 100644 --- a/typing_inspect.py +++ b/typing_inspect.py @@ -408,7 +408,11 @@ def get_parameters(tp): else: return () elif NEW_TYPING: - if (isinstance(tp, typingGenericAlias) or + if ( + ( + isinstance(tp, typingGenericAlias) and + hasattr(tp, '__parameters__') + ) or isinstance(tp, type) and issubclass(tp, Generic) and tp is not Generic): return tp.__parameters__
ilevkivskyi/typing_inspect
b24da20b0f137e00cd8c511843ff52cb92dcf470
diff --git a/test_typing_inspect.py b/test_typing_inspect.py index 9f6be56..eaea460 100644 --- a/test_typing_inspect.py +++ b/test_typing_inspect.py @@ -14,6 +14,7 @@ from typing import ( Union, Callable, Optional, TypeVar, Sequence, AnyStr, Mapping, MutableMapping, Iterable, Generic, List, Any, Dict, Tuple, NamedTuple, ) +from typing import T as typing_T from mypy_extensions import TypedDict as METypedDict from typing_extensions import TypedDict as TETypedDict @@ -354,6 +355,10 @@ class GetUtilityTestCase(TestCase): self.assertEqual(get_parameters(Union), ()) if not LEGACY_TYPING: self.assertEqual(get_parameters(List[int]), ()) + if PY39: + self.assertEqual(get_parameters(List), ()) + else: + self.assertEqual(get_parameters(List), (typing_T,)) else: # in 3.5.3 a list has no __args__ and instead they are used in __parameters__ # in 3.5.1 the behaviour is normal again.
`get_parameters` throws exception with non-indexed types from `typing` on python 3.10 **python 3.7** ``` >>> from typing import List >>> from typing_inspect import get_parameters >>> get_parameters(List) (~T,) ``` **python 3.10.6** ``` >>> from typing import List >>> from typing_inspect import get_parameters >>> get_parameters(List) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/james.robson/code/pio_utilities/.venv/lib/python3.10/site-packages/typing_inspect.py", line 414, in get_parameters return tp.__parameters__ File "/usr/lib/python3.10/typing.py", line 984, in __getattr__ raise AttributeError(attr) AttributeError: __parameters__ ``` When you don't provide type parameters the `typing` classes lacks the `__parameters__`, `_paramspec_tvars` and `_typevar_types` members.
0.0
b24da20b0f137e00cd8c511843ff52cb92dcf470
[ "test_typing_inspect.py::GetUtilityTestCase::test_parameters" ]
[ "test_typing_inspect.py::IsUtilityTestCase::test_callable", "test_typing_inspect.py::IsUtilityTestCase::test_classvar", "test_typing_inspect.py::IsUtilityTestCase::test_final_type", "test_typing_inspect.py::IsUtilityTestCase::test_generic", "test_typing_inspect.py::IsUtilityTestCase::test_is_forward_ref", "test_typing_inspect.py::IsUtilityTestCase::test_literal_type", "test_typing_inspect.py::IsUtilityTestCase::test_optional_type", "test_typing_inspect.py::IsUtilityTestCase::test_tuple", "test_typing_inspect.py::IsUtilityTestCase::test_typevar", "test_typing_inspect.py::IsUtilityTestCase::test_union", "test_typing_inspect.py::GetUtilityTestCase::test_args_evaluated", "test_typing_inspect.py::GetUtilityTestCase::test_bound", "test_typing_inspect.py::GetUtilityTestCase::test_constraints", "test_typing_inspect.py::GetUtilityTestCase::test_generic_bases", "test_typing_inspect.py::GetUtilityTestCase::test_generic_type", "test_typing_inspect.py::GetUtilityTestCase::test_get_forward_arg", "test_typing_inspect.py::GetUtilityTestCase::test_origin", "test_typing_inspect.py::GetUtilityTestCase::test_typed_dict_mypy_extension", "test_typing_inspect.py::GetUtilityTestCase::test_typed_dict_typing_extension" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-11-21 13:07:31+00:00
mit
2,811
imageio__imageio-255
diff --git a/imageio/plugins/tifffile.py b/imageio/plugins/tifffile.py index f6d25ad..a26ea79 100644 --- a/imageio/plugins/tifffile.py +++ b/imageio/plugins/tifffile.py @@ -37,8 +37,11 @@ READ_METADATA_KEYS = ('planar_configuration', 'is_fluoview', 'is_nih', class TiffFormat(Format): - """ Provides support for a wide range of Tiff images. + + Images that contain multiple pages can be read using ``imageio.mimread()`` + to read the individual pages, or ``imageio.volread()`` to obtain a + single (higher dimensional) array. Parameters for reading ---------------------- @@ -177,17 +180,28 @@ class TiffFormat(Format): def _close(self): self._tf.close() - + def _get_length(self): - return len(self._tf) - + if self.request.mode[1] in 'vV': + return 1 # or can there be pages in pages or something? + else: + return len(self._tf) + def _get_data(self, index): - # Get data - if index < 0 or index >= len(self._tf): - raise IndexError( - 'Index out of range while reading from tiff file') - im = self._tf[index].asarray() - meta = self._meta or self._get_meta_data(index) + if self.request.mode[1] in 'vV': + # Read data as single 3D (+ color channels) array + if index != 0: + raise IndexError( + 'Tiff support no more than 1 "volume" per file') + im = self._tf.asarray() # request as singleton image + meta = self._meta + else: + # Read as 2D image + if index < 0 or index >= len(self._tf): + raise IndexError( + 'Index out of range while reading from tiff file') + im = self._tf[index].asarray() + meta = self._meta or self._get_meta_data(index) # Return array and empty meta data return im, meta @@ -216,6 +230,8 @@ class TiffFormat(Format): def _append_data(self, im, meta): if meta: self.set_meta_data(meta) + # No need to check self.request.mode; tiffile figures out whether + # this is a single page, or all page data at once. self._tf.save(np.asanyarray(im), **self._meta) def set_meta_data(self, meta):
imageio/imageio
0e0be918f05f8f2812277c9204677b05c7d6f73f
diff --git a/tests/test_tifffile.py b/tests/test_tifffile.py index 5ab5ce7..ea7ad7d 100644 --- a/tests/test_tifffile.py +++ b/tests/test_tifffile.py @@ -34,16 +34,29 @@ def test_tifffile_reading_writing(): imageio.imsave(filename1, im2) im = imageio.imread(filename1) ims = imageio.mimread(filename1) + assert im.shape == im2.shape assert (im == im2).all() assert len(ims) == 1 - + # Multiple images imageio.mimsave(filename1, [im2, im2, im2]) im = imageio.imread(filename1) ims = imageio.mimread(filename1) - assert (im == im2).all() - assert len(ims) == 3, ims[0].shape - + assert im.shape == im2.shape + assert (im == im2).all() # note: this does not imply that the shape match! + assert len(ims) == 3 + for i in range(3): + assert ims[i].shape == im2.shape + assert (ims[i] == im2).all() + + # Read all planes as one array - we call it a volume for clarity + vol = imageio.volread(filename1) + vols = imageio.mvolread(filename1) + assert vol.shape == (3, ) + im2.shape + assert len(vols) == 1 and vol.shape == vols[0].shape + for i in range(3): + assert (vol[i] == im2).all() + # remote multipage rgb file filename2 = get_remote_file('images/multipage_rgb.tif') img = imageio.mimread(filename2) @@ -67,13 +80,24 @@ def test_tifffile_reading_writing(): # Fail raises(IndexError, R.get_data, -1) raises(IndexError, R.get_data, 3) - - # Ensure imwrite write works round trip + + # Ensure imread + imwrite works round trip + filename3 = os.path.join(test_dir, 'test_tiff2.tiff') + im1 = imageio.imread(filename1) + imageio.imwrite(filename3, im1) + im3 = imageio.imread(filename3) + assert im1.ndim == 3 + assert im1.shape == im3.shape + assert (im1 == im3).all() + + # Ensure imread + imwrite works round trip - volume like filename3 = os.path.join(test_dir, 'test_tiff2.tiff') - R = imageio.imread(filename1) - imageio.imwrite(filename3, R) - R2 = imageio.imread(filename3) - assert (R == R2).all() + im1 = imageio.volread(filename1) + imageio.volwrite(filename3, im1) + im3 = imageio.volread(filename3) + assert im1.ndim == 4 + assert im1.shape == im3.shape + assert (im1 == im3).all() run_tests_if_main()
Incorrect image dimensions after reading in 3D+c TIFF I'm trying to read the following file: https://www.dropbox.com/s/0ynbscx4cmd5k91/E_z2_512_1um_CONTROL.tif?dl=1 skimage (ie tifffile) reads this correctly, but imageio doesn't — even though I thought it also used tifffile as a backend for tiffs? ```python In [1]: import imageio In [2]: from skimage import io In [3]: im_iio = imageio.imread('E_z2_512_1um_CONTROL.tif') In [4]: im_iio.shape Out[4]: (159, 320, 512) In [5]: im_ski = io.imread('E_z2_512_1um_CONTROL.tif') In [6]: im_ski.shape Out[6]: (53, 320, 512, 3) ``` What imageio is doing is reading the file in the array order present in the file (plane, channel, row, column), and squashing pln and ch dimensions together, while skimage is behaving as expected and producing two separate dimensions for pln and ch and (maybe a bit more than expected) moving ch to the last dimension, which is the dimension order expected by most scipy packages. Any ideas about what is going wrong here?
0.0
0e0be918f05f8f2812277c9204677b05c7d6f73f
[ "tests/test_tifffile.py::test_tifffile_reading_writing" ]
[ "tests/test_tifffile.py::test_tifffile_format" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2017-05-21 01:28:34+00:00
bsd-2-clause
2,812
imageio__imageio-374
diff --git a/imageio/plugins/freeimage.py b/imageio/plugins/freeimage.py index 2e52c3d..7f93cb6 100644 --- a/imageio/plugins/freeimage.py +++ b/imageio/plugins/freeimage.py @@ -195,7 +195,7 @@ class FreeimagePngFormat(FreeimageFormat): Parameters for reading ---------------------- ignoregamma : bool - Avoid gamma correction. Default False. + Avoid gamma correction. Default True. Parameters for saving --------------------- @@ -212,7 +212,7 @@ class FreeimagePngFormat(FreeimageFormat): """ class Reader(FreeimageFormat.Reader): - def _open(self, flags=0, ignoregamma=False): + def _open(self, flags=0, ignoregamma=True): # Build flags from kwargs flags = int(flags) if ignoregamma: diff --git a/imageio/plugins/pillow.py b/imageio/plugins/pillow.py index f863241..ef11c5a 100644 --- a/imageio/plugins/pillow.py +++ b/imageio/plugins/pillow.py @@ -212,7 +212,7 @@ class PNGFormat(PillowFormat): Parameters for reading ---------------------- ignoregamma : bool - Avoid gamma correction. Default False. + Avoid gamma correction. Default True. pilmode : str From the Pillow documentation: @@ -272,12 +272,16 @@ class PNGFormat(PillowFormat): """ class Reader(PillowFormat.Reader): - def _open(self, pilmode=None, as_gray=False, ignoregamma=False): + def _open(self, pilmode=None, as_gray=False, ignoregamma=True): return PillowFormat.Reader._open(self, pilmode=pilmode, as_gray=as_gray) def _get_data(self, index): im, info = PillowFormat.Reader._get_data(self, index) - if not self.request.kwargs.get("ignoregamma", False): + if not self.request.kwargs.get("ignoregamma", True): + # The gamma value in the file represents the gamma factor for the + # hardware on the system where the file was created, and is meant + # to be able to match the colors with the system on which the + # image is shown. See also issue #366 try: gamma = float(info["gamma"]) except (KeyError, ValueError):
imageio/imageio
7df4f3afd0fb54845d28237f7c794c81e195684a
diff --git a/tests/test_freeimage.py b/tests/test_freeimage.py index 93e0d74..537fe76 100644 --- a/tests/test_freeimage.py +++ b/tests/test_freeimage.py @@ -493,6 +493,30 @@ def test_other(): raises(Exception, imageio.imsave, fnamebase + ".jng", im, "JNG") +def test_gamma_correction(): + need_internet() + + fname = get_remote_file("images/kodim03.png") + + # Load image three times + im1 = imageio.imread(fname, format="PNG-FI") + im2 = imageio.imread(fname, ignoregamma=True, format="PNG-FI") + im3 = imageio.imread(fname, ignoregamma=False, format="PNG-FI") + + # Default is to ignore gamma + assert np.all(im1 == im2) + + # Test result depending of application of gamma + assert im1.mean() == im2.mean() + + # TODO: We have assert im2.mean() == im3.mean() + # But this is wrong, we want: assert im2.mean() < im3.mean() + + # test_regression_302 + for im in (im1, im2, im3): + assert im.shape == (512, 768, 3) and im.dtype == "uint8" + + if __name__ == "__main__": # test_animated_gif() run_tests_if_main() diff --git a/tests/test_pillow.py b/tests/test_pillow.py index 290246d..fed9041 100644 --- a/tests/test_pillow.py +++ b/tests/test_pillow.py @@ -332,13 +332,27 @@ def test_images_with_transparency(): assert im.shape == (24, 30, 4) -def test_regression_302(): - # When using gamma correction, the result should keep the same dtype +def test_gamma_correction(): need_internet() fname = get_remote_file("images/kodim03.png") - im = imageio.imread(fname) - assert im.shape == (512, 768, 3) and im.dtype == "uint8" + + # Load image three times + im1 = imageio.imread(fname) + im2 = imageio.imread(fname, ignoregamma=True) + im3 = imageio.imread(fname, ignoregamma=False) + + # Default is to ignore gamma + assert np.all(im1 == im2) + + # Test result depending of application of gamma + assert im1.meta["gamma"] < 1 + assert im1.mean() == im2.mean() + assert im2.mean() < im3.mean() + + # test_regression_302 + for im in (im1, im2, im3): + assert im.shape == (512, 768, 3) and im.dtype == "uint8" def test_inside_zipfile():
When should the Pillow plugin apply gamma correction? *original title: Reading PNG files differently than scipy.misc* I've been using `scipy.misc.imread`for reading (tomographic) images for processing. After a recent upgrade of my system I'm told this is deprecated in favor of `imageio.imread`. Unfortunately my images are read differently depending on which I use, namely with a different gray-scale range, as can be seen below. ``` import scipy.misc import imageio import matplotlib.pyplot as plt %matplotlib inline import numpy r = 'test.png' # attached tho this issue img_scipy = scipy.misc.imread(r) img_imageio = imageio.imread(r) plt.subplot(121) plt.title('scipy min: %s, max: %s' %(numpy.min(img_scipy), numpy.max(img_scipy))) plt.imshow(img_scipy) plt.subplot(122) plt.imshow(img_imageio) plt.title('imageio min: %s, max: %s' %(numpy.min(img_imageio), numpy.max(img_imageio))) plt.show() ``` ![output](https://user-images.githubusercontent.com/1651235/43787395-2bf373c8-9a6b-11e8-98d4-1c04190ce38c.png) [ImageJ](http://fiji.sc/) reports a maximum gray value of 162 for the image, which is what I would have expected... imageio.__version__ = '2.3.0' scipy.__version__ = '1.1.0' ![test.png](https://user-images.githubusercontent.com/1651235/43787150-a6cf810a-9a6a-11e8-9a3d-71f06eb6e2db.png) How can I get my correct gray value range back?
0.0
7df4f3afd0fb54845d28237f7c794c81e195684a
[ "tests/test_pillow.py::test_gamma_correction" ]
[ "tests/test_freeimage.py::test_get_ref_im", "tests/test_freeimage.py::test_get_fi_lib", "tests/test_freeimage.py::test_freeimage_format", "tests/test_freeimage.py::test_freeimage_lib", "tests/test_freeimage.py::test_png", "tests/test_freeimage.py::test_png_dtypes", "tests/test_freeimage.py::test_jpg", "tests/test_freeimage.py::test_jpg_more", "tests/test_freeimage.py::test_bmp", "tests/test_freeimage.py::test_gif", "tests/test_freeimage.py::test_animated_gif", "tests/test_freeimage.py::test_ico", "tests/test_freeimage.py::test_mng", "tests/test_freeimage.py::test_other", "tests/test_freeimage.py::test_gamma_correction", "tests/test_pillow.py::test_pillow_format", "tests/test_pillow.py::test_png_remote", "tests/test_pillow.py::test_jpg", "tests/test_pillow.py::test_jpg_more", "tests/test_pillow.py::test_inside_zipfile", "tests/test_pillow.py::test_scipy_imread_compat" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-09-04 11:34:26+00:00
bsd-2-clause
2,813
imageio__imageio-447
diff --git a/.gitignore b/.gitignore index ec7c106..35d4389 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,6 @@ __pychache__ # IDE .idea +.project +.pydevproject +.settings diff --git a/imageio/plugins/freeimage.py b/imageio/plugins/freeimage.py index 7f93cb6..ca7db87 100644 --- a/imageio/plugins/freeimage.py +++ b/imageio/plugins/freeimage.py @@ -26,7 +26,7 @@ class FreeimageFormat(Format): The freeimage plugin requires a `freeimage` binary. If this binary not available on the system, it can be downloaded manually from <https://github.com/imageio/imageio-binaries> by either - + - the command line script ``imageio_download_bin freeimage`` - the Python method ``imageio.plugins.freeimage.download()`` @@ -35,7 +35,7 @@ class FreeimageFormat(Format): flags : int A freeimage-specific option. In most cases we provide explicit parameters for influencing image reading. - + Parameters for saving ---------------------- flags : int @@ -145,13 +145,13 @@ class FreeimageFormat(Format): class FreeimageBmpFormat(FreeimageFormat): """ A BMP format based on the Freeimage library. - + This format supports grayscale, RGB and RGBA images. The freeimage plugin requires a `freeimage` binary. If this binary not available on the system, it can be downloaded manually from <https://github.com/imageio/imageio-binaries> by either - + - the command line script ``imageio_download_bin freeimage`` - the Python method ``imageio.plugins.freeimage.download()`` @@ -161,7 +161,7 @@ class FreeimageBmpFormat(FreeimageFormat): Whether to compress the bitmap using RLE when saving. Default False. It seems this does not always work, but who cares, you should use PNG anyway. - + """ class Writer(FreeimageFormat.Writer): @@ -182,13 +182,13 @@ class FreeimageBmpFormat(FreeimageFormat): class FreeimagePngFormat(FreeimageFormat): """ A PNG format based on the Freeimage library. - + This format supports grayscale, RGB and RGBA images. The freeimage plugin requires a `freeimage` binary. If this binary not available on the system, it can be downloaded manually from <https://github.com/imageio/imageio-binaries> by either - + - the command line script ``imageio_download_bin freeimage`` - the Python method ``imageio.plugins.freeimage.download()`` @@ -196,7 +196,7 @@ class FreeimagePngFormat(FreeimageFormat): ---------------------- ignoregamma : bool Avoid gamma correction. Default True. - + Parameters for saving --------------------- compression : {0, 1, 6, 9} @@ -263,13 +263,13 @@ class FreeimagePngFormat(FreeimageFormat): class FreeimageJpegFormat(FreeimageFormat): """ A JPEG format based on the Freeimage library. - + This format supports grayscale and RGB images. The freeimage plugin requires a `freeimage` binary. If this binary not available on the system, it can be downloaded manually from <https://github.com/imageio/imageio-binaries> by either - + - the command line script ``imageio_download_bin freeimage`` - the Python method ``imageio.plugins.freeimage.download()`` @@ -280,9 +280,9 @@ class FreeimageJpegFormat(FreeimageFormat): Default True. If 2 is given, do the rotation in Python instead of freeimage. quickread : bool - Read the image more quickly, at the expense of quality. + Read the image more quickly, at the expense of quality. Default False. - + Parameters for saving --------------------- quality : scalar @@ -296,7 +296,7 @@ class FreeimageJpegFormat(FreeimageFormat): few percent of file size). Default False. baseline : bool Save basic JPEG, without metadata or any markers. Default False. - + """ class Reader(FreeimageFormat.Reader): @@ -316,7 +316,7 @@ class FreeimageJpegFormat(FreeimageFormat): return im, meta def _rotate(self, im, meta): - """ Use Orientation information from EXIF meta data to + """ Use Orientation information from EXIF meta data to orient the image correctly. Freeimage is also supposed to support that, and I am pretty sure it once did, but now it does not, so let's just do it in Python. @@ -370,12 +370,43 @@ class FreeimageJpegFormat(FreeimageFormat): return FreeimageFormat.Writer._append_data(self, im, meta) +class FreeimagePnmFormat(FreeimageFormat): + """ A PNM format based on the Freeimage library. + + This format supports single bit (PBM), grayscale (PGM) and RGB (PPM) + images, even with ASCII or binary coding. + + The freeimage plugin requires a `freeimage` binary. If this binary + not available on the system, it can be downloaded manually from + <https://github.com/imageio/imageio-binaries> by either + + - the command line script ``imageio_download_bin freeimage`` + - the Python method ``imageio.plugins.freeimage.download()`` + + Parameters for saving + --------------------- + use_ascii : bool + Save with ASCII coding. Default True. + """ + + class Writer(FreeimageFormat.Writer): + def _open(self, flags=0, use_ascii=True): + # Build flags from kwargs + flags = int(flags) + if use_ascii: + flags |= IO_FLAGS.PNM_SAVE_ASCII + # Act as usual, but with modified flags + return FreeimageFormat.Writer._open(self, flags) + + ## Create the formats SPECIAL_CLASSES = { "jpeg": FreeimageJpegFormat, "png": FreeimagePngFormat, "bmp": FreeimageBmpFormat, + "ppm": FreeimagePnmFormat, + "ppmraw": FreeimagePnmFormat, "gif": None, # defined in freeimagemulti "ico": None, # defined in freeimagemulti "mng": None, # defined in freeimagemulti
imageio/imageio
88b2a43cea81139e1a76460c68fa9aadebadfc1e
diff --git a/tests/test_freeimage.py b/tests/test_freeimage.py index 537fe76..b8be9d4 100644 --- a/tests/test_freeimage.py +++ b/tests/test_freeimage.py @@ -23,7 +23,7 @@ def setup_module(): # This tests requires our version of the FI lib try: imageio.plugins.freeimage.download() - except imageio.core.InternetNotAllowedError: + except core.InternetNotAllowedError: # We cannot download; skip all freeimage tests need_internet() @@ -486,6 +486,23 @@ def test_mng(): # ims = imageio.imread(get_remote_file('images/mngexample.mng')) +def test_pnm(): + + for useAscii in (True, False): + for crop in (0, 1, 2): + for colors in (0, 1, 3): + fname = fnamebase + fname += "%i.%i.%i.ppm" % (useAscii, crop, colors) + rim = get_ref_im(colors, crop, isfloat=False) + imageio.imsave(fname, rim, use_ascii=useAscii) + im = imageio.imread(fname) + assert_close(rim, im, 0.1) # lossless + + # Parameter fail + raises(TypeError, imageio.imread, fname, notavalidkwarg=True) + raises(TypeError, imageio.imsave, fname, im, notavalidk=True) + + def test_other(): # Cannot save float
PPM-FI not creating ASCII output When ssing the PPM-FI format string, no ASCII output is created. ```python imageio.imwrite(path, image_data, "PPM-FI") ``` Produces for example ``` P6 200 100 65535 <binary data> ``` This is the expected behavior when using PPMRAW-FI. The expected ASCII output would be something like ``` P3 200 100 65535 1 2 3 4 5 6 ... ```
0.0
88b2a43cea81139e1a76460c68fa9aadebadfc1e
[ "tests/test_freeimage.py::test_pnm" ]
[ "tests/test_freeimage.py::test_get_ref_im", "tests/test_freeimage.py::test_get_fi_lib", "tests/test_freeimage.py::test_freeimage_format", "tests/test_freeimage.py::test_freeimage_lib", "tests/test_freeimage.py::test_png", "tests/test_freeimage.py::test_png_dtypes", "tests/test_freeimage.py::test_jpg", "tests/test_freeimage.py::test_jpg_more", "tests/test_freeimage.py::test_bmp", "tests/test_freeimage.py::test_gif", "tests/test_freeimage.py::test_animated_gif", "tests/test_freeimage.py::test_ico", "tests/test_freeimage.py::test_mng", "tests/test_freeimage.py::test_other", "tests/test_freeimage.py::test_gamma_correction" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-16 23:56:40+00:00
bsd-2-clause
2,814
imageio__imageio-510
diff --git a/imageio/core/format.py b/imageio/core/format.py index 34ce741..c5e093a 100644 --- a/imageio/core/format.py +++ b/imageio/core/format.py @@ -30,12 +30,22 @@ a format object using ``imageio.formats.add_format()``. # imageio.get_reader and imageio.get_writer. import os +import sys import numpy as np from . import Array, asarray +MODENAMES = { + "i": "single-image", + "I": "multi-image", + "v": "single-volume", + "V": "multi-volume", + "?": "any-mode", +} + + class Format(object): """ Represents an implementation to read/write a particular file format @@ -153,8 +163,9 @@ class Format(object): """ select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" if select_mode not in self.modes: + modename = MODENAMES.get(select_mode, select_mode) raise RuntimeError( - "Format %s cannot read in mode %r" % (self.name, select_mode) + "Format %s cannot read in %s mode" % (self.name, modename) ) return self.Reader(self, request) @@ -167,8 +178,9 @@ class Format(object): """ select_mode = request.mode[1] if request.mode[1] in "iIvV" else "" if select_mode not in self.modes: + modename = MODENAMES.get(select_mode, select_mode) raise RuntimeError( - "Format %s cannot write in mode %r" % (self.name, select_mode) + "Format %s cannot write in %s mode" % (self.name, modename) ) return self.Writer(self, request) @@ -407,7 +419,10 @@ class Format(object): return self.iter_data() def __len__(self): - return self.get_length() + n = self.get_length() + if n == float("inf"): + n = sys.maxsize + return n # To implement diff --git a/imageio/core/functions.py b/imageio/core/functions.py index 71a7366..3a579b0 100644 --- a/imageio/core/functions.py +++ b/imageio/core/functions.py @@ -81,6 +81,7 @@ import numpy as np from . import Request, RETURN_BYTES from .. import formats +from .format import MODENAMES MEMTEST_DEFAULT_MIM = "256MB" @@ -176,8 +177,9 @@ def get_reader(uri, format=None, mode="?", **kwargs): else: format = formats.search_read_format(request) if format is None: + modename = MODENAMES.get(mode, mode) raise ValueError( - "Could not find a format to read the specified file " "in mode %r" % mode + "Could not find a format to read the specified file in %s mode" % modename ) # Return its reader object @@ -220,8 +222,9 @@ def get_writer(uri, format=None, mode="?", **kwargs): else: format = formats.search_write_format(request) if format is None: + modename = MODENAMES.get(mode, mode) raise ValueError( - "Could not find a format to write the specified file " "in mode %r" % mode + "Could not find a format to write the specified file in %s mode" % modename ) # Return its writer object diff --git a/imageio/plugins/ffmpeg.py b/imageio/plugins/ffmpeg.py index ba0d8e0..e0525b3 100644 --- a/imageio/plugins/ffmpeg.py +++ b/imageio/plugins/ffmpeg.py @@ -286,6 +286,10 @@ class FfmpegFormat(Format): self.request._video = None if self.request.filename in ["<video%i>" % i for i in range(10)]: self.request._video = self.request.filename + # Specify input framerate? + if self.request._video: + if "-framerate" not in str(self._arg_input_params): + self._arg_input_params.extend(["-framerate", str(float(fps or 15))]) # Get local filename if self.request._video: index = int(self.request._video[-2]) diff --git a/imageio/plugins/tifffile.py b/imageio/plugins/tifffile.py index d7e84ed..4bc6392 100644 --- a/imageio/plugins/tifffile.py +++ b/imageio/plugins/tifffile.py @@ -316,7 +316,7 @@ class TiffFormat(Format): if key in WRITE_METADATA_KEYS: # Special case of previously read `predictor` int value # 1(=NONE) translation to False expected by TiffWriter.save - if key=="predictor" and not isinstance(value, bool): + if key == "predictor" and not isinstance(value, bool): self._meta[key] = value > 1 else: self._meta[key] = value
imageio/imageio
09c34ccd708e1913c8a58459f9db54dbf14210f9
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py index 51af080..3fecb3a 100644 --- a/tests/test_ffmpeg.py +++ b/tests/test_ffmpeg.py @@ -4,6 +4,7 @@ from io import BytesIO import os +import sys import gc import time import threading @@ -100,6 +101,16 @@ def test_select(): assert imageio.formats.search_read_format(core.Request(fname1, "rI")) is F +def test_integer_reader_length(): + # Avoid regression for #280 + r = imageio.get_reader("imageio:cockatoo.mp4") + assert r.get_length() == float("inf") + assert isinstance(len(r), int) + assert len(r) == sys.maxsize + assert bool(r) + assert True if r else False + + def test_read_and_write(): R = imageio.read(get_remote_file("images/cockatoo.mp4"), "ffmpeg")
`if imageio.get_reader(...): pass` fails for FfmpegFormat.Reader objects The following statement: `if imageio.get_reader('<video0>'): pass` raises 'OverflowError: cannot convert float infinity to integer' (at least in Python 2.7) It seems that `FfmpegFormat.Reader` has no `__nonzero__()` method (nor `__bool__()` for Python 3?), so the `__len__()` method is evaluated, which, in this case, returns `float('inf')`. A quick hack for anyone running into this issue could be to use `if ... is not None`. (see [stackoverflow](https://stackoverflow.com/a/7816439/4720018))
0.0
09c34ccd708e1913c8a58459f9db54dbf14210f9
[ "tests/test_ffmpeg.py::test_integer_reader_length" ]
[ "tests/test_ffmpeg.py::test_get_exe_installed", "tests/test_ffmpeg.py::test_get_exe_env", "tests/test_ffmpeg.py::test_select", "tests/test_ffmpeg.py::test_read_and_write", "tests/test_ffmpeg.py::test_write_not_contiguous", "tests/test_ffmpeg.py::test_reader_more", "tests/test_ffmpeg.py::test_writer_more", "tests/test_ffmpeg.py::test_writer_file_properly_closed", "tests/test_ffmpeg.py::test_writer_pixelformat_size_verbose", "tests/test_ffmpeg.py::test_writer_ffmpeg_params", "tests/test_ffmpeg.py::test_writer_wmv", "tests/test_ffmpeg.py::test_framecatcher", "tests/test_ffmpeg.py::test_reverse_read" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-18 13:01:41+00:00
bsd-2-clause
2,815
imageio__imageio-678
diff --git a/imageio/core/request.py b/imageio/core/request.py index d24e259..d2ddae2 100644 --- a/imageio/core/request.py +++ b/imageio/core/request.py @@ -244,8 +244,11 @@ class Request(object): # Set extension if self._filename is not None: - parts = urlparse(self._filename) - ext = Path(parts.path).suffix.lower() + if self._uri_type in (URI_FILENAME, URI_ZIPPED): + path = self._filename + else: + path = urlparse(self._filename).path + ext = Path(path).suffix.lower() self._extension = ext if ext != "" else None def _parse_uri(self, uri):
imageio/imageio
e1226c751fb30196879620977d6f4072c45f8719
diff --git a/tests/test_core.py b/tests/test_core.py index bcb584e..9700f5e 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -783,6 +783,21 @@ def test_imwrite_not_array_like(): imageio.imwrite("foo.bmp", "asd") +def test_imwrite_symbol_name(): + # this is a regression test for https://github.com/imageio/imageio/issues/674 + if sys.platform == "linux": + name = """#!~:@$%^&`-+{};',.()? []_=.jpg""" + elif sys.platform == "win32": + name = """#!~@$%^&`-+{};',.() []_=.jpg""" + elif sys.platform == "darwin": + name = """#!~@$%^&`-+{};',.()? []_=.jpg""" + else: + pytest.skip("Unknown OS.") + tmp_request = imageio.core.Request(name, "w") + assert tmp_request.extension == ".jpg" + tmp_request.finish() + + def test_legacy_empty_image(): with pytest.raises(RuntimeError): with iio.imopen("foo.bmp", "wI", format="GIF-PIL") as file:
imageiov2.10.1. The imwrite will raise ValueError when filename include "#". Imageio V2.10.1 ``` import imageio import numpy as np imageio.imwrite('#1.jpg', np.zeros([512, 512, 3], dtype=np.uint8)) ``` It will raise ValueError: Could not find a format to read the specified file in ImageMode.single_image mode. But it will good. No raise. ``` imageio.imwrite('#1.jpg', np.zeros([512, 512, 3], dtype=np.uint8), '.jpg') ```
0.0
e1226c751fb30196879620977d6f4072c45f8719
[ "tests/test_core.py::test_imwrite_symbol_name" ]
[ "tests/test_core.py::test_fetching", "tests/test_core.py::test_request", "tests/test_core.py::test_request_read_sources", "tests/test_core.py::test_request_save_sources", "tests/test_core.py::test_request_seekable_file_object", "tests/test_core.py::test_request_file_no_seek", "tests/test_core.py::test_util_dict", "tests/test_core.py::test_util_get_platform", "tests/test_core.py::test_util_asarray", "tests/test_core.py::test_util_progres_bar", "tests/test_core.py::test_util_image_as_uint", "tests/test_core.py::test_util_has_has_module", "tests/test_core.py::test_to_nbytes_correct[1-1_0]", "tests/test_core.py::test_to_nbytes_correct[1-1_1]", "tests/test_core.py::test_to_nbytes_correct[8B-8]", "tests/test_core.py::test_to_nbytes_correct[1MB-1000000]", "tests/test_core.py::test_to_nbytes_correct[1M-1000000]", "tests/test_core.py::test_to_nbytes_correct[1GiB-1073741824]", "tests/test_core.py::test_to_nbytes_correct[1.5TB-1500000000000.0]", "tests/test_core.py::test_to_nbytes_incorrect[1mb]", "tests/test_core.py::test_to_nbytes_incorrect[1Giib]", "tests/test_core.py::test_to_nbytes_incorrect[GB]", "tests/test_core.py::test_to_nbytes_incorrect[1.3.2TB]", "tests/test_core.py::test_to_nbytes_incorrect[8b]", "tests/test_core.py::test_example_plugin", "tests/test_core.py::test_imwrite_not_subclass", "tests/test_core.py::test_imwrite_not_array_like", "tests/test_core.py::test_legacy_empty_image", "tests/test_core.py::test_imopen_unsupported_iomode", "tests/test_core.py::test_imopen_no_plugin_found", "tests/test_core.py::test_imopen_unregistered_plugin[.jpg]", "tests/test_core.py::test_plugin_selection_failure", "tests/test_core.py::test_plugin_selection_success[.jpg]", "tests/test_core.py::test_legacy_object_image_writing", "tests/test_core.py::test_request_mode_backwards_compatibility", "tests/test_core.py::test_faulty_legacy_mode_access", "tests/test_core.py::test_mvolread_out_of_bytes", "tests/test_core.py::test_invalid_explicit_plugin" ]
{ "failed_lite_validators": [ "has_media" ], "has_test_patch": true, "is_lite": false }
2021-11-05 08:12:21+00:00
bsd-2-clause
2,816
imankulov__linguee-api-51
diff --git a/linguee_api/parser_utils.py b/linguee_api/parser_utils.py index cadea2b..6708037 100644 --- a/linguee_api/parser_utils.py +++ b/linguee_api/parser_utils.py @@ -55,3 +55,11 @@ def take_first_item(variants) -> Optional[str]: if not variants["item"]: return None return variants["item"][0] + + +def take_first_non_empty_item(variants) -> Optional[str]: + """Take the first non-empty item variant and normalize.""" + for item in variants["item"]: + if item: + return item + return None diff --git a/linguee_api/parsers.py b/linguee_api/parsers.py index 77527d7..d93a36c 100644 --- a/linguee_api/parsers.py +++ b/linguee_api/parsers.py @@ -13,7 +13,12 @@ from linguee_api.models import ( SearchResultOrError, UsageFrequency, ) -from linguee_api.parser_utils import concat_values, normalize, take_first_item +from linguee_api.parser_utils import ( + concat_values, + normalize, + take_first_item, + take_first_non_empty_item, +) class IParser(abc.ABC): @@ -237,12 +242,19 @@ lemma_schema = [ attr="onclick", callback=parse_audio_links, ), - String( + Group( name="usage_frequency", - quant="?", - css="span.tag_c", - attr="class", - callback=parse_usage_frequency, + quant=1, + callback=take_first_non_empty_item, + children=[ + String( + name="item", + quant="*", + css="span.tag_c", + attr="class", + callback=parse_usage_frequency, + ), + ], ), Group( name="examples",
imankulov/linguee-api
7ca9ca3dadc77997e7952003f03d7aa8a48a130f
diff --git a/tests/parsers/test_search_result.py b/tests/parsers/test_search_result.py index bc71300..ea77397 100644 --- a/tests/parsers/test_search_result.py +++ b/tests/parsers/test_search_result.py @@ -93,6 +93,7 @@ async def test_parser_should_find_correction( ("wünschen", "de", "en"), ("envisage", "en", "zh"), ("envisage", "en", "sv"), + ("über", "de", "en"), ], ) @pytest.mark.asyncio
500 error for "über" xextract.parsers.ParsingError: Parser String(name="usage_frequency") matched 2 elements ("?" expected). looks like there are two span with tag_c class.
0.0
7ca9ca3dadc77997e7952003f03d7aa8a48a130f
[ "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[\\xfcber-de-en]" ]
[ "tests/parsers/test_search_result.py::test_parser_should_detect_not_found[constibado-pt-en-True]", "tests/parsers/test_search_result.py::test_parser_should_detect_not_found[M\\xf6glichkei-de-en-False]", "tests/parsers/test_search_result.py::test_parser_should_detect_not_found[esgotar-pt-en-False]", "tests/parsers/test_search_result.py::test_parser_should_detect_not_found[not", "tests/parsers/test_search_result.py::test_parser_should_detect_not_found[xxxxzzzz-pt-en-True]", "tests/parsers/test_search_result.py::test_parser_should_find_translation_examples", "tests/parsers/test_search_result.py::test_parser_should_find_correction[constibado-pt-en-constipado]", "tests/parsers/test_search_result.py::test_parser_should_find_correction[M\\xf6glichkei-de-en-m\\xf6glichkeit]", "tests/parsers/test_search_result.py::test_parser_should_find_correction[esgotar-pt-en-None]", "tests/parsers/test_search_result.py::test_parser_should_find_correction[xxxxzzzz-pt-en-None]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[esgotar-pt-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[M\\xf6glichkei-de-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[obrigado-pt-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[not", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[einfach-de-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[Tisch-de-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[w\\xfcnschen-de-en]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[envisage-en-zh]", "tests/parsers/test_search_result.py::test_parse_to_dict_should_return_parseable_result[envisage-en-sv]", "tests/parsers/test_search_result.py::test_parser_should_find_grammar_info_in_german_verbs", "tests/parsers/test_search_result.py::test_parser_should_process_examples_without_links", "tests/parsers/test_search_result.py::test_parser_should_find_almost_always_usage_frequency", "tests/parsers/test_search_result.py::test_parser_should_find_often_usage_frequency", "tests/parsers/test_search_result.py::test_parser_should_find_lemma_forms", "tests/parsers/test_search_result.py::test_parser_should_find_lemma_forms_for_verbs" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-04-25 17:01:33+00:00
mit
2,817
imapex__ciscosparkbot-12
diff --git a/ciscosparkbot/Spark.py b/ciscosparkbot/Spark.py index d91685a..f9ca3f8 100644 --- a/ciscosparkbot/Spark.py +++ b/ciscosparkbot/Spark.py @@ -9,6 +9,7 @@ Classes: from flask import Flask, request from ciscosparkapi import CiscoSparkAPI +from ciscosparkbot.models import Response import sys import json @@ -257,8 +258,13 @@ class SparkBot(Flask): else: pass - # send_message_to_room(room_id, reply) - if reply: + # allow command handlers to craft their own Spark message + if reply and isinstance(reply, Response): + reply.roomId = room_id + reply = reply.as_dict() + self.spark.messages.create(**reply) + reply = "ok" + elif reply: self.spark.messages.create(roomId=room_id, markdown=reply) return reply diff --git a/ciscosparkbot/__about__.py b/ciscosparkbot/__about__.py index f14e5b2..7c50a86 100644 --- a/ciscosparkbot/__about__.py +++ b/ciscosparkbot/__about__.py @@ -7,7 +7,7 @@ __title__ = "ciscosparkbot" __summary__ = "Python Bot for Cisco Spark" __uri__ = "http://github.com/imapex/ciscosparkbot" -__version__ = "0.5.5" +__version__ = "0.6.2" __author__ = "Cisco Systems, Inc." __email__ = "[email protected]" diff --git a/ciscosparkbot/models.py b/ciscosparkbot/models.py new file mode 100644 index 0000000..979670b --- /dev/null +++ b/ciscosparkbot/models.py @@ -0,0 +1,64 @@ +import json + + +class Response(object): + def __init__(self, attributes=None): + if attributes: + self.attributes = attributes + else: + self.attributes = dict() + self.attributes['text'] = None + self.attributes['roomId'] = None + self.attributes['markdown'] = None + self.attributes['html'] = None + self.attributes['files'] = list() + + @property + def text(self): + return self.attributes['text'] + + @text.setter + def text(self, val): + self.attributes['text'] = val + + @property + def files(self): + return self.attributes['files'] + + @files.setter + def files(self, val): + self.attributes['files'].append(val) + + @property + def roomId(self): + return self.attributes['roomId'] + + @roomId.setter + def roomId(self, val): + self.attributes['roomId'] = val + + @property + def markdown(self): + return self.attributes['markdown'] + + @markdown.setter + def markdown(self, val): + self.attributes['markdown'] = val + + @property + def html(self): + return self.attributes['html'] + + @html.setter + def html(self, val): + self.attributes['html'] = val + + def as_dict(self): + ret = dict() + for k, v in self.attributes.items(): + if v: + ret[k] = v + return ret + + def json(self): + return json.dumps(self.attributes) diff --git a/requirements.txt b/requirements.txt index a1cb3da..7faef01 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ Flask==0.12.1 -ciscosparkapi==0.5.5 \ No newline at end of file +ciscosparkapi==0.10 diff --git a/sample.py b/sample.py index 54165ce..7e620c6 100644 --- a/sample.py +++ b/sample.py @@ -2,9 +2,9 @@ """ Sample code for using ciscosparkbot """ - import os from ciscosparkbot import SparkBot +from ciscosparkbot.models import Response __author__ = "imapex" __author_email__ = "[email protected]" @@ -27,12 +27,23 @@ def do_something(incoming_msg): return "i did what you said - {}".format(incoming_msg.text) +def ret_message(incoming_msg): + m = Response() + u = 'https://sayingimages.com/wp-content/uploads/' + u = u + 'aaaaaalll-righty-then-alrighty-meme.jpg' + m.files = u + return m + + # Create a new bot bot = SparkBot(bot_app_name, spark_bot_token=spark_token, spark_bot_url=bot_url, spark_bot_email=bot_email, debug=True) + # Add new command bot.add_command('/dosomething', 'help for do something', do_something) +bot.add_command('/demo', 'sampel that allows spark message to be returned', + ret_message) # Run Bot bot.run(host='0.0.0.0', port=5000)
imapex/ciscosparkbot
ccc0097a556e6675f97ad5045df83b9cd1af37ed
diff --git a/tests/models.py b/tests/models.py new file mode 100644 index 0000000..fa4a022 --- /dev/null +++ b/tests/models.py @@ -0,0 +1,40 @@ +import unittest +from ciscosparkbot.models import Response + + +class ModelTests(unittest.TestCase): + + def test_response_text(self): + r = Response() + r.text = "hello" + self.assertEqual(r.text, "hello") + + def test_response_files(self): + r = Response() + r.files = "someurl" + self.assertEqual(r.files[0], "someurl") + + def test_response_roomid(self): + r = Response() + r.roomId = "someid" + self.assertEqual(r.roomId, "someid") + + def test_response_markdown(self): + r = Response() + r.markdown = "**some markdown**" + self.assertEqual(r.markdown, "**some markdown**") + + def test_response_html(self): + r = Response() + r.html = "<h1>some html</h1>" + self.assertEqual(r.html, "<h1>some html</h1>") + + def test_response_json(self): + r = Response() + r.text = "foo" + self.assertIn('text', r.json()) + + def test_response_as_dict(self): + r = Response() + r.text = "foo" + self.assertIn('text', r.as_dict())
Allow callbacks to return `ciscosparkapi.Message` objects This will allow extended functionality such as files, html, and mentions
0.0
ccc0097a556e6675f97ad5045df83b9cd1af37ed
[ "tests/models.py::ModelTests::test_response_as_dict", "tests/models.py::ModelTests::test_response_files", "tests/models.py::ModelTests::test_response_html", "tests/models.py::ModelTests::test_response_json", "tests/models.py::ModelTests::test_response_markdown", "tests/models.py::ModelTests::test_response_roomid", "tests/models.py::ModelTests::test_response_text" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-05-10 20:17:49+00:00
apache-2.0
2,818
indico__flask-multipass-72
diff --git a/CHANGES.rst b/CHANGES.rst index 4a63425..0817943 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,11 @@ Changelog ========= +Version 0.5.1 +------------- + +- Fix compatibility with Python 3.8 and 3.9 + Version 0.5 ----------- diff --git a/flask_multipass/__init__.py b/flask_multipass/__init__.py index 97505a8..ea6d783 100644 --- a/flask_multipass/__init__.py +++ b/flask_multipass/__init__.py @@ -13,7 +13,7 @@ from .group import Group from .identity import IdentityProvider -__version__ = '0.5' +__version__ = '0.5.1' __all__ = ('Multipass', 'AuthProvider', 'IdentityProvider', 'AuthInfo', 'IdentityInfo', 'Group', 'MultipassException', 'AuthenticationFailed', 'IdentityRetrievalFailed', 'GroupRetrievalFailed', 'NoSuchUser', 'InvalidCredentials') diff --git a/flask_multipass/util.py b/flask_multipass/util.py index f328970..4131f2e 100644 --- a/flask_multipass/util.py +++ b/flask_multipass/util.py @@ -4,6 +4,7 @@ # Flask-Multipass is free software; you can redistribute it # and/or modify it under the terms of the Revised BSD License. +import sys from functools import wraps from importlib.metadata import entry_points as importlib_entry_points from inspect import getmro, isclass @@ -143,14 +144,17 @@ def resolve_provider_type(base, type_, registry=None): if registry is not None and type_ in registry: cls = registry[type_] else: - entry_points = importlib_entry_points(group=base._entry_point, name=type_) + if sys.version_info < (3, 10): + entry_points = {ep for ep in importlib_entry_points().get(base._entry_point, []) if ep.name == type_} + else: + entry_points = importlib_entry_points(group=base._entry_point, name=type_) if not entry_points: raise ValueError('Unknown type: ' + type_) elif len(entry_points) != 1: # TODO: remove the getattr check after dropping python 3.8 defs = ', '.join(getattr(ep, 'module', ep.value) for ep in entry_points) raise RuntimeError(f'Type {type_} is not unique. Defined in {defs}') - entry_point = entry_points[0] + entry_point = list(entry_points)[0] cls = entry_point.load() if not issubclass(cls, base): raise TypeError(f'Found a class {cls} which is not a subclass of {base}')
indico/flask-multipass
d7d885326f8f9f40126af2b7dda4808d222391b7
diff --git a/tests/test_core.py b/tests/test_core.py index 0adada1..ef1e60b 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -218,3 +218,12 @@ def test_handle_auth_error_with_redirect(mocker): multipass.handle_auth_error(AuthenticationFailed(), redirect_to_login=True) assert flash.called redirect.assert_called_with(app.config['MULTIPASS_LOGIN_URLS'][0]) + + +def test_load_providers_from_entrypoints(): + app = Flask('test') + app.config['SECRET_KEY'] = 'testing' + app.config['MULTIPASS_AUTH_PROVIDERS'] = {'test': {'type': 'static'}} + app.config['MULTIPASS_IDENTITY_PROVIDERS'] = {'test': {'type': 'static'}} + app.config['MULTIPASS_PROVIDER_MAP'] = {'test': 'test'} + Multipass(app) diff --git a/tests/test_util.py b/tests/test_util.py index 4fc6532..250fbee 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -4,6 +4,7 @@ # Flask-Multipass is free software; you can redistribute it # and/or modify it under the terms of the Revised BSD License. +import sys from importlib.metadata import EntryPoint import pytest @@ -170,7 +171,7 @@ def test_login_view(mocker): class DummyBase: - _entry_point = 'dummy' + _entry_point = 'fakeproviders' class Dummy(DummyBase): @@ -190,21 +191,29 @@ class MockEntryPoint(EntryPoint): return mapping[self.name] -def mock_entry_point(name): +def mock_entry_point(name, n=0): # we can't override MockEntryPoint's `__init__` to pass the default values since it's using # a namedtuple in Python<3.11, and required args are handled via __new__ in namedtuple - return MockEntryPoint(name, 'dummy.value', 'dummy.group') + return MockEntryPoint(name, f'dummy.value.{n}', 'dummy.group') @pytest.fixture def mock_entry_points(monkeypatch): - def _mock_entry_points(*, group, name): - return { - 'dummy': [mock_entry_point('dummy')], - 'fake': [mock_entry_point('fake')], - 'multi': [mock_entry_point('dummy'), mock_entry_point('fake')], - 'unknown': [] - }[name] + MOCK_EPS = { + 'fakeproviders': [ + mock_entry_point('dummy'), + mock_entry_point('fake'), + mock_entry_point('multi'), + mock_entry_point('multi', 1), + ] + } + + if sys.version_info < (3, 10): + def _mock_entry_points(): + return MOCK_EPS + else: + def _mock_entry_points(*, group, name): + return [ep for ep in MOCK_EPS[group] if ep.name == name] monkeypatch.setattr('flask_multipass.util.importlib_entry_points', _mock_entry_points)
Type error on init_app ``` File ".../site-packages/flask_multipass/util.py", line 146, in resolve_provider_type entry_points = importlib_entry_points(group=base._entry_point, name=type_) TypeError: entry_points() for an unexpected keyword argument 'group' ``` I see this error and version 0.5 dies while loading. It's trying to call `importlib.metadata.entrypoints` but that doesn't have a group argument.
0.0
d7d885326f8f9f40126af2b7dda4808d222391b7
[ "tests/test_util.py::test_resolve_provider_type_invalid", "tests/test_util.py::test_resolve_provider_type" ]
[ "tests/test_core.py::test_init_app_twice", "tests/test_core.py::test_init_app_late", "tests/test_core.py::test_init_app_immediately", "tests/test_core.py::test_multiple_apps", "tests/test_core.py::test_initialize_providers", "tests/test_core.py::test_initialize_providers_unique", "tests/test_core.py::test_create_login_rule", "tests/test_core.py::test_create_login_rule_disabled", "tests/test_core.py::test_render_template", "tests/test_core.py::test_next_url", "tests/test_core.py::test_next_url_invalid", "tests/test_core.py::test_validate_next_url[foo-True]", "tests/test_core.py::test_validate_next_url[/foo-True]", "tests/test_core.py::test_validate_next_url[/foo?bar-True]", "tests/test_core.py::test_validate_next_url[/foo#bar-True]", "tests/test_core.py::test_validate_next_url[//localhost-True]", "tests/test_core.py::test_validate_next_url[//localhost/foo-True]", "tests/test_core.py::test_validate_next_url[http://localhost-True]", "tests/test_core.py::test_validate_next_url[https://localhost/-True]", "tests/test_core.py::test_validate_next_url[//evil-False]", "tests/test_core.py::test_validate_next_url[//evil.com-False]", "tests/test_core.py::test_validate_next_url[//evil.com:80-False]", "tests/test_core.py::test_validate_next_url[http://evil.com-False]", "tests/test_core.py::test_validate_next_url[https://evil.com-False]", "tests/test_core.py::test_login_finished", "tests/test_core.py::test_login_finished_returns", "tests/test_core.py::test_identity_handler", "tests/test_core.py::test_login_check", "tests/test_core.py::test_handle_auth_error", "tests/test_core.py::test_handle_auth_error_with_redirect", "tests/test_util.py::test_get_canonical_provider_map[config_map0-canonical_map0]", "tests/test_util.py::test_get_canonical_provider_map[config_map1-canonical_map1]", "tests/test_util.py::test_get_canonical_provider_map[config_map2-canonical_map2]", "tests/test_util.py::test_get_canonical_provider_map[config_map3-canonical_map3]", "tests/test_util.py::test_get_canonical_provider_map[config_map4-canonical_map4]", "tests/test_util.py::test_get_canonical_provider_map[config_map5-canonical_map5]", "tests/test_util.py::test_get_canonical_provider_map[config_map6-canonical_map6]", "tests/test_util.py::test_get_state_app_not_initialized", "tests/test_util.py::test_get_state_explicit", "tests/test_util.py::test_get_state", "tests/test_util.py::test_convert_provider_data[provider_data0-mapping0-None-result0]", "tests/test_util.py::test_convert_provider_data[provider_data1-mapping1-None-result1]", "tests/test_util.py::test_convert_provider_data[provider_data2-mapping2-None-result2]", "tests/test_util.py::test_convert_provider_data[provider_data3-mapping3-key_filter3-result3]", "tests/test_util.py::test_convert_provider_data[provider_data4-mapping4-key_filter4-result4]", "tests/test_util.py::test_convert_provider_data[provider_data5-mapping5-key_filter5-result5]", "tests/test_util.py::test_convert_provider_data[provider_data6-mapping6-key_filter6-result6]", "tests/test_util.py::test_convert_provider_data[provider_data7-mapping7-key_filter7-result7]", "tests/test_util.py::test_convert_provider_data[provider_data8-mapping8-key_filter8-result8]", "tests/test_util.py::test_convert_app_data[app_data0-mapping0-None-result0]", "tests/test_util.py::test_convert_app_data[app_data1-mapping1-key_filter1-result1]", "tests/test_util.py::test_convert_app_data[app_data2-mapping2-None-result2]", "tests/test_util.py::test_convert_app_data[app_data3-mapping3-None-result3]", "tests/test_util.py::test_convert_app_data[app_data4-mapping4-None-result4]", "tests/test_util.py::test_convert_app_data[app_data5-mapping5-None-result5]", "tests/test_util.py::test_convert_app_data[app_data6-mapping6-None-result6]", "tests/test_util.py::test_convert_app_data[app_data7-mapping7-None-result7]", "tests/test_util.py::test_convert_app_data[app_data8-mapping8-key_filter8-result8]", "tests/test_util.py::test_convert_app_data[app_data9-mapping9-key_filter9-result9]", "tests/test_util.py::test_convert_app_data[app_data10-mapping10-key_filter10-result10]", "tests/test_util.py::test_convert_app_data[app_data11-mapping11-key_filter11-result11]", "tests/test_util.py::test_convert_app_data[app_data12-mapping12-key_filter12-result12]", "tests/test_util.py::test_convert_app_data[app_data13-mapping13-key_filter13-result13]", "tests/test_util.py::test_convert_app_data[app_data14-mapping14-key_filter14-result14]", "tests/test_util.py::test_convert_app_data[app_data15-mapping15-key_filter15-result15]", "tests/test_util.py::test_convert_app_data[app_data16-mapping16-key_filter16-result16]", "tests/test_util.py::test_convert_app_data[app_data17-mapping17-key_filter17-result17]", "tests/test_util.py::test_convert_app_data[app_data18-mapping18-key_filter18-result18]", "tests/test_util.py::test_convert_app_data[app_data19-mapping19-key_filter19-result19]", "tests/test_util.py::test_convert_app_data[app_data20-mapping20-key_filter20-result20]", "tests/test_util.py::test_convert_app_data[app_data21-mapping21-key_filter21-result21]", "tests/test_util.py::test_convert_app_data[app_data22-mapping22-key_filter22-result22]", "tests/test_util.py::test_convert_app_data[app_data23-mapping23-key_filter23-result23]", "tests/test_util.py::test_convert_app_data[app_data24-mapping24-key_filter24-result24]", "tests/test_util.py::test_convert_app_data[app_data25-mapping25-key_filter25-result25]", "tests/test_util.py::test_get_provider_base", "tests/test_util.py::test_get_provider_base_invalid", "tests/test_util.py::test_login_view", "tests/test_util.py::test_resolve_provider_type_class", "tests/test_util.py::test_validate_provider_map[False-auth_providers0-identity_providers0-provider_map0]", "tests/test_util.py::test_validate_provider_map[False-auth_providers1-identity_providers1-provider_map1]", "tests/test_util.py::test_validate_provider_map[False-auth_providers2-identity_providers2-provider_map2]", "tests/test_util.py::test_validate_provider_map[False-auth_providers3-identity_providers3-provider_map3]", "tests/test_util.py::test_validate_provider_map[True-auth_providers4-identity_providers4-provider_map4]", "tests/test_util.py::test_validate_provider_map[True-auth_providers5-identity_providers5-provider_map5]", "tests/test_util.py::test_classproperty", "tests/test_util.py::test_supports_meta_no_support_attrs", "tests/test_util.py::test_supports_meta_ok[True]", "tests/test_util.py::test_supports_meta_ok[False]", "tests/test_util.py::test_supports_meta_fail[True]", "tests/test_util.py::test_supports_meta_fail[False]", "tests/test_util.py::test_supports_meta_inheritance[True]", "tests/test_util.py::test_supports_meta_inheritance[False]", "tests/test_util.py::test_supports_meta_multi", "tests/test_util.py::test_supports_meta_default_true" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-06 18:31:01+00:00
bsd-3-clause
2,819
inducer__pudb-260
diff --git a/pudb/ui_tools.py b/pudb/ui_tools.py index 9997cad..a398865 100644 --- a/pudb/ui_tools.py +++ b/pudb/ui_tools.py @@ -1,6 +1,6 @@ from __future__ import absolute_import, division, print_function import urwid -from urwid.util import _target_encoding +from urwid.util import _target_encoding, calc_width # generic urwid helpers ------------------------------------------------------- @@ -14,7 +14,7 @@ def make_canvas(txt, attr, maxcol, fill_attr=None): # filter out zero-length attrs line_attr = [(aname, l) for aname, l in line_attr if l > 0] - diff = maxcol - len(line) + diff = maxcol - calc_width(line, 0, len(line)) if diff > 0: line += " "*diff line_attr.append((fill_attr, diff))
inducer/pudb
fef17b6f33da7d03758c150b37cd2f84754aa01d
diff --git a/test/test_make_canvas.py b/test/test_make_canvas.py index 093cd63..b1ed681 100644 --- a/test/test_make_canvas.py +++ b/test/test_make_canvas.py @@ -49,6 +49,19 @@ def test_byte_boundary(): ) assert list(canvas.content()) == [[('var value', None, b'aaaaaa\xc3\xa9')]] +def test_wide_chars(): + text = u"data: '中文'" + canvas = make_canvas( + txt=[text], + attr=[[('var label', 6), ('var value', 4)]], + maxcol=47, + ) + assert list(canvas.content()) == [[ + ('var label', None, b'data: '), + ('var value', None, u"'中文'".encode('utf-8')), + (None, None, b' '*(47 - 12)), # 10 chars, 2 of which are double width + ]] + if __name__ == "__main__": import sys
"Canvas text is wider than the maxcol specified" with Chinese The full script is simple: ``` data = "中文" ``` Run it with ``` pudb3 a.py ``` And press "n" I got this: ``` Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/pudb/__init__.py", line 83, in runscript dbg._runscript(mainpyfile) File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 419, in _runscript self.run(statement, globals=globals_, locals=locals_) File "/usr/lib/python3.6/bdb.py", line 431, in run exec(cmd, globals, locals) File "<string>", line 1, in <module> File "a.py", line 1, in <module> data = "中文" File "/usr/lib/python3.6/bdb.py", line 52, in trace_dispatch return self.dispatch_return(frame, arg) File "/usr/lib/python3.6/bdb.py", line 93, in dispatch_return self.user_return(frame, arg) File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 385, in user_return self.interaction(frame) File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 339, in interaction show_exc_dialog=show_exc_dialog) File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 2079, in call_with_ui return f(*args, **kwargs) File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 2307, in interaction self.event_loop() File "/usr/lib/python3.6/site-packages/pudb/debugger.py", line 2265, in event_loop canvas = toplevel.render(self.size, focus=True) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/container.py", line 2085, in render focus = focus and self.focus_position == i) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/container.py", line 1526, in render canv = w.render((maxcol, rows), focus=focus and item_focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/container.py", line 1526, in render canv = w.render((maxcol, rows), focus=focus and item_focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/urwid/listbox.py", line 485, in render canvas = widget.render((maxcol,)) File "/usr/lib/python3.6/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/usr/lib/python3.6/site-packages/pudb/var_view.py", line 163, in render return make_canvas(text, attr, maxcol, apfx+"value") File "/usr/lib/python3.6/site-packages/pudb/ui_tools.py", line 48, in make_canvas maxcol=maxcol) File "/usr/lib/python3.6/site-packages/urwid/canvas.py", line 356, in __init__ raise CanvasError("Canvas text is wider than the maxcol specified \n%r\n%r\n%r"%(maxcol,widths,text)) urwid.canvas.CanvasError: Canvas text is wider than the maxcol specified 53 [55] [b"data: '\xe4\xb8\xad\xe6\x96\x87' "] ``` This is a Python 3.6.0 on Arch Linux, with zh_CN.UTF-8 locale. And pudb is "python-pudb 2017.1.1-1" (the pudb3 script doesn't accept `--version` nor `-V` :-( )
0.0
fef17b6f33da7d03758c150b37cd2f84754aa01d
[ "test/test_make_canvas.py::test_wide_chars" ]
[ "test/test_make_canvas.py::test_simple", "test/test_make_canvas.py::test_multiple", "test/test_make_canvas.py::test_boundary", "test/test_make_canvas.py::test_byte_boundary" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-07-05 00:13:12+00:00
mit
2,820
inducer__pycparserext-46
diff --git a/pycparserext/ext_c_parser.py b/pycparserext/ext_c_parser.py index b59d98e..7611ce1 100644 --- a/pycparserext/ext_c_parser.py +++ b/pycparserext/ext_c_parser.py @@ -169,6 +169,12 @@ class FuncDeclExt(c_ast.Node): nodelist.append(("asm", self.asm)) return tuple(nodelist) + def __iter__(self): + if self.args is not None: + yield self.args + if self.type is not None: + yield self.type + attr_names = () # }}}
inducer/pycparserext
9e66047b3d3b3c50abe212a319ba42663b796f58
diff --git a/test/test_pycparserext.py b/test/test_pycparserext.py index e93eb78..d6e9666 100644 --- a/test/test_pycparserext.py +++ b/test/test_pycparserext.py @@ -375,6 +375,24 @@ def test_double_pointer(): assert gen.visit(ast).find("func_with_p2pp(const char *, Error **)") != -1 +def test_node_visitor(): + from pycparser.c_ast import NodeVisitor + + class FuncDeclVisitor(NodeVisitor): + def visit_FuncDecl(self, node): + node.show() + + src = """ + void func1(); + int func2(int param1); + """ + import pycparserext.ext_c_parser as ext_c_parser + + parser = ext_c_parser.GnuCParser() + ast = parser.parse(src) + FuncDeclVisitor().visit(ast) + + if __name__ == "__main__": import sys if len(sys.argv) > 1:
Cannot traverse nodes using NodeVisitor, FuncDeclExt is not iterable Using `GnuCParser()` and subclassing `c_ast.NodeVisitor`, I cannot traverse the nodes as in the FuncDefs example in https://github.com/eliben/pycparser/blob/master/examples/func_defs.py It results in the following error: ``` Traceback (most recent call last): [...] File "main_script.py", line 77, in verify FuncDefVisitor().visit(self.ast) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 158, in visit return visitor(node) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 165, in generic_visit self.visit(c) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 158, in visit return visitor(node) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 165, in generic_visit self.visit(c) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 158, in visit return visitor(node) File "/path/venv/lib/python3.6/site-packages/pycparser/c_ast.py", line 164, in generic_visit for c in node: TypeError: 'FuncDeclExt' object is not iterable ```
0.0
9e66047b3d3b3c50abe212a319ba42663b796f58
[ "test/test_pycparserext.py::test_node_visitor" ]
[ "test/test_pycparserext.py::test_asm_volatile_1", "test/test_pycparserext.py::test_asm_volatile_2", "test/test_pycparserext.py::test_asm_volatile_3", "test/test_pycparserext.py::test_funky_header_code", "test/test_pycparserext.py::test_funky_header_code_2", "test/test_pycparserext.py::test_funky_header_code_3", "test/test_pycparserext.py::test_funky_header_code_4", "test/test_pycparserext.py::test_funky_header_code_5", "test/test_pycparserext.py::test_opencl[int]", "test/test_pycparserext.py::test_opencl[uint]", "test/test_pycparserext.py::test_array_attributes", "test/test_pycparserext.py::test_func_decl_attribute", "test/test_pycparserext.py::test_func_ret_ptr_decl_attribute", "test/test_pycparserext.py::test_array_ptr_decl_attribute", "test/test_pycparserext.py::test_gnu_statement_expression", "test/test_pycparserext.py::test_empty_gnu_statement_expression", "test/test_pycparserext.py::test_empty_struct_declaration", "test/test_pycparserext.py::test_nesty_c_declarator", "test/test_pycparserext.py::test_const_ptr_func_arg", "test/test_pycparserext.py::test_pointer_reproduction", "test/test_pycparserext.py::test_no_added_attr", "test/test_pycparserext.py::test_double_pointer" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-08-28 16:51:12+00:00
mit
2,821
inducer__pycparserext-52
diff --git a/pycparserext/ext_c_generator.py b/pycparserext/ext_c_generator.py index 3ecccad..297793d 100644 --- a/pycparserext/ext_c_generator.py +++ b/pycparserext/ext_c_generator.py @@ -63,7 +63,13 @@ class AsmAndAttributesMixin(object): if isinstance(modifier, c_ast.ArrayDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' - nstr += '[' + self.visit(modifier.dim) + ']' + + # BUG FIX: pycparser ignores quals + dim_quals = (' '.join(modifier.dim_quals) + ' ' + if modifier.dim_quals else '') + + nstr += '[' + dim_quals + self.visit(modifier.dim) + ']' + elif isinstance(modifier, c_ast.FuncDecl): if (i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl)): nstr = '(' + nstr + ')' diff --git a/pycparserext/ext_c_lexer.py b/pycparserext/ext_c_lexer.py index 1f8126c..5acff45 100644 --- a/pycparserext/ext_c_lexer.py +++ b/pycparserext/ext_c_lexer.py @@ -61,16 +61,30 @@ def add_lexer_keywords(cls, keywords): kw.upper() for kw in keywords) -add_lexer_keywords(GnuCLexer, [ - '__attribute__', '__asm__', '__asm', '__typeof__', - '__real__', '__imag__', '__builtin_types_compatible_p', - '__const', '__restrict', '__inline', '__inline__', - '__extension__', 'asm', '__attribute']) - -_CL_KEYWORDS = ['kernel', 'constant', 'global', 'local', 'private', - "read_only", "write_only", "read_write"] -add_lexer_keywords(OpenCLCLexer, [ - '__attribute__', '__attribute', '__asm__', '__asm', 'asm'] - + _CL_KEYWORDS + ["__"+kw for kw in _CL_KEYWORDS]) +_COMMON_KEYWORDS = [ + '__attribute__', '__attribute', + '__asm__', '__asm', 'asm'] + +_GNU_KEYWORDS = [ + '__typeof__', + '__real__', '__imag__', + '__builtin_types_compatible_p', + '__const', + '__restrict__', '__restrict', + '__inline__', '__inline', + '__extension__', + '__volatile', '__volatile__'] + +add_lexer_keywords(GnuCLexer, _COMMON_KEYWORDS + _GNU_KEYWORDS) + +# These will be added as unadorned keywords and keywords with '__' prepended +_CL_BASE_KEYWORDS = [ + 'kernel', 'constant', 'global', 'local', 'private', + 'read_only', 'write_only', 'read_write'] + +_CL_KEYWORDS = _COMMON_KEYWORDS +_CL_KEYWORDS += _CL_BASE_KEYWORDS + ["__"+kw for kw in _CL_BASE_KEYWORDS] + +add_lexer_keywords(OpenCLCLexer, _CL_KEYWORDS) # vim: fdm=marker diff --git a/pycparserext/ext_c_parser.py b/pycparserext/ext_c_parser.py index 00fad2a..abbb381 100644 --- a/pycparserext/ext_c_parser.py +++ b/pycparserext/ext_c_parser.py @@ -387,17 +387,17 @@ class _AsmMixin(object): p[0] = Asm(p[1], p[3], p[5], p[7], p[9], coord=self._coord(p.lineno(2))) def p_asm_keyword(self, p): - """ asm_keyword : __ASM__ asm_volatile - | __ASM asm_volatile - | ASM asm_volatile + """ asm_keyword : __ASM__ asm_volatile_opt + | __ASM asm_volatile_opt + | ASM asm_volatile_opt """ p[0] = p[1] if p[2]: p[0] += ' ' + p[2] - def p_asm_volatile(self, p): - """ asm_volatile : VOLATILE - | empty + def p_asm_volatile_opt(self, p): + """ asm_volatile_opt : unified_volatile + | empty """ p[0] = p[1] @@ -475,7 +475,10 @@ class GnuCParser(_AsmAndAttributesMixin, CParserBase): def p_type_qualifier_gnu(self, p): """ type_qualifier : __CONST | __RESTRICT + | __RESTRICT__ | __EXTENSION__ + | __VOLATILE + | __VOLATILE__ """ p[0] = p[1] @@ -540,6 +543,12 @@ class GnuCParser(_AsmAndAttributesMixin, CParserBase): """ p[0] = RangeExpression(p[2], p[4], coord=self._coord(p.lineno(1))) + def p_unified_volatile_gnu(self, p): + """ unified_volatile : VOLATILE + | __VOLATILE + | __VOLATILE__ + """ + p[0] = p[1] # }}} @@ -615,4 +624,9 @@ class OpenCLCParser(_AsmAndAttributesMixin, CParserBase): """ p[0] = p[1] + def p_unified_volatile_cl(self, p): + """ unified_volatile : VOLATILE + """ + p[0] = p[1] + # vim: fdm=marker
inducer/pycparserext
9365b816fdad96c28ca5d5a8bad771125c53098e
diff --git a/test/test_pycparserext.py b/test/test_pycparserext.py index 0ab21f8..d39f285 100644 --- a/test/test_pycparserext.py +++ b/test/test_pycparserext.py @@ -94,6 +94,20 @@ def test_asm_volatile_3(): print(GnuCGenerator().visit(ast)) +def test_asm_volatile_4(): + src = """ + void barrier(void) { + __asm__ __volatile__("": : :"memory"); + } """ + from pycparserext.ext_c_parser import GnuCParser + p = GnuCParser() + ast = p.parse(src) + ast.show() + + from pycparserext.ext_c_generator import GnuCGenerator + print(GnuCGenerator().visit(ast)) + + def test_funky_header_code(): src = """ extern __inline int __attribute__ ((__nothrow__)) __signbitf (float __x) @@ -438,6 +452,19 @@ def test_designated_initializers(): assert _round_trip_matches(src) [email protected]("restrict_kw", ["restrict", "__restrict__", "__restrict"]) +def test_restrict(restrict_kw): + src = """ + void f(int n, int * {0} p, int * {0} q) + {{ + }} + typedef int *array_t[10]; + {0} array_t a; + void f(int m, int n, float a[{0} m][n], float b[{0} m][n]); + """ .format(restrict_kw) + assert _round_trip_matches(src) + + def test_node_visitor(): from pycparser.c_ast import NodeVisitor
add support for __volatile__, and __restrict__ I added some support to handle Snapdragon processors, header files. Basically, trivial support for __volatile__ I could have used a #define but this seems to be a better method. I think GCC supports both __XXX and __XXX__ for all of those key words so this is really a missing feature. mhoffman-linux02$ git diff ``` diff --git a/pycparserext/ext_c_lexer.py b/pycparserext/ext_c_lexer.py index e501a61..ed7ae67 100644 --- a/pycparserext/ext_c_lexer.py +++ b/pycparserext/ext_c_lexer.py @@ -63,8 +63,8 @@ def add_lexer_keywords(cls, keywords): add_lexer_keywords(GnuCLexer, [ '__attribute__', '__asm__', '__asm', '__typeof__', '__real__', '__imag__', '__builtin_types_compatible_p', - '__const', '__restrict', '__inline', '__inline__', - '__extension__', 'asm', '__attribute']) + '__const', '__restrict', '__restrict__', '__inline', '__inline__', + '__extension__', 'asm', '__attribute', '__volatile__']) _CL_KEYWORDS = ['kernel', 'constant', 'global', 'local', 'private', "read_only", "write_only", "read_write"] diff --git a/pycparserext/ext_c_parser.py b/pycparserext/ext_c_parser.py index c9a014a..218d118 100644 --- a/pycparserext/ext_c_parser.py +++ b/pycparserext/ext_c_parser.py @@ -359,6 +359,7 @@ class _AsmMixin(object): def p_asm_volatile(self, p): """ asm_volatile : VOLATILE + | __VOLATILE__ | empty """ p[0] = p[1] @@ -434,6 +435,7 @@ class GnuCParser(_AsmAndAttributesMixin, CParserBase): def p_type_qualifier_gnu(self, p): """ type_qualifier : __CONST | __RESTRICT + | __RESTRICT__ | __EXTENSION__ """ p[0] = p[1] ```
0.0
9365b816fdad96c28ca5d5a8bad771125c53098e
[ "test/test_pycparserext.py::test_asm_volatile_4", "test/test_pycparserext.py::test_restrict[restrict]", "test/test_pycparserext.py::test_restrict[__restrict__]", "test/test_pycparserext.py::test_restrict[__restrict]" ]
[ "test/test_pycparserext.py::test_asm_volatile_1", "test/test_pycparserext.py::test_asm_volatile_2", "test/test_pycparserext.py::test_asm_volatile_3", "test/test_pycparserext.py::test_funky_header_code", "test/test_pycparserext.py::test_funky_header_code_2", "test/test_pycparserext.py::test_funky_header_code_3", "test/test_pycparserext.py::test_funky_header_code_4", "test/test_pycparserext.py::test_funky_header_code_5", "test/test_pycparserext.py::test_opencl[int]", "test/test_pycparserext.py::test_opencl[uint]", "test/test_pycparserext.py::test_array_attributes", "test/test_pycparserext.py::test_func_decl_attribute", "test/test_pycparserext.py::test_func_ret_ptr_decl_attribute", "test/test_pycparserext.py::test_array_ptr_decl_attribute", "test/test_pycparserext.py::test_gnu_statement_expression", "test/test_pycparserext.py::test_empty_gnu_statement_expression", "test/test_pycparserext.py::test_lvalue_gnu_statement_expression", "test/test_pycparserext.py::test_empty_struct_declaration", "test/test_pycparserext.py::test_nesty_c_declarator", "test/test_pycparserext.py::test_const_ptr_func_arg", "test/test_pycparserext.py::test_pointer_reproduction", "test/test_pycparserext.py::test_no_added_attr", "test/test_pycparserext.py::test_double_pointer", "test/test_pycparserext.py::test_designated_initializers", "test/test_pycparserext.py::test_node_visitor" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-08 17:33:04+00:00
mit
2,822
inducer__pycparserext-53
diff --git a/pycparserext/ext_c_generator.py b/pycparserext/ext_c_generator.py index 751905a..3ecccad 100644 --- a/pycparserext/ext_c_generator.py +++ b/pycparserext/ext_c_generator.py @@ -138,6 +138,9 @@ class GnuCGenerator(AsmAndAttributesMixin, CGeneratorBase): def visit_TypeList(self, n): return ', '.join(self.visit(ch) for ch in n.types) + def visit_RangeExpression(self, n): + return '%s ... %s' % (self.visit(n.first), self.visit(n.last)) + class GNUCGenerator(GnuCGenerator): def __init__(self): diff --git a/pycparserext/ext_c_parser.py b/pycparserext/ext_c_parser.py index 51d9b64..00fad2a 100644 --- a/pycparserext/ext_c_parser.py +++ b/pycparserext/ext_c_parser.py @@ -158,6 +158,29 @@ class TypeOfExpression(c_ast.Node): attr_names = () +class RangeExpression(c_ast.Node): + def __init__(self, first, last, coord=None): + self.first = first + self.last = last + self.coord = coord + + def children(self): + nodelist = [] + if self.first is not None: + nodelist.append(("first", self.first)) + if self.last is not None: + nodelist.append(("last", self.last)) + return tuple(nodelist) + + def __iter__(self): + if self.first is not None: + yield self.first + if self.last is not None: + yield self.last + + attr_names = () + + # These are the same as pycparser's, but it does *not* declare __slots__-- # so we can poke in attributes at our leisure. class TypeDeclExt(c_ast.TypeDecl): @@ -512,6 +535,11 @@ class GnuCParser(_AsmAndAttributesMixin, CParserBase): """ struct_declaration_list : empty """ p[0] = None + def p_range_designator(self, p): + """ designator : LBRACKET constant_expression ELLIPSIS constant_expression RBRACKET + """ + p[0] = RangeExpression(p[2], p[4], coord=self._coord(p.lineno(1))) + # }}}
inducer/pycparserext
667781d692eb69ad4906eb107e168d4384bf006d
diff --git a/test/test_pycparserext.py b/test/test_pycparserext.py index f415930..0ab21f8 100644 --- a/test/test_pycparserext.py +++ b/test/test_pycparserext.py @@ -2,6 +2,53 @@ from __future__ import print_function import pytest +# Inspired from pycparser's compare_asts test function +def _compare_asts(first, second): + if type(first) is not type(second): + return False + + if isinstance(first, tuple): + if first[0] != second[0]: + return False + + return _compare_asts(first[1], second[1]) + + for attr in first.attr_names: + if getattr(first, attr) != getattr(second, attr): + return False + + for i, c1 in enumerate(first.children()): + if not _compare_asts(c1, second.children()[i]): + return False + return True + + +def _round_trip_matches(src): + from pycparserext.ext_c_parser import GnuCParser + from pycparserext.ext_c_generator import GnuCGenerator + + p = GnuCParser() + + first_ast = p.parse(src) + + gen = GnuCGenerator().visit(first_ast) + + second_ast = p.parse(gen) + + if not _compare_asts(first_ast, second_ast): + print('First AST:') + first_ast.show() + + print('Generated code:') + print(gen) + + print('Second AST:') + second_ast.show() + + return False + return True + + def test_asm_volatile_1(): src = """ void read_tsc(void) { @@ -374,6 +421,23 @@ def test_double_pointer(): assert gen.visit(ast).find("func_with_p2pp(const char *, Error **)") != -1 +def test_designated_initializers(): + src = """ + int a[6] = { [4] = 29, [2] = 15 }; + + int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; + + int v1 = 5, v2 = 6; + int b[] = { [1] = v1, v2, [4] = v4 }; + + struct foo { int x; int y; }; + struct foo bar[10] = { [1].y = 5, [2].x = 1, [0].x = 3 }; + + char char_map[256] = { [0 ... 255] = '?', ['0' ... '9'] = 'X' }; + """ + assert _round_trip_matches(src) + + def test_node_visitor(): from pycparser.c_ast import NodeVisitor
GNU C array init with "..." not supported This is a GNU extension, see [Designated Inits](https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html#Designated-Inits) in the GCC manual. However, the GnuCParser doesn't cope: ``` >>> from pycparserext.ext_c_parser import GnuCParser >>> p=GnuCParser() >>> p.parse("int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files (x86)\Python27\lib\site-packages\pycparserext\ext_c_parser.py", line 64, in parse return self.cparser.parse(text, lexer=self.clex, debug=debuglevel) File "C:\Program Files (x86)\Python27\lib\site-packages\pycparser\ply\yacc.py", line 331, in parse return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc) File "C:\Program Files (x86)\Python27\lib\site-packages\pycparser\ply\yacc.py", line 1181, in parseopt_notrack tok = call_errorfunc(self.errorfunc, errtoken, self) File "C:\Program Files (x86)\Python27\lib\site-packages\pycparser\ply\yacc.py", line 193, in call_errorfunc r = errorfunc(token) File "C:\Program Files (x86)\Python27\lib\site-packages\pycparser\c_parser.py", line 1721, in p_error column=self.clex.find_tok_column(p))) File "C:\Program Files (x86)\Python27\lib\site-packages\pycparser\plyparser.py", line 55, in _parse_error raise ParseError("%s: %s" % (coord, msg)) pycparser.plyparser.ParseError: :1:21: before: ... ``` Tested with pycparserext 2016.2. No idea if this is _supposed_ to be supported, but I had an instance of this in my code so I ran into it.
0.0
667781d692eb69ad4906eb107e168d4384bf006d
[ "test/test_pycparserext.py::test_designated_initializers" ]
[ "test/test_pycparserext.py::test_asm_volatile_1", "test/test_pycparserext.py::test_asm_volatile_2", "test/test_pycparserext.py::test_asm_volatile_3", "test/test_pycparserext.py::test_funky_header_code", "test/test_pycparserext.py::test_funky_header_code_2", "test/test_pycparserext.py::test_funky_header_code_3", "test/test_pycparserext.py::test_funky_header_code_4", "test/test_pycparserext.py::test_funky_header_code_5", "test/test_pycparserext.py::test_opencl[int]", "test/test_pycparserext.py::test_opencl[uint]", "test/test_pycparserext.py::test_array_attributes", "test/test_pycparserext.py::test_func_decl_attribute", "test/test_pycparserext.py::test_func_ret_ptr_decl_attribute", "test/test_pycparserext.py::test_array_ptr_decl_attribute", "test/test_pycparserext.py::test_gnu_statement_expression", "test/test_pycparserext.py::test_empty_gnu_statement_expression", "test/test_pycparserext.py::test_lvalue_gnu_statement_expression", "test/test_pycparserext.py::test_empty_struct_declaration", "test/test_pycparserext.py::test_nesty_c_declarator", "test/test_pycparserext.py::test_const_ptr_func_arg", "test/test_pycparserext.py::test_pointer_reproduction", "test/test_pycparserext.py::test_no_added_attr", "test/test_pycparserext.py::test_double_pointer", "test/test_pycparserext.py::test_node_visitor" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-08-08 18:22:03+00:00
mit
2,823
inducer__pycparserext-62
diff --git a/pycparserext/ext_c_parser.py b/pycparserext/ext_c_parser.py index 62efb56..f91394e 100644 --- a/pycparserext/ext_c_parser.py +++ b/pycparserext/ext_c_parser.py @@ -558,6 +558,15 @@ class GnuCParser(_AsmAndAttributesMixin, CParserBase): """ p[0] = RangeExpression(p[2], p[4], coord=self._coord(p.lineno(1))) + def p_labeled_statement_4(self, p): + """ labeled_statement : CASE constant_expression ELLIPSIS constant_expression \ + COLON pragmacomp_or_statement + """ + p[0] = c_ast.Case( + RangeExpression(p[2], p[4], coord=self._coord(p.lineno(1))), + [p[6]], + self._coord(p.lineno(1))) + def p_unified_volatile_gnu(self, p): """ unified_volatile : VOLATILE | __VOLATILE
inducer/pycparserext
502dbb977e9cc9336f447aaaab86c1ee1addb03a
diff --git a/test/test_pycparserext.py b/test/test_pycparserext.py index 2162073..5d77556 100644 --- a/test/test_pycparserext.py +++ b/test/test_pycparserext.py @@ -469,6 +469,22 @@ def test_designated_initializers(): assert _round_trip_matches(src) +def test_case_ranges(): + src = """ + void f() { + switch (1) { + case 3: + break; + case 0 ... 5: + break; + case 'A' ... 'Z': + break; + } + } + """ + assert _round_trip_matches(src) + + @pytest.mark.parametrize("restrict_kw", ["restrict", "__restrict__", "__restrict"]) def test_restrict(restrict_kw): src = """
Support for case ranges Hi, Thanks for this project! I see that you've implemented designated range initializers. Would you consider implementing the somewhat related case ranges (https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html)?
0.0
502dbb977e9cc9336f447aaaab86c1ee1addb03a
[ "test/test_pycparserext.py::test_case_ranges" ]
[ "test/test_pycparserext.py::test_asm_volatile_1", "test/test_pycparserext.py::test_asm_volatile_2", "test/test_pycparserext.py::test_asm_volatile_3", "test/test_pycparserext.py::test_asm_volatile_4", "test/test_pycparserext.py::test_asm_label", "test/test_pycparserext.py::test_funky_header_code", "test/test_pycparserext.py::test_funky_header_code_2", "test/test_pycparserext.py::test_funky_header_code_3", "test/test_pycparserext.py::test_funky_header_code_4", "test/test_pycparserext.py::test_funky_header_code_5", "test/test_pycparserext.py::test_opencl[int]", "test/test_pycparserext.py::test_opencl[uint]", "test/test_pycparserext.py::test_array_attributes", "test/test_pycparserext.py::test_func_decl_attribute", "test/test_pycparserext.py::test_func_ret_ptr_decl_attribute", "test/test_pycparserext.py::test_array_ptr_decl_attribute", "test/test_pycparserext.py::test_gnu_statement_expression", "test/test_pycparserext.py::test_empty_gnu_statement_expression", "test/test_pycparserext.py::test_lvalue_gnu_statement_expression", "test/test_pycparserext.py::test_empty_struct_declaration", "test/test_pycparserext.py::test_nesty_c_declarator", "test/test_pycparserext.py::test_const_ptr_func_arg", "test/test_pycparserext.py::test_pointer_reproduction", "test/test_pycparserext.py::test_no_added_attr", "test/test_pycparserext.py::test_double_pointer", "test/test_pycparserext.py::test_designated_initializers", "test/test_pycparserext.py::test_restrict[restrict]", "test/test_pycparserext.py::test_restrict[__restrict__]", "test/test_pycparserext.py::test_restrict[__restrict]", "test/test_pycparserext.py::test_node_visitor", "test/test_pycparserext.py::test_typeof_reproduction", "test/test_pycparserext.py::test_typedef" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-22 00:23:14+00:00
mit
2,824
inducer__pymbolic-58
diff --git a/pymbolic/parser.py b/pymbolic/parser.py index b846193..cb4cb62 100644 --- a/pymbolic/parser.py +++ b/pymbolic/parser.py @@ -37,6 +37,8 @@ _openpar = intern("openpar") _closepar = intern("closepar") _openbracket = intern("openbracket") _closebracket = intern("closebracket") +_true = intern("True") +_false = intern("False") _identifier = intern("identifier") _whitespace = intern("whitespace") _comma = intern("comma") @@ -164,6 +166,8 @@ class Parser: (_closepar, pytools.lex.RE(r"\)")), (_openbracket, pytools.lex.RE(r"\[")), (_closebracket, pytools.lex.RE(r"\]")), + (_true, pytools.lex.RE(r"True")), + (_false, pytools.lex.RE(r"False")), (_identifier, pytools.lex.RE(r"[@$a-z_A-Z_][@$a-zA-Z_0-9]*")), (_whitespace, pytools.lex.RE("[ \n\t]*")), (_comma, pytools.lex.RE(",")), @@ -193,6 +197,12 @@ class Parser: return self.parse_float(pstate.next_str_and_advance()) elif next_tag is _imaginary: return complex(pstate.next_str_and_advance()) + elif next_tag is _true: + assert pstate.next_str_and_advance() == "True" + return True + elif next_tag is _false: + assert pstate.next_str_and_advance() == "False" + return False elif next_tag is _identifier: return primitives.Variable(pstate.next_str_and_advance()) elif next_tag is _if: @@ -330,7 +340,7 @@ class Parser: then_expr = left_exp pstate.advance() pstate.expect_not_end() - condition = self.parse_expression(pstate, _PREC_LOGICAL_OR) + condition = self.parse_expression(pstate, _PREC_IF) pstate.expect(_else) pstate.advance() else_expr = self.parse_expression(pstate)
inducer/pymbolic
725a184b2a38a1095d83635b9c2efe9b15371584
diff --git a/test/test_pymbolic.py b/test/test_pymbolic.py index 7908d6b..6f58587 100644 --- a/test/test_pymbolic.py +++ b/test/test_pymbolic.py @@ -290,6 +290,8 @@ def test_parser(): with pytest.deprecated_call(): parse("1+if(0, 1, 2)") + assert eval(str(parse("1729 if True or False else 42"))) == 1729 + # }}}
[Parser] Incorrect if-else precedence ```python In [11]: parse("10 if x or y else 20") ``` raises: ``` ParseError: else expected, or found instead at index 8: ...or y else 20... ```
0.0
725a184b2a38a1095d83635b9c2efe9b15371584
[ "test/test_pymbolic.py::test_parser" ]
[ "test/test_pymbolic.py::test_integer_power", "test/test_pymbolic.py::test_expand", "test/test_pymbolic.py::test_substitute", "test/test_pymbolic.py::test_no_comparison", "test/test_pymbolic.py::test_structure_preservation", "test/test_pymbolic.py::test_mappers", "test/test_pymbolic.py::test_func_dep_consistency", "test/test_pymbolic.py::test_conditions", "test/test_pymbolic.py::test_graphviz", "test/test_pymbolic.py::test_ast_interop", "test/test_pymbolic.py::test_compile", "test/test_pymbolic.py::test_unifier", "test/test_pymbolic.py::test_stringifier_preserve_shift_order", "test/test_pymbolic.py::test_flop_counter", "test/test_pymbolic.py::test_multiplicative_stringify_preserves_association", "test/test_pymbolic.py::test_differentiator_flags_for_nonsmooth_and_discontinuous" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-07-11 22:22:52+00:00
mit
2,825
inducer__pytools-222
diff --git a/pytools/persistent_dict.py b/pytools/persistent_dict.py index fb77d4b..4090cb4 100644 --- a/pytools/persistent_dict.py +++ b/pytools/persistent_dict.py @@ -460,7 +460,7 @@ class KeyBuilder: import datetime # Convert to datetime object - self.rec(key_hash, datetime.datetime.combine(datetime.date.today(), key)) + self.rec(key_hash, datetime.datetime.combine(datetime.date.min, key)) self.rec(key_hash, "<time>") def update_for_datetime(self, key_hash: Hash, key: Any) -> None:
inducer/pytools
a5efddf54fd4467d729ec4118faa1a059b309d0b
diff --git a/pytools/test/test_persistent_dict.py b/pytools/test/test_persistent_dict.py index 649bd00..d53fcfd 100644 --- a/pytools/test/test_persistent_dict.py +++ b/pytools/test/test_persistent_dict.py @@ -621,7 +621,7 @@ def test_datetime_hashing() -> None: == keyb(datetime.time(12, 0)) == keyb(datetime.time(12, 0, 0)) == keyb(datetime.time(12, 0, 0, 0)) - == "bf73f48b2f2666b5c42f6993e628fdc15e0b6c3127186c3ab44ce08ed83d0472") + == "288ec82f6a00ac15968d4d257d4aca1089b863c61ef2ee200e64351238397705") assert keyb(datetime.time(12, 0)) != keyb(datetime.time(12, 1)) # Aware time @@ -634,7 +634,7 @@ def test_datetime_hashing() -> None: assert t1 == t2 assert (keyb(t1) == keyb(t2) - == "c0947587c92ab6e2df90475dd497aff1d83df55fbd5af6c55b2a0a221b2437a4") + == "3587427ca9d581779d532b397df206ddeadfcf4e38b1ee69c19174e8e1268cc4") assert t1 != t3 assert keyb(t1) != keyb(t3)
`datetime` hashing tests fail https://github.com/inducer/pytools/actions/runs/8864710333/job/24340173299 @matthiasdiener could you take a look?
0.0
a5efddf54fd4467d729ec4118faa1a059b309d0b
[ "pytools/test/test_persistent_dict.py::test_datetime_hashing" ]
[ "pytools/test/test_persistent_dict.py::test_persistent_dict_storage_and_lookup", "pytools/test/test_persistent_dict.py::test_persistent_dict_deletion", "pytools/test/test_persistent_dict.py::test_persistent_dict_synchronization", "pytools/test/test_persistent_dict.py::test_persistent_dict_cache_collisions", "pytools/test/test_persistent_dict.py::test_persistent_dict_clear", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_storage_and_lookup[0]", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_storage_and_lookup[256]", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_lru_policy", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_synchronization", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_cache_collisions", "pytools/test/test_persistent_dict.py::test_write_once_persistent_dict_clear", "pytools/test/test_persistent_dict.py::test_scalar_hashing", "pytools/test/test_persistent_dict.py::test_frozenset_hashing", "pytools/test/test_persistent_dict.py::test_ABC_hashing", "pytools/test/test_persistent_dict.py::test_class_hashing", "pytools/test/test_persistent_dict.py::test_dataclass_hashing", "pytools/test/test_persistent_dict.py::test_xdg_cache_home" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2024-04-29 15:49:01+00:00
mit
2,826
influxdata__influxdb-client-python-203
diff --git a/CHANGELOG.md b/CHANGELOG.md index 36afb4f..249f243 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ ## 1.16.0 [unreleased] +### Features +1. [#203](https://github.com/influxdata/influxdb-client-python/pull/203): Allow configuring client via TOML file. + ### Documentation 1. [#202](https://github.com/influxdata/influxdb-client-python/pull/202): Added an example how to use RxPY and sync batching diff --git a/README.rst b/README.rst index cc9d396..12b9a52 100644 --- a/README.rst +++ b/README.rst @@ -379,7 +379,7 @@ _______ Via Configuration file ______________________ -In a ini configuration file you are able to specify default tags by ``tags`` segment. +In a `init <https://docs.python.org/3/library/configparser.html>`_ configuration file you are able to specify default tags by ``tags`` segment. .. code-block:: python @@ -398,6 +398,8 @@ In a ini configuration file you are able to specify default tags by ``tags`` seg customer = California Miner data_center = ${env.data_center} +You could also use a `TOML <https://toml.io/en/>`_ format for the configuration file. + Via Environment Properties __________________________ You are able to specify default tags by environment properties with prefix ``INFLUXDB_V2_TAG_``. diff --git a/influxdb_client/client/influxdb_client.py b/influxdb_client/client/influxdb_client.py index 35765b2..e078f50 100644 --- a/influxdb_client/client/influxdb_client.py +++ b/influxdb_client/client/influxdb_client.py @@ -69,44 +69,79 @@ class InfluxDBClient(object): @classmethod def from_config_file(cls, config_file: str = "config.ini", debug=None, enable_gzip=False): """ - Configure client via '*.ini' file in segment 'influx2'. + Configure client via configuration file. The configuration has to be under 'influx' section. - Supported options: + The supported formats: + - https://docs.python.org/3/library/configparser.html + - https://toml.io/en/ + + Configuration options: - url - org - token - timeout, - verify_ssl - ssl_ca_cert + + config.ini example:: + + [influx2] + url=http://localhost:8086 + org=my-org + token=my-token + timeout=6000 + + [tags] + id = 132-987-655 + customer = California Miner + data_center = ${env.data_center} + + config.toml example:: + + [influx2] + url = "http://localhost:8086" + token = "my-token" + org = "my-org" + timeout = 6000 + + [tags] + id = "132-987-655" + customer = "California Miner" + data_center = "${env.data_center}" + """ config = configparser.ConfigParser() config.read(config_file) - url = config['influx2']['url'] - token = config['influx2']['token'] + def config_value(key: str): + return config['influx2'][key].strip('"') + + url = config_value('url') + token = config_value('token') timeout = None if config.has_option('influx2', 'timeout'): - timeout = config['influx2']['timeout'] + timeout = config_value('timeout') org = None if config.has_option('influx2', 'org'): - org = config['influx2']['org'] + org = config_value('org') verify_ssl = True if config.has_option('influx2', 'verify_ssl'): - verify_ssl = config['influx2']['verify_ssl'] + verify_ssl = config_value('verify_ssl') ssl_ca_cert = None if config.has_option('influx2', 'ssl_ca_cert'): - ssl_ca_cert = config['influx2']['ssl_ca_cert'] + ssl_ca_cert = config_value('ssl_ca_cert') default_tags = None if config.has_section('tags'): - default_tags = dict(config.items('tags')) + tags = {k: v.strip('"') for k, v in config.items('tags')} + default_tags = dict(tags) if timeout: return cls(url, token, debug=debug, timeout=int(timeout), org=org, default_tags=default_tags,
influxdata/influxdb-client-python
4f1e14e4a01200b1a927e2ca470b3662fcb376fd
diff --git a/tests/config.toml b/tests/config.toml new file mode 100644 index 0000000..8f9522e --- /dev/null +++ b/tests/config.toml @@ -0,0 +1,11 @@ +[influx2] + url = "http://localhost:8086" + token = "my-token" + org = "my-org" + active = true + timeout = 6000 + +[tags] + id = "132-987-655" + customer = "California Miner" + data_center = "${env.data_center}" diff --git a/tests/test_InfluxDBClient.py b/tests/test_InfluxDBClient.py index 241fa9a..894a7f6 100644 --- a/tests/test_InfluxDBClient.py +++ b/tests/test_InfluxDBClient.py @@ -47,6 +47,26 @@ class InfluxDBClientTest(unittest.TestCase): self.assertEqual(health.status, "pass") self.assertEqual(health.name, "influxdb") + def test_init_from_ini_file(self): + self.client = InfluxDBClient.from_config_file(f'{os.path.dirname(__file__)}/config.ini') + + self.assertConfig() + + def test_init_from_toml_file(self): + self.client = InfluxDBClient.from_config_file(f'{os.path.dirname(__file__)}/config.toml') + + self.assertConfig() + + def assertConfig(self): + self.assertEqual("http://localhost:8086", self.client.url) + self.assertEqual("my-org", self.client.org) + self.assertEqual("my-token", self.client.token) + self.assertEqual(6000, self.client.timeout) + self.assertEqual(3, len(self.client.default_tags)) + self.assertEqual("132-987-655", self.client.default_tags["id"]) + self.assertEqual("California Miner", self.client.default_tags["customer"]) + self.assertEqual("${env.data_center}", self.client.default_tags["data_center"]) + def test_init_from_file_ssl_default(self): self.client = InfluxDBClient.from_config_file(f'{os.path.dirname(__file__)}/config.ini')
`InfluxDBClient.from_config_file()` incompatible with config files generated by `influx setup` The method `InfluxDBClient.from_config_file()` does not seem to be compatible with the config file format generated by `influx setup` due to quotation marks around strings. Would it be better to make the client deal with the quotation marks correctly, perhaps by `.strip()`-ing the quote characters, or would it be better to change the config file format generated by `influx setup`? __Steps to reproduce:__ 1. Run the following in shell on new install of influxdb2 (added line breaks for clarity): ``` influx setup --bucket=telem --name=influx2 # name expected by InfluxDBClient.from_config_file() --org=moms-sewing-room --password=fhqwhgads --username=edgar_jr --force ``` This creates the file ~/.influxdbv2/configs where the first un-commented section is as below, note the quotation marks around all the strings: ``` [influx2] url = "http://localhost:8086" token = "7CkNpNw7A6rmeyc_vp0zYPGoOhcZ9zji9C0_RDG1rvb75hQ-JdMyOU81l4SfXJcumH3De1l7O85kODONyzYCKA==" org = "moms-sewing-room" active = true ``` 2. Run the following in a Python interpreter: ``` import time from datetime import datetime from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import WriteOptions client = InfluxDBClient.from_config_file('~/.influxdbv2/configs') write_api = client.write_api( write_options=WriteOptions( batch_size=500, # number of data points per batch flush_interval=1000, # milliseconds before batch is written jitter_interval=0, retry_interval=1000, # milliseconds before retry after failed write max_retries=5, max_retry_delay=10_000, # give up after this many milliseconds exponential_base=2 ) ) point = Point.from_dict( dictionary={ 'measurement': 'my_measurement', 'fields': {'field1': 1.0}, 'time': datetime.utcnow(), }, write_precision=WritePrecision.NS, ) write_api.write(bucket='telem', record=point) # wait long enough for write attempts to fail time.sleep(15) ``` __Expected behavior:__ Points are written to the bucket successfully. __Actual behavior:__ Multiple unsuccessful attempts to write points, emitting the following to the console: ``` The retriable error occurred during request. Reason: '<urllib3.connection.HTTPConnection object at 0x7fbf5b9150d0>: Failed to establish a new connection: [Errno -2] Name or service not known'. The retriable error occurred during request. Reason: '<urllib3.connection.HTTPConnection object at 0x7fbf5b8fdbe0>: Failed to establish a new connection: [Errno -2] Name or service not known'. The retriable error occurred during request. Reason: '<urllib3.connection.HTTPConnection object at 0x7fbf5b913640>: Failed to establish a new connection: [Errno -2] Name or service not known'. The retriable error occurred during request. Reason: '<urllib3.connection.HTTPConnection object at 0x7fbf5b915970>: Failed to establish a new connection: [Errno -2] Name or service not known'. The retriable error occurred during request. Reason: '<urllib3.connection.HTTPConnection object at 0x7fbf5b915640>: Failed to establish a new connection: [Errno -2] Name or service not known'. The batch item wasn't processed successfully because: HTTPConnectionPool(host='"http', port=80): Max retries exceeded with url: //localhost:8086%22/api/v2/write?org=%22moms-sewing-room%22&bucket=telem&precision=ns (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbf5b913af0>: Failed to establish a new connection: [Errno -2] Name or service not known')) ``` The useful clue is this part: ``` Max retries exceeded with url: //localhost:8086%22/api/v2/write?org=%22moms-sewing-room%22&bucket=telem&precision=ns ``` __Additional details:__ Based on the error message, clearly the URL is missing the "http:" up front, and there are a bunch of "%22" instances scattered around, which is the URL encoding for `"`. Inspecting the `InfluxDBClient` object that was created: ``` In [5]: client.url Out[5]: '"http://localhost:8086"' ``` The strings from the config file were captured with the quotation marks included (this applies to token and org as well). If I edit the config file to remove the quotation marks I'm able to write to the database with no problems. User Franky1 [replied](https://community.influxdata.com/t/strings-in-config-file-created-by-influx-setup-incompatible-with-python-influxdbclient-from-config-file/18659/2?u=nerdenceman) to my post on the user forum with some insight: > The Python client uses the python standard library `configparser` to read the ini file. The configparser lib does not actually expect quotes in the ini file for strings as a value. If it does, the quotes are included in the read string. This seems to be the case here. __Specifications:__ - Client Version: 1.14.0 - InfluxDB Version: 2.0.4 - Platform: Linux Mint 20.1 (based on Ubuntu Focal)
0.0
4f1e14e4a01200b1a927e2ca470b3662fcb376fd
[ "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_toml_file" ]
[ "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_ConnectToSelfSignedServer", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_TrailingSlashInUrl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_ini_file" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-11 07:16:05+00:00
mit
2,827
influxdata__influxdb-client-python-238
diff --git a/CHANGELOG.md b/CHANGELOG.md index dbc23df..891af11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ### Features 1. [#237](https://github.com/influxdata/influxdb-client-python/pull/237): Use kwargs to pass query parameters into API list call - useful for the ability to use pagination. 1. [#241](https://github.com/influxdata/influxdb-client-python/pull/241): Add detail error message for not supported type of `Point.field` +1. [#238](https://github.com/influxdata/influxdb-client-python/pull/238): Add possibility to specify default `timezone` for datetimes without `tzinfo` ## 1.17.0 [2021-04-30] diff --git a/influxdb_client/client/util/date_utils.py b/influxdb_client/client/util/date_utils.py index f7557b1..f1f6f39 100644 --- a/influxdb_client/client/util/date_utils.py +++ b/influxdb_client/client/util/date_utils.py @@ -10,6 +10,15 @@ date_helper = None class DateHelper: """DateHelper to groups different implementations of date operations.""" + def __init__(self, timezone: datetime.tzinfo = UTC) -> None: + """ + Initialize defaults. + + :param timezone: Default timezone used for serialization "datetime" without "tzinfo". + Default value is "UTC". + """ + self.timezone = timezone + def parse_date(self, date_string: str): """ Parse string into Date or Timestamp. @@ -40,7 +49,7 @@ class DateHelper: :return: datetime in UTC """ if not value.tzinfo: - return UTC.localize(value) + return self.to_utc(value.replace(tzinfo=self.timezone)) else: return value.astimezone(UTC)
influxdata/influxdb-client-python
be6760d50fac203137e7e2edd91b63c2ed8e68ca
diff --git a/tests/test_DateHelper.py b/tests/test_DateHelper.py new file mode 100644 index 0000000..abff4e5 --- /dev/null +++ b/tests/test_DateHelper.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +import unittest +from datetime import datetime, timezone + +from pytz import UTC, timezone + +from influxdb_client.client.util.date_utils import DateHelper + + +class DateHelperTest(unittest.TestCase): + + def test_to_utc(self): + date = DateHelper().to_utc(datetime(2021, 4, 29, 20, 30, 10, 0)) + self.assertEqual(datetime(2021, 4, 29, 20, 30, 10, 0, UTC), date) + + def test_to_utc_different_timezone(self): + date = DateHelper(timezone=timezone('ETC/GMT+2')).to_utc(datetime(2021, 4, 29, 20, 30, 10, 0)) + self.assertEqual(datetime(2021, 4, 29, 22, 30, 10, 0, UTC), date) + + +if __name__ == '__main__': + unittest.main()
_convert_timestamp assumes passed datetime to be UTC This function here https://github.com/influxdata/influxdb-client-python/blob/62f93503044dbbd86443555ccfac5cfd8359f91a/influxdb_client/client/write/point.py#L130 assumes a passed datetime object to be in UTC format if no timezone is specified. I find this to be highly misleading. From the moment on I set the local timezone when I install an OS I want my system to accept local timezone data from me if I don't specify otherwise.
0.0
be6760d50fac203137e7e2edd91b63c2ed8e68ca
[ "tests/test_DateHelper.py::DateHelperTest::test_to_utc_different_timezone" ]
[ "tests/test_DateHelper.py::DateHelperTest::test_to_utc" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-04-29 09:15:07+00:00
mit
2,828
influxdata__influxdb-client-python-303
diff --git a/CHANGELOG.md b/CHANGELOG.md index 255be7d..5ab8620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,11 +3,16 @@ ### Features 1. [#281](https://github.com/influxdata/influxdb-client-python/pull/281): `FluxTable`, `FluxColumn` and `FluxRecord` objects have helpful reprs 1. [#293](https://github.com/influxdata/influxdb-client-python/pull/293): `dataframe_serializer` supports batching +1. [#301](https://github.com/influxdata/influxdb-client-python/pull/301): Add `proxy_headers` to configuration options + +### Documentation +1. [#301](https://github.com/influxdata/influxdb-client-python/pull/301): How to configure proxy ### Bug Fixes 1. [#283](https://github.com/influxdata/influxdb-client-python/pull/283): Set proxy server in config file 1. [#290](https://github.com/influxdata/influxdb-client-python/pull/290): `Threshold` domain models mapping 1. [#290](https://github.com/influxdata/influxdb-client-python/pull/290): `DashboardService` responses types +1. [#303](https://github.com/influxdata/influxdb-client-python/pull/303): Backslash escaping in serialization to Line protocol ## 1.19.0 [2021-07-09] diff --git a/README.rst b/README.rst index 268770c..0198265 100644 --- a/README.rst +++ b/README.rst @@ -76,6 +76,7 @@ InfluxDB 2.0 client features - `How to use Jupyter + Pandas + InfluxDB 2`_ - Advanced Usage - `Gzip support`_ + - `Proxy configuration`_ - `Delete data`_ Installation @@ -1059,6 +1060,41 @@ Gzip support .. marker-gzip-end +Proxy configuration +^^^^^^^^^^^^^^^^^^^ +.. marker-proxy-start + +You can configure the client to tunnel requests through an HTTP proxy. +The following proxy options are supported: + +- ``proxy`` - Set this to configure the http proxy to be used, ex. ``http://localhost:3128`` +- ``proxy_headers`` - A dictionary containing headers that will be sent to the proxy. Could be used for proxy authentication. + +.. code-block:: python + + from influxdb_client import InfluxDBClient + + with InfluxDBClient(url="http://localhost:8086", + token="my-token", + org="my-org", + proxy="http://localhost:3128") as client: + +.. note:: + + If your proxy notify the client with permanent redirect (``HTTP 301``) to **different host**. + The client removes ``Authorization`` header, because otherwise the contents of ``Authorization`` is sent to third parties + which is a security vulnerability. + + You can change this behaviour by: + + .. code-block:: python + + from urllib3 import Retry + Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset() + Retry.DEFAULT.remove_headers_on_redirect = Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT + +.. marker-proxy-end + Delete data ^^^^^^^^^^^ .. marker-delete-start diff --git a/docs/usage.rst b/docs/usage.rst index 26f8315..f563181 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -10,18 +10,18 @@ Query :start-after: marker-query-start :end-before: marker-query-end -Pandas DataFrame -^^^^^^^^^^^^^^^^ -.. include:: ../README.rst - :start-after: marker-pandas-start - :end-before: marker-pandas-end - Write ^^^^^ .. include:: ../README.rst :start-after: marker-writes-start :end-before: marker-writes-end +Pandas DataFrame +^^^^^^^^^^^^^^^^ +.. include:: ../README.rst + :start-after: marker-pandas-start + :end-before: marker-pandas-end + Delete data ^^^^^^^^^^^ .. include:: ../README.rst @@ -34,6 +34,12 @@ Gzip support :start-after: marker-gzip-start :end-before: marker-gzip-end +Proxy configuration +^^^^^^^^^^^^^^^^^^^ +.. include:: ../README.rst + :start-after: marker-proxy-start + :end-before: marker-proxy-end + Debugging ^^^^^^^^^ diff --git a/influxdb_client/client/influxdb_client.py b/influxdb_client/client/influxdb_client.py index 9ee7179..e0c471e 100644 --- a/influxdb_client/client/influxdb_client.py +++ b/influxdb_client/client/influxdb_client.py @@ -38,6 +38,8 @@ class InfluxDBClient(object): :key bool verify_ssl: Set this to false to skip verifying SSL certificate when calling API from https server. :key str ssl_ca_cert: Set this to customize the certificate file to verify the peer. :key str proxy: Set this to configure the http proxy to be used (ex. http://localhost:3128) + :key str proxy_headers: A dictionary containing headers that will be sent to the proxy. Could be used for proxy + authentication. :key int connection_pool_maxsize: Number of connections to save that can be reused by urllib3. Defaults to "multiprocessing.cpu_count() * 5". :key urllib3.util.retry.Retry retries: Set the default retry strategy that is used for all HTTP requests @@ -63,6 +65,7 @@ class InfluxDBClient(object): conf.verify_ssl = kwargs.get('verify_ssl', True) conf.ssl_ca_cert = kwargs.get('ssl_ca_cert', None) conf.proxy = kwargs.get('proxy', None) + conf.proxy_headers = kwargs.get('proxy_headers', None) conf.connection_pool_maxsize = kwargs.get('connection_pool_maxsize', conf.connection_pool_maxsize) conf.timeout = timeout diff --git a/influxdb_client/client/write/point.py b/influxdb_client/client/write/point.py index 98af23e..04d3c9c 100644 --- a/influxdb_client/client/write/point.py +++ b/influxdb_client/client/write/point.py @@ -18,7 +18,6 @@ EPOCH = UTC.localize(datetime.utcfromtimestamp(0)) DEFAULT_WRITE_PRECISION = WritePrecision.NS _ESCAPE_MEASUREMENT = str.maketrans({ - '\\': r'\\', # Note: this is wrong. Backslashes are not escaped like this in measurements. ',': r'\,', ' ': r'\ ', '\n': r'\n', @@ -27,7 +26,6 @@ _ESCAPE_MEASUREMENT = str.maketrans({ }) _ESCAPE_KEY = str.maketrans({ - '\\': r'\\', # Note: this is wrong. Backslashes are not escaped like this in keys. ',': r'\,', '=': r'\=', ' ': r'\ ', diff --git a/influxdb_client/configuration.py b/influxdb_client/configuration.py index 53b55d6..0132cf1 100644 --- a/influxdb_client/configuration.py +++ b/influxdb_client/configuration.py @@ -112,6 +112,8 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)): # Proxy URL self.proxy = None + # A dictionary containing headers that will be sent to the proxy + self.proxy_headers = None # Safe chars for path_param self.safe_chars_for_path_param = '' diff --git a/influxdb_client/rest.py b/influxdb_client/rest.py index c77f5f7..49a3592 100644 --- a/influxdb_client/rest.py +++ b/influxdb_client/rest.py @@ -107,6 +107,7 @@ class RESTClientObject(object): cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, **addition_pool_args ) else:
influxdata/influxdb-client-python
cf2186200156c1f5cc2008703bb54775241d2aba
diff --git a/tests/test_InfluxDBClient.py b/tests/test_InfluxDBClient.py index db5a1ae..cbacdfa 100644 --- a/tests/test_InfluxDBClient.py +++ b/tests/test_InfluxDBClient.py @@ -5,7 +5,9 @@ import threading import unittest from influxdb_client import InfluxDBClient, Point -from influxdb_client.client.write_api import SYNCHRONOUS, ASYNCHRONOUS, WriteOptions, WriteType +from influxdb_client.client.write_api import WriteOptions, WriteType + +from tests.base_test import BaseTest class InfluxDBClientTest(unittest.TestCase): @@ -167,6 +169,49 @@ class InfluxDBClientTest(unittest.TestCase): self.assertIsNone(api_client._pool) self.assertIsNone(self.client.api_client) + +class InfluxDBClientTestIT(BaseTest): + httpRequest = [] + + def tearDown(self) -> None: + super(InfluxDBClientTestIT, self).tearDown() + if hasattr(self, 'httpd'): + self.httpd.shutdown() + if hasattr(self, 'httpd_thread'): + self.httpd_thread.join() + InfluxDBClientTestIT.httpRequest = [] + + def test_proxy(self): + self._start_proxy_server() + + self.client.close() + self.client = InfluxDBClient(url=self.host, + token=self.auth_token, + proxy=f"http://localhost:{self.httpd.server_address[1]}", + proxy_headers={'ProxyHeader': 'Val'}) + ready = self.client.ready() + self.assertEqual(ready.status, "ready") + self.assertEqual(1, len(InfluxDBClientTestIT.httpRequest)) + self.assertEqual('Val', InfluxDBClientTestIT.httpRequest[0].headers.get('ProxyHeader')) + + def _start_proxy_server(self): + import http.server + import urllib.request + + class ProxyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): + + def do_GET(self): + InfluxDBClientTestIT.httpRequest.append(self) + self.send_response(200) + self.send_header('Content-type', 'application/json') + self.end_headers() + self.copyfile(urllib.request.urlopen(self.path), self.wfile) + + self.httpd = http.server.HTTPServer(('localhost', 0), ProxyHTTPRequestHandler) + self.httpd_thread = threading.Thread(target=self.httpd.serve_forever) + self.httpd_thread.start() + + class ServerWithSelfSingedSSL(http.server.SimpleHTTPRequestHandler): def _set_headers(self): self.send_response(200) diff --git a/tests/test_WriteApi.py b/tests/test_WriteApi.py index 8480068..301d643 100644 --- a/tests/test_WriteApi.py +++ b/tests/test_WriteApi.py @@ -515,6 +515,30 @@ class WriteApiTestMock(BaseTest): self.assertEqual(1, len(requests)) self.assertEqual("h2o,customer=California\\ Miner,id=132-987-655 level=1 1", requests[0].parsed_body) + def test_redirect(self): + from urllib3 import Retry + Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset() + Retry.DEFAULT.remove_headers_on_redirect = Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT + self.influxdb_client.close() + + self.influxdb_client = InfluxDBClient(url="http://localhost", token="my-token", org="my-org") + + httpretty.register_uri(httpretty.POST, uri="http://localhost2/api/v2/write", status=204) + httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=301, + adding_headers={'Location': 'http://localhost2/api/v2/write'}) + + self.write_client = self.influxdb_client.write_api(write_options=SYNCHRONOUS) + + self.write_client.write("my-bucket", "my-org", {"measurement": "h2o", "fields": {"level": 1.0}, "time": 1}) + + requests = httpretty.httpretty.latest_requests + self.assertEqual(2, len(requests)) + self.assertEqual('Token my-token', requests[0].headers['Authorization']) + self.assertEqual('Token my-token', requests[1].headers['Authorization']) + + from urllib3 import Retry + Retry.DEFAULT.remove_headers_on_redirect = Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT + class AsynchronousWriteTest(BaseTest): diff --git a/tests/test_point.py b/tests/test_point.py index f37e362..40446a9 100644 --- a/tests/test_point.py +++ b/tests/test_point.py @@ -267,7 +267,7 @@ class PointTest(unittest.TestCase): point._tags = { "empty_tag": "", "none_tag": None, - "backslash_tag": "C:\\", + "backslash_tag": "C:\\\\", "integer_tag": 2, "string_tag": "hello" } @@ -379,6 +379,15 @@ class PointTest(unittest.TestCase): self.assertEqual('Type: "<class \'pytz.UTC\'>" of field: "level" is not supported.', f'{exception}') + def test_backslash(self): + point = Point.from_dict({"measurement": "test", + "tags": {"tag1": "value1", "tag2": "value\2", "tag3": "value\\3", + "tag4": r"value\4", "tag5": r"value\\5"}, "time": 1624989000000000000, + "fields": {"value": 10}}, write_precision=WritePrecision.NS) + self.assertEqual( + "test,tag1=value1,tag2=value\2,tag3=value\\3,tag4=value\\4,tag5=value\\\\5 value=10i 1624989000000000000", + point.to_line_protocol()) + if __name__ == '__main__': unittest.main()
re-escaping the \ character when converting to line protocol - **InfluxDB version: 1.8.5** - **InfluxDB-python version: 1.18.0** - **Python version: 3.6.9** - **Operating system version: Ubuntu 18.04** influx is re-escaping `\` character when converting to line protocol. here is my python code ``` from influxdb import InfluxDBClient connection = InfluxDBClient(host='localhost', database='telegraf') points = [{ "measurement": "test", "tags": { "tag1": "value1", "tag2": "value\2", "tag3": "value\\3", "tag4": r"value\4", "tag5": r"value\\5" }, "time": 1624989000000000000, "fields": { "value": 10 } }] connection.write_points(points) ``` influx db ``` > select * from test; name: test time tag1 tag2 tag3 tag4 tag5 value ---- ---- ---- ---- ---- ---- ----- 1624989000000000000 value1 value value\\3 value\\4 value\\\\5 10 > INSERT test,tag1=value1,tag2=value\2,tag3=value\3,tag4=value\4,tag5=value\\5 value=10i 1624999000000000000 > select * from test; name: test time tag1 tag2 tag3 tag4 tag5 value ---- ---- ---- ---- ---- ---- ----- 1624989000000000000 value1 value value\\3 value\\4 value\\\\5 10 1624999000000000000 value1 value\2 value\3 value\4 value\\5 10 ``` This was reported on slack before some days please check the conversation link below https://influxcommunity.slack.com/archives/CHQ5VG6F8/p1625576669051600
0.0
cf2186200156c1f5cc2008703bb54775241d2aba
[ "tests/test_point.py::PointTest::test_backslash", "tests/test_point.py::PointTest::test_lineprotocol_encode" ]
[ "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_ConnectToSelfSignedServer", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_TrailingSlashInUrl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_default_conf", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_connection_pool_maxsize", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_proxy", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_ini_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_toml_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_write_context_manager", "tests/test_WriteApi.py::WriteApiTestMock::test_redirect", "tests/test_WriteApi.py::WriteApiTestMock::test_writes_asynchronous_without_retry", "tests/test_WriteApi.py::WriteApiTestMock::test_writes_default_tags_dict_without_tag", "tests/test_WriteApi.py::WriteApiTestMock::test_writes_synchronous_without_retry", "tests/test_point.py::PointTest::test_DateTimeFormatting", "tests/test_point.py::PointTest::test_DateTimeUtc", "tests/test_point.py::PointTest::test_EqualSignEscaping", "tests/test_point.py::PointTest::test_FieldEscape", "tests/test_point.py::PointTest::test_FieldNullValue", "tests/test_point.py::PointTest::test_FieldTypes", "tests/test_point.py::PointTest::test_InstantFormatting", "tests/test_point.py::PointTest::test_MeasurementEscape", "tests/test_point.py::PointTest::test_OverrideTagField", "tests/test_point.py::PointTest::test_TagEmptyKey", "tests/test_point.py::PointTest::test_TagEmptyValue", "tests/test_point.py::PointTest::test_TagEscapingKeyAndValue", "tests/test_point.py::PointTest::test_Time", "tests/test_point.py::PointTest::test_TimePrecisionDefault", "tests/test_point.py::PointTest::test_TimeSpanFormatting", "tests/test_point.py::PointTest::test_from_dict_without_tags", "tests/test_point.py::PointTest::test_from_dict_without_timestamp", "tests/test_point.py::PointTest::test_infinity_values", "tests/test_point.py::PointTest::test_only_infinity_values", "tests/test_point.py::PointTest::test_point_protocol", "tests/test_point.py::PointTest::test_points_from_different_timezones", "tests/test_point.py::PointTest::test_timestamp", "tests/test_point.py::PointTest::test_timezone", "tests/test_point.py::PointTest::test_unsupported_field_type" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-08-13 05:58:24+00:00
mit
2,829
influxdata__influxdb-client-python-502
diff --git a/CHANGELOG.md b/CHANGELOG.md index 13c59ff..d84e990 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ### Features 1. [#498](https://github.com/influxdata/influxdb-client-python/pull/498): Add possibility to update user's password by `users_api` +1. [#502](https://github.com/influxdata/influxdb-client-python/pull/502): Add `FluxRecord.row` with response data stored in array ### Bug Fixes 1. [#497](https://github.com/influxdata/influxdb-client-python/pull/497): Parsing InfluxDB response with new line character in CSV column [async/await] diff --git a/influxdb_client/client/flux_csv_parser.py b/influxdb_client/client/flux_csv_parser.py index 4756d32..db4c4c7 100644 --- a/influxdb_client/client/flux_csv_parser.py +++ b/influxdb_client/client/flux_csv_parser.py @@ -4,6 +4,7 @@ import base64 import codecs import csv as csv_parser +import warnings from enum import Enum from typing import List @@ -262,6 +263,7 @@ class FluxCsvParser(object): column_name = fluxColumn.label str_val = csv[fluxColumn.index + 1] record.values[column_name] = self._to_value(str_val, fluxColumn) + record.row.append(record.values[column_name]) return record @@ -321,6 +323,13 @@ class FluxCsvParser(object): @staticmethod def add_column_names_and_tags(table, csv): """Add labels to columns.""" + if len(csv) != len(set(csv)): + message = f"""The response contains columns with duplicated names: '{csv}'. + +You should use the 'record.row' to access your data instead of 'record.values' dictionary. +""" + warnings.warn(message, UserWarning) + print(message) i = 1 for column in table.columns: column.label = csv[i] diff --git a/influxdb_client/client/flux_table.py b/influxdb_client/client/flux_table.py index 5ae5490..4232476 100644 --- a/influxdb_client/client/flux_table.py +++ b/influxdb_client/client/flux_table.py @@ -101,6 +101,7 @@ class FluxRecord(FluxStructure): values = {} self.table = table self.values = values + self.row = [] def get_start(self): """Get '_start' value."""
influxdata/influxdb-client-python
07224165fb8624ba8dc3cc03a11d7afa7679c67d
diff --git a/tests/query_output.json b/tests/query_output.json index 4cbe36d..b60aac0 100644 --- a/tests/query_output.json +++ b/tests/query_output.json @@ -78,7 +78,18 @@ "_time": "2020-02-27T16:20:00+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:20:00+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -92,7 +103,18 @@ "_time": "2020-02-27T16:21:40+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:21:40+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -106,7 +128,18 @@ "_time": "2020-02-27T16:23:20+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:23:20+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -120,7 +153,18 @@ "_time": "2020-02-27T16:25:00+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:25:00+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -134,7 +178,18 @@ "_time": "2020-02-27T16:26:40+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:26:40+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -148,7 +203,18 @@ "_time": "2020-02-27T16:28:20+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:28:20+00:00", + 2.0, + "test1" + ] }, { "table": 0, @@ -162,7 +228,18 @@ "_time": "2020-02-27T16:30:00+00:00", "_value": 2.0, "tag": "test1" - } + }, + "row": [ + "_result", + 0, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:30:00+00:00", + 2.0, + "test1" + ] } ] }, @@ -245,7 +322,18 @@ "_time": "2020-02-27T16:20:00+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:20:00+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -259,7 +347,18 @@ "_time": "2020-02-27T16:21:40+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:21:40+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -273,7 +372,18 @@ "_time": "2020-02-27T16:23:20+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:23:20+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -287,7 +397,18 @@ "_time": "2020-02-27T16:25:00+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:25:00+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -301,7 +422,18 @@ "_time": "2020-02-27T16:26:40+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:26:40+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -315,7 +447,18 @@ "_time": "2020-02-27T16:28:20+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:28:20+00:00", + 2.0, + "test2" + ] }, { "table": 1, @@ -329,7 +472,18 @@ "_time": "2020-02-27T16:30:00+00:00", "_value": 2.0, "tag": "test2" - } + }, + "row": [ + "_result", + 1, + "value", + "python_client_test", + "2010-02-27T04:48:32.752600+00:00", + "2020-02-27T16:48:32.752600+00:00", + "2020-02-27T16:30:00+00:00", + 2.0, + "test2" + ] } ] } diff --git a/tests/test_FluxCSVParser.py b/tests/test_FluxCSVParser.py index b7461f2..3091ff9 100644 --- a/tests/test_FluxCSVParser.py +++ b/tests/test_FluxCSVParser.py @@ -3,6 +3,7 @@ import math import unittest from io import BytesIO +import pytest from urllib3 import HTTPResponse from influxdb_client.client.flux_csv_parser import FluxCsvParser, FluxSerializationMode, FluxQueryException, \ @@ -356,6 +357,26 @@ class FluxCsvParserTest(unittest.TestCase): self.assertEqual(['south', 'B', None, 18], parsed[2]) self.assertEqual(['south', 'D', None, 22], parsed[3]) + def test_parse_duplicate_column_names(self): + data = """#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,string,string,double +#group,false,false,true,true,false,true,true,false +#default,_result,,,,,,, +,result,table,_start,_stop,_time,_measurement,location,result +,,0,2022-09-13T06:14:40.469404272Z,2022-09-13T06:24:40.469404272Z,2022-09-13T06:24:33.746Z,my_measurement,Prague,25.3 +,,0,2022-09-13T06:14:40.469404272Z,2022-09-13T06:24:40.469404272Z,2022-09-13T06:24:39.299Z,my_measurement,Prague,25.3 +,,0,2022-09-13T06:14:40.469404272Z,2022-09-13T06:24:40.469404272Z,2022-09-13T06:24:40.454Z,my_measurement,Prague,25.3 +""" + with pytest.warns(UserWarning) as warnings: + tables = self._parse_to_tables(data=data) + self.assertEqual(1, len(warnings)) + self.assertEqual(1, tables.__len__()) + self.assertEqual(8, tables[0].columns.__len__()) + self.assertEqual(3, tables[0].records.__len__()) + self.assertEqual(7, tables[0].records[0].values.__len__()) + self.assertEqual(8, tables[0].records[0].row.__len__()) + self.assertEqual(25.3, tables[0].records[0].row[7]) + + @staticmethod def _parse_to_tables(data: str, serialization_mode=FluxSerializationMode.tables, response_metadata_mode=FluxResponseMetadataMode.full) -> TableList:
FluxTable / FluxRecord can't handle tables with duplicate column labels ### Specifications - ### Code sample to reproduce problem Make a query for measurements that include a field called *result* or other labels that occur by default in the [annotated CSV response header](https://docs.influxdata.com/influxdb/v2.4/reference/syntax/annotated-csv/#example). Make the field name part of the annotated CSV response header via `pivot`. The annotated CSV returned by the API will have columns with duplicate labels. ### Expected behavior Being able to access all data returned by the API as annotated CSV ### Actual behavior Flux CSV parser can't handle duplicate header names. It turns CSV rows into `FluxRecord`s whose internal values are represented as python dicts, meaning values from columns with the same label overwrite each other. See [flux_csv_parser.py from line 262](https://github.com/influxdata/influxdb-client-python/blob/1ca66901c9052432d6caa8cc303086918af7d5c1/influxdb_client/client/flux_csv_parser.py#L262-L265) for the logic that collapses a list of columns into a dict based on the column label. ### Additional info _No response_
0.0
07224165fb8624ba8dc3cc03a11d7afa7679c67d
[ "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_parse_duplicate_column_names", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_to_json_by_encoder" ]
[ "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_ParseExportFromUserInterface", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_ParseInf", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_more_tables", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_multiple_queries", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_one_table", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_parse_to_json", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_parse_to_json_columns", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_parse_to_values", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_parse_without_datatype", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_response_with_error", "tests/test_FluxCSVParser.py::FluxCsvParserTest::test_table_index_not_start_at_zero" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-09-14 09:04:39+00:00
mit
2,830
influxdata__influxdb-client-python-559
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6708882..4e8da89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ ## 1.37.0 [unreleased] +### Bug Fixes +1. [#559](https://github.com/influxdata/influxdb-client-python/pull/559): Exceptions in callbacks can cause deadlocks + ## 1.36.0 [2023-01-26] ### Features diff --git a/README.rst b/README.rst index 5e69b75..de6e64f 100644 --- a/README.rst +++ b/README.rst @@ -447,6 +447,9 @@ The batching is configurable by ``write_options``\ : * - **max_retry_delay** - the maximum delay between each retry attempt in milliseconds - ``125_000`` + * - **max_close_wait** + - the maximum amount of time to wait for batches to flush when `.close()` is called + - ``300_000`` * - **exponential_base** - the base for the exponential retry delay, the next delay is computed using random exponential backoff as a random value within the interval ``retry_interval * exponential_base^(attempts-1)`` and ``retry_interval * exponential_base^(attempts)``. Example for ``retry_interval=5_000, exponential_base=2, max_retry_delay=125_000, total=5`` Retry delays are random distributed values within the ranges of ``[5_000-10_000, 10_000-20_000, 20_000-40_000, 40_000-80_000, 80_000-125_000]`` - ``2`` @@ -470,6 +473,7 @@ The batching is configurable by ``write_options``\ : retry_interval=5_000, max_retries=5, max_retry_delay=30_000, + max_close_wait=300_000, exponential_base=2)) as _write_client: """ diff --git a/influxdb_client/client/write_api.py b/influxdb_client/client/write_api.py index f03a3c5..0fcf27c 100644 --- a/influxdb_client/client/write_api.py +++ b/influxdb_client/client/write_api.py @@ -51,6 +51,7 @@ class WriteOptions(object): max_retry_delay=125_000, max_retry_time=180_000, exponential_base=2, + max_close_wait=300_000, write_scheduler=ThreadPoolScheduler(max_workers=1)) -> None: """ Create write api configuration. @@ -66,6 +67,7 @@ class WriteOptions(object): :param max_retry_delay: the maximum delay between each retry attempt in milliseconds :param max_retry_time: total timeout for all retry attempts in milliseconds, if 0 retry is disabled :param exponential_base: base for the exponential retry delay + :parama max_close_wait: the maximum time to wait for writes to be flushed if close() is called :param write_scheduler: """ self.write_type = write_type @@ -78,6 +80,7 @@ class WriteOptions(object): self.max_retry_time = max_retry_time self.exponential_base = exponential_base self.write_scheduler = write_scheduler + self.max_close_wait = max_close_wait def to_retry_strategy(self, **kwargs): """ @@ -410,9 +413,31 @@ You can use native asynchronous version of the client: self._subject.dispose() self._subject = None - # Wait for finish writing + """ + We impose a maximum wait time to ensure that we do not cause a deadlock if the + background thread has exited abnormally + + Each iteration waits 100ms, but sleep expects the unit to be seconds so convert + the maximum wait time to seconds. + + We keep a counter of how long we've waited + """ + max_wait_time = self._write_options.max_close_wait / 1000 + waited = 0 + sleep_period = 0.1 + + # Wait for writing to finish while not self._disposable.is_disposed: - sleep(0.1) + sleep(sleep_period) + waited += sleep_period + + # Have we reached the upper limit? + if waited >= max_wait_time: + logger.warning( + "Reached max_close_wait (%s seconds) waiting for batches to finish writing. Force closing", + max_wait_time + ) + break if self._disposable: self._disposable = None @@ -505,11 +530,25 @@ You can use native asynchronous version of the client: if response.exception: logger.error("The batch item wasn't processed successfully because: %s", response.exception) if self._error_callback: - self._error_callback(response.data.to_key_tuple(), response.data.data, response.exception) + try: + self._error_callback(response.data.to_key_tuple(), response.data.data, response.exception) + except Exception as e: + """ + Unfortunately, because callbacks are user-provided generic code, exceptions can be entirely + arbitrary + + We trap it, log that it occurred and then proceed - there's not much more that we can + really do. + """ + logger.error("The configured error callback threw an exception: %s", e) + else: logger.debug("The batch item: %s was processed successfully.", response) if self._success_callback: - self._success_callback(response.data.to_key_tuple(), response.data.data) + try: + self._success_callback(response.data.to_key_tuple(), response.data.data) + except Exception as e: + logger.error("The configured success callback threw an exception: %s", e) @staticmethod def _on_error(ex): diff --git a/setup.py b/setup.py index 2afe906..5c63fa2 100644 --- a/setup.py +++ b/setup.py @@ -21,6 +21,7 @@ test_requires = [ 'randomize>=0.13', 'pytest>=5.0.0', 'pytest-cov>=3.0.0', + 'pytest-timeout>=2.1.0', 'httpretty==1.0.5', 'psutil>=5.6.3', 'aioresponses>=0.7.3',
influxdata/influxdb-client-python
a07fea6a3d8625ff327be9b824760978958f5246
diff --git a/tests/test_WriteApiBatching.py b/tests/test_WriteApiBatching.py index 917a4a5..8befd7e 100644 --- a/tests/test_WriteApiBatching.py +++ b/tests/test_WriteApiBatching.py @@ -647,6 +647,51 @@ class BatchingWriteTest(unittest.TestCase): self.assertIsInstance(callback.error, InfluxDBError) self.assertEqual(400, callback.error.response.status) + @pytest.mark.timeout(timeout=20) + def test_error_callback_exception(self): + httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=400) + + class ErrorCallback(object): + def __init__(self): + self.conf = None + self.data = None + self.error = None + + def __call__(self, conf: (str, str, str), data: str, error: InfluxDBError): + self.conf = conf + self.data = data + self.error = error + raise Exception('Test generated an error') + + + callback = ErrorCallback() + + self._write_client.close() + self._write_client = WriteApi(influxdb_client=self.influxdb_client, + write_options=WriteOptions(batch_size=2, max_close_wait=2_000), error_callback=callback) + + self._write_client.write("my-bucket", "my-org", + ["h2o_feet,location=coyote_creek water_level=1 x", + "h2o_feet,location=coyote_creek water_level=2 2"]) + + time.sleep(1) + _requests = httpretty.httpretty.latest_requests + self.assertEqual(1, len(_requests)) + self.assertEqual("h2o_feet,location=coyote_creek water_level=1 x\n" + "h2o_feet,location=coyote_creek water_level=2 2", _requests[0].parsed_body) + + self.assertEqual(b"h2o_feet,location=coyote_creek water_level=1 x\n" + b"h2o_feet,location=coyote_creek water_level=2 2", callback.data) + self.assertEqual("my-bucket", callback.conf[0]) + self.assertEqual("my-org", callback.conf[1]) + self.assertEqual("ns", callback.conf[2]) + self.assertIsNotNone(callback.error) + self.assertIsInstance(callback.error, InfluxDBError) + self.assertEqual(400, callback.error.response.status) + + self._write_client.close() + + def test_retry_callback(self): httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=204) httpretty.register_uri(httpretty.POST, uri="http://localhost/api/v2/write", status=429, adding_headers={'Retry-After': '1'})
Exceptions in Callback Handlers can lead to deadlock ### Specifications * Client Version: 1.3.6 * InfluxDB Version: 1.8.10 / 2.x * Platform: Any ### Code sample to reproduce problem Attaching repro script [repro_lockup.py.gz](https://github.com/influxdata/influxdb-client-python/files/10700243/repro_lockup.py.gz) ### Expected behavior Script should exit once processing in `main()` is complete, even if the callback handlers fail (for whatever reason) ### Actual behavior Script runs until killed. Strace shows processing is stuck in sleep ``` clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, {tv_sec=1438366, tv_nsec=978518494}, NULL) = 0 clock_gettime(CLOCK_MONOTONIC, {tv_sec=1438366, tv_nsec=979255844}) = 0 clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, {tv_sec=1438367, tv_nsec=79255844}, NULL) = 0 clock_gettime(CLOCK_MONOTONIC, {tv_sec=1438367, tv_nsec=79775567}) = 0 clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, {tv_sec=1438367, tv_nsec=179775567}, NULL) = 0 clock_gettime(CLOCK_MONOTONIC, {tv_sec=1438367, tv_nsec=180567114}) = 0 ``` Looks to be [this while loop](https://github.com/influxdata/influxdb-client-python/blob/a07fea6a3d8625ff327be9b824760978958f5246/influxdb_client/client/write_api.py#L414) ### Additional info _No response_
0.0
a07fea6a3d8625ff327be9b824760978958f5246
[ "tests/test_WriteApiBatching.py::BatchingWriteTest::test_error_callback_exception" ]
[ "tests/test_WriteApiBatching.py::BatchingWriteTest::test_batch_size", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_batch_size_group_by", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_data_class", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_default_tags", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_del", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_error_callback", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_flush_interval", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_jitter_interval", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_named_tuple", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_record_types", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_recover_from_error", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_retry_callback", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_retry_disabled_max_retries", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_retry_disabled_max_retry_time", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_retry_interval", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_retry_interval_max_retries", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_subscribe_wait", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_success_callback", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_to_low_flush_interval", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_user_agent_header", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_write_point_different_precision", "tests/test_WriteApiBatching.py::BatchingWriteTest::test_write_result" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-09 20:15:20+00:00
mit
2,831
influxdata__influxdb-client-python-631
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f2cb4d..6f11f45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug Fixes 1. [#562](https://github.com/influxdata/influxdb-client-python/pull/562): Use `ThreadPoolScheduler` for `WriteApi`'s batch subject instead of `TimeoutScheduler` to prevent creating unnecessary threads repeatedly +1. [#631](https://github.com/influxdata/influxdb-client-python/pull/631): Logging HTTP requests without query parameters ## 1.39.0 [2023-12-05] diff --git a/influxdb_client/_sync/rest.py b/influxdb_client/_sync/rest.py index 2d80de1..eadbf06 100644 --- a/influxdb_client/_sync/rest.py +++ b/influxdb_client/_sync/rest.py @@ -170,7 +170,7 @@ class RESTClientObject(object): headers['Content-Type'] = 'application/json' if self.configuration.debug: - _BaseRESTClient.log_request(method, f"{url}?{urlencode(query_params)}") + _BaseRESTClient.log_request(method, f"{url}{'' if query_params is None else '?' + urlencode(query_params)}") _BaseRESTClient.log_headers(headers, '>>>') _BaseRESTClient.log_body(body, '>>>')
influxdata/influxdb-client-python
d7181fab9612dd0558822fc40e5d9ccf5a15d56b
diff --git a/tests/test_InfluxDBClient.py b/tests/test_InfluxDBClient.py index ca37291..c2f9b0a 100644 --- a/tests/test_InfluxDBClient.py +++ b/tests/test_InfluxDBClient.py @@ -415,6 +415,18 @@ class InfluxDBClientTestMock(unittest.TestCase): logger = logging.getLogger('influxdb_client.client.http') self.assertEqual(2, len(logger.handlers)) + def test_debug_request_without_query_parameters(self): + httpretty.register_uri(httpretty.GET, uri="http://localhost/ping", status=200, body="") + self.influxdb_client = InfluxDBClient("http://localhost", "my-token", debug=True) + + log_stream = StringIO() + logger = logging.getLogger("influxdb_client.client.http") + logger.addHandler(logging.StreamHandler(log_stream)) + + self.influxdb_client.api_client.call_api('/ping', 'GET') + + self.assertIn("'GET http://localhost/ping'", log_stream.getvalue()) + class ServerWithSelfSingedSSL(http.server.SimpleHTTPRequestHandler): def _set_headers(self, response: bytes):
Ping throwing exception when DEBUG is True ### Specifications * Client Version: influxdb-client-python/1.36.0 * InfluxDB Version: v2.7.1 * Platform: alpine-linux ### Code sample to reproduce problem ```python from influxdb_client import InfluxDBClient client = InfluxDBClient(url='http://localhost:8086', token="MyToken==", org='myorganization', timeout=30000, debug=True) client.api_client.call_api('/ping', 'GET') ``` ### Expected behavior I am using connection check method from official example: examples/connection_check.py to see if my DB is connected. This is working fine, when I have `debug=False`, it will simply pass. ### Actual behavior However, when I do `debug=True` I will get this exception: ``` python3 examples/debug_test.py Traceback (most recent call last): File "/usr/lib/python3.10/urllib/parse.py", line 947, in urlencode if len(query) and not isinstance(query[0], tuple): TypeError: object of type 'NoneType' has no len() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/examples/debug_test.py", line 5, in <module> client.api_client.call_api('/ping', 'GET') File "/usr/lib/python3.10/site-packages/influxdb_client/_sync/api_client.py", line 343, in call_api return self.__call_api(resource_path, method, File "/usr/lib/python3.10/site-packages/influxdb_client/_sync/api_client.py", line 173, in __call_api response_data = self.request( File "/usr/lib/python3.10/site-packages/influxdb_client/_sync/api_client.py", line 365, in request return self.rest_client.GET(url, File "/usr/lib/python3.10/site-packages/influxdb_client/_sync/rest.py", line 268, in GET return self.request("GET", url, File "/usr/lib/python3.10/site-packages/influxdb_client/_sync/rest.py", line 173, in request _BaseRESTClient.log_request(method, f"{url}?{urlencode(query_params)}") File "/usr/lib/python3.10/urllib/parse.py", line 955, in urlencode raise TypeError("not a valid non-string sequence " File "/usr/lib/python3.10/urllib/parse.py", line 947, in urlencode if len(query) and not isinstance(query[0], tuple): TypeError: not a valid non-string sequence or mapping object ``` ### Additional info I was trying different formats of debug variable (string, etc) but none seems to work, boolean is only working option, it seems like there is something in `urllib`.
0.0
d7181fab9612dd0558822fc40e5d9ccf5a15d56b
[ "tests/test_InfluxDBClient.py::InfluxDBClientTestMock::test_debug_request_without_query_parameters" ]
[ "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_ConnectToSelfSignedServer", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_TrailingSlashInUrl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_certificate_context", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_certificate_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_default_conf", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_connection_pool_maxsize", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_kwargs", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_cert_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_cert_file_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_cert_key", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_cert_key_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_key_password", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_env_ssl_key_password_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_kwargs", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_proxy", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_ca_cert_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_cert_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_cert_file_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_cert_key", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_cert_key_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_key_password", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_file_ssl_key_password_default", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_ini_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_ini_file_custom_name", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_json_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_init_from_toml_file", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_timeout_as_float", "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_write_context_manager", "tests/test_InfluxDBClient.py::InfluxDBClientTestMock::test_custom_debug_logging_handler", "tests/test_InfluxDBClient.py::InfluxDBClientTestMock::test_duplicate_debug_logging_handler", "tests/test_InfluxDBClient.py::InfluxDBClientTestMock::test_init_without_token", "tests/test_InfluxDBClient.py::InfluxDBClientTestMock::test_redacted_auth_header" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2024-01-17 13:24:45+00:00
mit
2,832
influxdata__influxdb-client-python-93
diff --git a/CHANGELOG.md b/CHANGELOG.md index 5122bb1..2bf8f08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ ### Bug Fixes 1. [#85](https://github.com/influxdata/influxdb-client-python/issues/85): Fixed a possibility to generate empty write batch 2. [#86](https://github.com/influxdata/influxdb-client-python/issues/86): BREAKING CHANGE: Fixed parameters in delete api - now delete api accepts also bucket name and org name instead of only ids +1. [#93](https://github.com/influxdata/influxdb-client-python/pull/93): Remove trailing slash from connection URL ## 1.6.0 [2020-04-17] diff --git a/influxdb_client/client/influxdb_client.py b/influxdb_client/client/influxdb_client.py index a8ca4ee..a78c130 100644 --- a/influxdb_client/client/influxdb_client.py +++ b/influxdb_client/client/influxdb_client.py @@ -40,7 +40,10 @@ class InfluxDBClient(object): self.default_tags = default_tags conf = _Configuration() - conf.host = self.url + if self.url.endswith("/"): + conf.host = self.url[:-1] + else: + conf.host = self.url conf.enable_gzip = enable_gzip conf.debug = debug
influxdata/influxdb-client-python
e68cf1a2030bc33c9619907227615adebe2070cc
diff --git a/tests/test_BucketsApi.py b/tests/test_BucketsApi.py index a528bf0..876e5e6 100644 --- a/tests/test_BucketsApi.py +++ b/tests/test_BucketsApi.py @@ -37,6 +37,7 @@ class BucketsClientTest(BaseTest): assert self.buckets_api.find_bucket_by_id(my_bucket.id) assert "bucket not found" in e.value.body + @pytest.mark.skip(reason="https://github.com/influxdata/influxdb/issues/14900") def test_find_by_name(self): my_org = self.find_my_org() diff --git a/tests/test_InfluxDBClient.py b/tests/test_InfluxDBClient.py new file mode 100644 index 0000000..1e8da1d --- /dev/null +++ b/tests/test_InfluxDBClient.py @@ -0,0 +1,13 @@ +import unittest + +from influxdb_client import InfluxDBClient + + +class InfluxDBClientTest(unittest.TestCase): + + def test_TrailingSlashInUrl(self): + client = InfluxDBClient(url="http://localhost:9999", token="my-token", org="my-org") + self.assertEqual('http://localhost:9999', client.api_client.configuration.host) + + client = InfluxDBClient(url="http://localhost:9999/", token="my-token", org="my-org") + self.assertEqual('http://localhost:9999', client.api_client.configuration.host)
trim trailing slash for urls When using a url without a trailing slash, everything works fine: `client = InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdata.com", token=token, org=org, debug=True)` But when adding a trailing slash to the url: `client = InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdata.com/", token=token, org=org, debug=True)` the error that comes back is `HTTP response body: {"code":"not found","message":"path not found"}` when I use InfluxDB cloud. For localhost, without a slash, i get a 200, but with a slash, i get a 204. IMO, we should detect and trim the trailing slash from the connection urls.
0.0
e68cf1a2030bc33c9619907227615adebe2070cc
[ "tests/test_InfluxDBClient.py::InfluxDBClientTest::test_TrailingSlashInUrl" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-05-12 10:14:52+00:00
mit
2,833
inhumantsar__python-ec2-reaper-15
diff --git a/ec2_reaper/aws_lambda.py b/ec2_reaper/aws_lambda.py index e9fcdd2..e90645d 100644 --- a/ec2_reaper/aws_lambda.py +++ b/ec2_reaper/aws_lambda.py @@ -25,10 +25,15 @@ TAG_MATCHER = json.loads(TAG_MATCHER) if isinstance(TAG_MATCHER, strclasses) els SLACK_ENDPOINT = os.environ.get('SLACK_ENDPOINT', None) DEBUG = os.environ.get('DEBUG', True) +log.debug('startup: got value for DEBUG: {} ({})'.format(DEBUG, type(DEBUG))) +if isinstance(DEBUG, str): + DEBUG = False if DEBUG.lower() == 'false' else True + if DEBUG: log.setLevel(logging.DEBUG) logging.getLogger('botocore').setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.INFO) + log.debug('startup: debug logging on') else: log.setLevel(logging.INFO) logging.getLogger('botocore').setLevel(logging.WARNING)
inhumantsar/python-ec2-reaper
d4b0f08b945f95f550149482486c4301f87f3619
diff --git a/tests/test_lambda_handler.py b/tests/test_lambda_handler.py index bc153b4..7ad0968 100644 --- a/tests/test_lambda_handler.py +++ b/tests/test_lambda_handler.py @@ -2,6 +2,7 @@ import logging import json import sys from datetime import datetime, timedelta +import os from ec2_reaper import aws_lambda from ec2_reaper import LOCAL_TZ @@ -10,12 +11,19 @@ logging.basicConfig(level=logging.DEBUG) logging.getLogger('botocore').setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.INFO) +# mock has some weirdness in python 3.3, 3.5, and 3.6 if sys.version_info < (3, 0) or (sys.version_info >= (3, 5) and sys.version_info < (3, 6)): from mock import patch else: from unittest.mock import patch +# py 2.7 has reload built in but it's moved around a bit in py3+ +if sys.version_info >= (3, 0) and sys.version_info < (3, 4): + from imp import reload +elif sys.version_info >= (3, 4): + from importlib import reload + # when no results, handler should have called reap, *not* called (slack) notify, # and should have returned a happy response json obj, @patch.object(aws_lambda, 'reap') @@ -55,3 +63,27 @@ def test_reap_2neg_1pos(mock_notify, mock_reap): assert r['statusCode'] == 200 assert r['body']['log'] == mock_reap_results assert r['body']['reaped'] == 1 + +# env vars come in as strings, so bools like DEBUG need testing +def test_debug_envvar(): + from ec2_reaper import aws_lambda as al + # true + os.environ['DEBUG'] = 'true' + reload(al) + assert al.DEBUG == True + os.environ['DEBUG'] = 'True' + reload(al) + assert al.DEBUG == True + + # default to safety + os.environ['DEBUG'] = 'mooooooooo' + reload(al) + assert al.DEBUG == True + + # false + os.environ['DEBUG'] = 'False' + reload(al) + assert al.DEBUG == False + os.environ['DEBUG'] = 'false' + reload(al) + assert al.DEBUG == False
lambda function doesn't honor the debug option properly passed `DEBUG: false` as an env var but it still does NO-OPs and debug logging. the env var is probably being read by python in as a string.
0.0
d4b0f08b945f95f550149482486c4301f87f3619
[ "tests/test_lambda_handler.py::test_debug_envvar" ]
[ "tests/test_lambda_handler.py::test_reap_no_results", "tests/test_lambda_handler.py::test_reap_2neg_1pos" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2017-12-27 16:55:28+00:00
bsd-3-clause
2,834