instance_id
stringlengths
12
57
base_commit
stringlengths
40
40
created_at
stringdate
2015-01-06 14:05:07
2025-04-29 17:56:51
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
158k
patch
stringlengths
261
20.8k
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
280
206k
meta
dict
version
stringclasses
463 values
install_config
dict
requirements
stringlengths
93
34k
environment
stringlengths
772
20k
FAIL_TO_PASS
sequencelengths
1
856
FAIL_TO_FAIL
sequencelengths
0
536
PASS_TO_PASS
sequencelengths
0
7.87k
PASS_TO_FAIL
sequencelengths
0
92
license_name
stringclasses
35 values
__index_level_0__
int64
11
21.4k
num_tokens_patch
int64
103
4.99k
before_filepaths
sequencelengths
0
14
dask__dask-3606
279fdf7a6a78a1dfaa0974598aead3e1b44f9194
2018-06-13 16:07:48
279fdf7a6a78a1dfaa0974598aead3e1b44f9194
diff --git a/dask/dataframe/core.py b/dask/dataframe/core.py index 146b1eb9f..be22829a1 100644 --- a/dask/dataframe/core.py +++ b/dask/dataframe/core.py @@ -1030,12 +1030,15 @@ Dask Name: {name}, {task} tasks""".format(klass=self.__class__.__name__, def bfill(self, axis=None, limit=None): return self.fillna(method='bfill', limit=limit, axis=axis) - def sample(self, frac, replace=False, random_state=None): + def sample(self, n=None, frac=None, replace=False, random_state=None): """ Random sample of items Parameters ---------- - frac : float + n : int, optional + Number of items to return is not supported by dask. Use frac + instead. + frac : float, optional Fraction of axis items to return. replace : boolean, optional Sample with or without replacement. Default = False. @@ -1048,6 +1051,17 @@ Dask Name: {name}, {task} tasks""".format(klass=self.__class__.__name__, DataFrame.random_split pandas.DataFrame.sample """ + if n is not None: + msg = ("sample does not support the number of sampled items " + "parameter, 'n'. Please use the 'frac' parameter instead.") + if isinstance(n, Number) and 0 <= n <= 1: + warnings.warn(msg) + frac = n + else: + raise ValueError(msg) + + if frac is None: + raise ValueError("frac must not be None") if random_state is None: random_state = np.random.RandomState()
DataFrame.sample function signature differs from pandas - `pandas.DataFrame.sample(n, frac, ...)` - `dask.dataframe.DataFrame.sample(frac, ...)` We can't reliably do `n`, so we should raise if it's anything but `None`. But it'd still be nice to match the signature.
dask/dask
diff --git a/dask/dataframe/tests/test_dataframe.py b/dask/dataframe/tests/test_dataframe.py index b155de6c9..06d1dae90 100644 --- a/dask/dataframe/tests/test_dataframe.py +++ b/dask/dataframe/tests/test_dataframe.py @@ -1379,7 +1379,7 @@ def test_embarrassingly_parallel_operations(): assert_eq(a.notnull(), df.notnull()) assert_eq(a.isnull(), df.isnull()) - assert len(a.sample(0.5).compute()) < len(df) + assert len(a.sample(frac=0.5).compute()) < len(df) def test_fillna(): @@ -1452,26 +1452,46 @@ def test_sample(): index=[10, 20, 30, 40, 50, 60]) a = dd.from_pandas(df, 2) - b = a.sample(0.5) + b = a.sample(frac=0.5) assert_eq(b, b) - c = a.sample(0.5, random_state=1234) - d = a.sample(0.5, random_state=1234) + c = a.sample(frac=0.5, random_state=1234) + d = a.sample(frac=0.5, random_state=1234) assert_eq(c, d) - assert a.sample(0.5)._name != a.sample(0.5)._name + assert a.sample(frac=0.5)._name != a.sample(frac=0.5)._name def test_sample_without_replacement(): df = pd.DataFrame({'x': [1, 2, 3, 4, None, 6], 'y': list('abdabd')}, index=[10, 20, 30, 40, 50, 60]) a = dd.from_pandas(df, 2) - b = a.sample(0.7, replace=False) + b = a.sample(frac=0.7, replace=False) bb = b.index.compute() assert len(bb) == len(set(bb)) +def test_sample_raises(): + df = pd.DataFrame({'x': [1, 2, 3, 4, None, 6], 'y': list('abdabd')}, + index=[10, 20, 30, 40, 50, 60]) + a = dd.from_pandas(df, 2) + + # Make sure frac is replaced with n when 0 <= n <= 1 + # This is so existing code (i.e. ddf.sample(0.5)) won't break + with pytest.warns(UserWarning): + b = a.sample(0.5, random_state=1234) + c = a.sample(frac=0.5, random_state=1234) + assert_eq(b, c) + + with pytest.raises(ValueError): + a.sample(n=10) + + # Make sure frac is provided + with pytest.raises(ValueError): + a.sample(frac=None) + + def test_datetime_accessor(): df = pd.DataFrame({'x': [1, 2, 3, 4]}) df['x'] = df.x.astype('M8[us]')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
0.17
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 click==8.0.4 cloudpickle==2.2.1 -e git+https://github.com/dask/dask.git@279fdf7a6a78a1dfaa0974598aead3e1b44f9194#egg=dask distributed==1.21.8 HeapDict==1.0.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work locket==1.0.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work msgpack==1.0.5 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 partd==1.2.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 python-dateutil==2.9.0.post0 pytz==2025.2 six==1.17.0 sortedcontainers==2.4.0 tblib==1.7.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work toolz==0.12.0 tornado==6.1 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zict==2.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - click==8.0.4 - cloudpickle==2.2.1 - distributed==1.21.8 - heapdict==1.0.1 - locket==1.0.0 - msgpack==1.0.5 - numpy==1.19.5 - pandas==1.1.5 - partd==1.2.0 - psutil==7.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - six==1.17.0 - sortedcontainers==2.4.0 - tblib==1.7.0 - toolz==0.12.0 - tornado==6.1 - zict==2.1.0 prefix: /opt/conda/envs/dask
[ "dask/dataframe/tests/test_dataframe.py::test_sample_raises" ]
[ "dask/dataframe/tests/test_dataframe.py::test_Dataframe", "dask/dataframe/tests/test_dataframe.py::test_attributes", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[npartitions1]", "dask/dataframe/tests/test_dataframe.py::test_clip[2-5]", "dask/dataframe/tests/test_dataframe.py::test_clip[2.5-3.5]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_picklable", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_month", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include0-None]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[None-exclude1]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include2-exclude2]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include3-None]", "dask/dataframe/tests/test_dataframe.py::test_to_timestamp", "dask/dataframe/tests/test_dataframe.py::test_apply", "dask/dataframe/tests/test_dataframe.py::test_apply_warns", "dask/dataframe/tests/test_dataframe.py::test_apply_infer_columns", "dask/dataframe/tests/test_dataframe.py::test_info", "dask/dataframe/tests/test_dataframe.py::test_groupby_multilevel_info", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-False]", "dask/dataframe/tests/test_dataframe.py::test_shift", "dask/dataframe/tests/test_dataframe.py::test_shift_with_freq", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[first]", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[last]", "dask/dataframe/tests/test_dataframe.py::test_datetime_loc_open_slicing" ]
[ "dask/dataframe/tests/test_dataframe.py::test_head_tail", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions_warn", "dask/dataframe/tests/test_dataframe.py::test_index_head", "dask/dataframe/tests/test_dataframe.py::test_Series", "dask/dataframe/tests/test_dataframe.py::test_Index", "dask/dataframe/tests/test_dataframe.py::test_Scalar", "dask/dataframe/tests/test_dataframe.py::test_column_names", "dask/dataframe/tests/test_dataframe.py::test_index_names", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[1]", "dask/dataframe/tests/test_dataframe.py::test_rename_columns", "dask/dataframe/tests/test_dataframe.py::test_rename_series", "dask/dataframe/tests/test_dataframe.py::test_rename_series_method", "dask/dataframe/tests/test_dataframe.py::test_describe", "dask/dataframe/tests/test_dataframe.py::test_describe_empty", "dask/dataframe/tests/test_dataframe.py::test_cumulative", "dask/dataframe/tests/test_dataframe.py::test_dropna", "dask/dataframe/tests/test_dataframe.py::test_squeeze", "dask/dataframe/tests/test_dataframe.py::test_where_mask", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_multi_argument", "dask/dataframe/tests/test_dataframe.py::test_map_partitions", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_column_info", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_method_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_keeps_kwargs_readable", "dask/dataframe/tests/test_dataframe.py::test_metadata_inference_single_partition_aligned_args", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates_subset", "dask/dataframe/tests/test_dataframe.py::test_get_partition", "dask/dataframe/tests/test_dataframe.py::test_ndim", "dask/dataframe/tests/test_dataframe.py::test_dtype", "dask/dataframe/tests/test_dataframe.py::test_value_counts", "dask/dataframe/tests/test_dataframe.py::test_unique", "dask/dataframe/tests/test_dataframe.py::test_isin", "dask/dataframe/tests/test_dataframe.py::test_len", "dask/dataframe/tests/test_dataframe.py::test_size", "dask/dataframe/tests/test_dataframe.py::test_nbytes", "dask/dataframe/tests/test_dataframe.py::test_quantile", "dask/dataframe/tests/test_dataframe.py::test_quantile_missing", "dask/dataframe/tests/test_dataframe.py::test_empty_quantile", "dask/dataframe/tests/test_dataframe.py::test_dataframe_quantile", "dask/dataframe/tests/test_dataframe.py::test_index", "dask/dataframe/tests/test_dataframe.py::test_assign", "dask/dataframe/tests/test_dataframe.py::test_map", "dask/dataframe/tests/test_dataframe.py::test_concat", "dask/dataframe/tests/test_dataframe.py::test_args", "dask/dataframe/tests/test_dataframe.py::test_known_divisions", "dask/dataframe/tests/test_dataframe.py::test_unknown_divisions", "dask/dataframe/tests/test_dataframe.py::test_align[inner]", "dask/dataframe/tests/test_dataframe.py::test_align[outer]", "dask/dataframe/tests/test_dataframe.py::test_align[left]", "dask/dataframe/tests/test_dataframe.py::test_align[right]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[inner]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[outer]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[left]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[right]", "dask/dataframe/tests/test_dataframe.py::test_combine", "dask/dataframe/tests/test_dataframe.py::test_combine_first", "dask/dataframe/tests/test_dataframe.py::test_random_partitions", "dask/dataframe/tests/test_dataframe.py::test_series_round", "dask/dataframe/tests/test_dataframe.py::test_repartition_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_on_pandas_dataframe", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions_same_limits", "dask/dataframe/tests/test_dataframe.py::test_repartition_object_index", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_errors", "dask/dataframe/tests/test_dataframe.py::test_embarrassingly_parallel_operations", "dask/dataframe/tests/test_dataframe.py::test_fillna", "dask/dataframe/tests/test_dataframe.py::test_fillna_multi_dataframe", "dask/dataframe/tests/test_dataframe.py::test_ffill_bfill", "dask/dataframe/tests/test_dataframe.py::test_fillna_series_types", "dask/dataframe/tests/test_dataframe.py::test_sample", "dask/dataframe/tests/test_dataframe.py::test_sample_without_replacement", "dask/dataframe/tests/test_dataframe.py::test_datetime_accessor", "dask/dataframe/tests/test_dataframe.py::test_str_accessor", "dask/dataframe/tests/test_dataframe.py::test_empty_max", "dask/dataframe/tests/test_dataframe.py::test_deterministic_apply_concat_apply_names", "dask/dataframe/tests/test_dataframe.py::test_aca_meta_infer", "dask/dataframe/tests/test_dataframe.py::test_aca_split_every", "dask/dataframe/tests/test_dataframe.py::test_reduction_method", "dask/dataframe/tests/test_dataframe.py::test_reduction_method_split_every", "dask/dataframe/tests/test_dataframe.py::test_pipe", "dask/dataframe/tests/test_dataframe.py::test_gh_517", "dask/dataframe/tests/test_dataframe.py::test_drop_axis_1", "dask/dataframe/tests/test_dataframe.py::test_gh580", "dask/dataframe/tests/test_dataframe.py::test_rename_dict", "dask/dataframe/tests/test_dataframe.py::test_rename_function", "dask/dataframe/tests/test_dataframe.py::test_rename_index", "dask/dataframe/tests/test_dataframe.py::test_to_frame", "dask/dataframe/tests/test_dataframe.py::test_applymap", "dask/dataframe/tests/test_dataframe.py::test_abs", "dask/dataframe/tests/test_dataframe.py::test_round", "dask/dataframe/tests/test_dataframe.py::test_cov", "dask/dataframe/tests/test_dataframe.py::test_corr", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_meta", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_mixed", "dask/dataframe/tests/test_dataframe.py::test_autocorr", "dask/dataframe/tests/test_dataframe.py::test_index_time_properties", "dask/dataframe/tests/test_dataframe.py::test_nlargest_nsmallest", "dask/dataframe/tests/test_dataframe.py::test_reset_index", "dask/dataframe/tests/test_dataframe.py::test_dataframe_compute_forward_kwargs", "dask/dataframe/tests/test_dataframe.py::test_series_iteritems", "dask/dataframe/tests/test_dataframe.py::test_dataframe_iterrows", "dask/dataframe/tests/test_dataframe.py::test_dataframe_itertuples", "dask/dataframe/tests/test_dataframe.py::test_astype", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals_known", "dask/dataframe/tests/test_dataframe.py::test_groupby_callable", "dask/dataframe/tests/test_dataframe.py::test_methods_tokenize_differently", "dask/dataframe/tests/test_dataframe.py::test_categorize_info", "dask/dataframe/tests/test_dataframe.py::test_gh_1301", "dask/dataframe/tests/test_dataframe.py::test_timeseries_sorted", "dask/dataframe/tests/test_dataframe.py::test_column_assignment", "dask/dataframe/tests/test_dataframe.py::test_columns_assignment", "dask/dataframe/tests/test_dataframe.py::test_attribute_assignment", "dask/dataframe/tests/test_dataframe.py::test_setitem_triggering_realign", "dask/dataframe/tests/test_dataframe.py::test_inplace_operators", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_getitem_meta", "dask/dataframe/tests/test_dataframe.py::test_getitem_multilevel", "dask/dataframe/tests/test_dataframe.py::test_getitem_string_subclass", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[list]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[array]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Series]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Index]", "dask/dataframe/tests/test_dataframe.py::test_diff", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-20]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[2]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[2]", "dask/dataframe/tests/test_dataframe.py::test_values", "dask/dataframe/tests/test_dataframe.py::test_copy", "dask/dataframe/tests/test_dataframe.py::test_del", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-False]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-False]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sum]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[mean]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[std]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[var]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[count]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[min]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[max]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmin]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmax]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[prod]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[all]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sem]", "dask/dataframe/tests/test_dataframe.py::test_to_datetime", "dask/dataframe/tests/test_dataframe.py::test_to_timedelta", "dask/dataframe/tests/test_dataframe.py::test_isna[values0]", "dask/dataframe/tests/test_dataframe.py::test_isna[values1]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[0]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_nonmonotonic", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-False-drop0]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-True-drop1]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-False-False-drop2]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-True-False-drop3]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-False-drop4]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-True-drop5]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1.5-None-False-True-drop6]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-False-False-drop7]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-True-False-drop8]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-2.5-False-False-drop9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index0-0-9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index1--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index2-None-10]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index3-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index4--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index5-None-2]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index6--2-3]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index7-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index8-left8-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index9-None-right9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index10-left10-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index11-None-right11]", "dask/dataframe/tests/test_dataframe.py::test_better_errors_object_reductions", "dask/dataframe/tests/test_dataframe.py::test_sample_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_coerce", "dask/dataframe/tests/test_dataframe.py::test_bool", "dask/dataframe/tests/test_dataframe.py::test_cumulative_multiple_columns", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[asarray]", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[func1]", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations_errors", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_multi_dimensional", "dask/dataframe/tests/test_dataframe.py::test_meta_raises" ]
[]
BSD 3-Clause "New" or "Revised" License
2,662
411
[ "dask/dataframe/core.py" ]
elastic__rally-524
54edbccaef684a2a5e202ba37b3fd0ca1b786821
2018-06-14 07:32:19
085e3d482717d88dfc2d41aa34502eb108abbfe9
diff --git a/esrally/config.py b/esrally/config.py index a4a65a81..d9152ec7 100644 --- a/esrally/config.py +++ b/esrally/config.py @@ -38,8 +38,8 @@ class ConfigFile: """ return os.path.isfile(self.location) - def load(self, interpolation=configparser.ExtendedInterpolation()): - config = configparser.ConfigParser(interpolation=interpolation) + def load(self): + config = configparser.ConfigParser() config.read(self.location, encoding="utf-8") return config @@ -370,7 +370,7 @@ class ConfigFactory: config["source"]["elasticsearch.src.subdir"] = io.basename(source_dir) config["benchmarks"] = {} - config["benchmarks"]["local.dataset.cache"] = "${node:root.dir}/data" + config["benchmarks"]["local.dataset.cache"] = os.path.join(root_dir, "data") config["reporting"] = {} config["reporting"]["datastore.type"] = data_store_type @@ -515,7 +515,7 @@ def migrate(config_file, current_version, target_version, out=print, i=input): % (target_version, current_version)) # but first a backup... config_file.backup() - config = config_file.load(interpolation=None) + config = config_file.load() if current_version == 12 and target_version > current_version: # the current configuration allows to benchmark from sources @@ -633,6 +633,10 @@ def migrate(config_file, current_version, target_version, out=print, i=input): if current_version == 16 and target_version > current_version: config.pop("runtime", None) + if "benchmarks" in config and "local.dataset.cache" in config["benchmarks"]: + if config["benchmarks"]["local.dataset.cache"] == "${node:root.dir}/data": + root_dir = config["node"]["root.dir"] + config["benchmarks"]["local.dataset.cache"] = os.path.join(root_dir, "data") current_version = 17 config["meta"]["config.version"] = str(current_version)
Password with symbols can cause errors parsing rally.ini file **Rally version**: 0.11.0 **OS version**: Ubuntu 16.04 **Description of the problem including expected versus actual behavior**: I specified an Elastic Cloud cluster as the metrics store and picked a password that contained a `$` followed by a character. This resulted in the following error when I tried to run the eventdata track: ``` Traceback (most recent call last): File "/usr/local/bin/esrally", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 588, in main ensure_configuration_present(cfg, args, sub_command) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 428, in ensure_configuration_present cfg.load_config(auto_upgrade=True) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 206, in load_config self.migrate_config() File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 239, in migrate_config migrate(self.config_file, self._stored_config_version(), Config.CURRENT_CONFIG_VERSION) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 588, in migrate .format(config_file.location, PROGRAM_NAME)) esrally.config.ConfigError: ('The config file in /home/ubuntu/.rally/rally.ini is too old. Please delete it and reconfigure Rally from scratch with esrally configure.', None) ```
elastic/rally
diff --git a/tests/config_test.py b/tests/config_test.py index 9e42da3f..8ace3469 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -252,6 +252,7 @@ class ConfigFactoryTests(TestCase): for k, v in config_store.config[section].items(): print("%s::%s: %s" % (section, k, v)) + root_dir = io.normalize_path(os.path.abspath("./in-memory/benchmarks")) self.assertTrue("meta" in config_store.config) self.assertEqual(str(config.Config.CURRENT_CONFIG_VERSION), config_store.config["meta"]["config.version"]) @@ -259,15 +260,16 @@ class ConfigFactoryTests(TestCase): self.assertEqual("local", config_store.config["system"]["env.name"]) self.assertTrue("node" in config_store.config) - self.assertEqual(io.normalize_path(os.path.abspath("./in-memory/benchmarks")), config_store.config["node"]["root.dir"]) - self.assertEqual(io.normalize_path(os.path.abspath("./in-memory/benchmarks/src")), config_store.config["node"]["src.root.dir"]) + + self.assertEqual(root_dir, config_store.config["node"]["root.dir"]) + self.assertEqual(os.path.join(root_dir, "src"), config_store.config["node"]["src.root.dir"]) self.assertTrue("source" in config_store.config) self.assertEqual("https://github.com/elastic/elasticsearch.git", config_store.config["source"]["remote.repo.url"]) self.assertEqual("elasticsearch", config_store.config["source"]["elasticsearch.src.subdir"]) self.assertTrue("benchmarks" in config_store.config) - self.assertEqual("${node:root.dir}/data", config_store.config["benchmarks"]["local.dataset.cache"]) + self.assertEqual(os.path.join(root_dir, "data"), config_store.config["benchmarks"]["local.dataset.cache"]) self.assertTrue("reporting" in config_store.config) self.assertEqual("in-memory", config_store.config["reporting"]["datastore.type"]) @@ -765,5 +767,29 @@ class ConfigMigrationTests(TestCase): self.assertIn("distributions", config_file.config) self.assertNotIn("release.url", config_file.config["distributions"]) + def test_migrate_from_16_to_17(self): + config_file = InMemoryConfigStore("test") + sample_config = { + "meta": { + "config.version": 16 + }, + "node": { + "root.dir": "/home/user/.rally/benchmarks" + }, + "runtime": { + "java.home": "/usr/local/javas/10" + }, + "benchmarks": { + "local.dataset.cache": "${node:root.dir}/data" + } + } + config_file.store(sample_config) + config.migrate(config_file, 16, 17, out=null_output) + + self.assertTrue(config_file.backup_created) + self.assertEqual("17", config_file.config["meta"]["config.version"]) + self.assertNotIn("runtime", config_file.config) + self.assertEqual("/home/user/.rally/benchmarks/data", config_file.config["benchmarks"]["local.dataset.cache"]) +
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc python3-dev" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@54edbccaef684a2a5e202ba37b3fd0ca1b786821#egg=esrally exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==3.0.2 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work psutil==5.4.0 py-cpuinfo==3.2.0 pytest @ file:///croot/pytest_1738938843180/work pytest-benchmark==5.1.0 tabulate==0.8.1 thespian==3.9.2 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work urllib3==1.22
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - elasticsearch==6.2.0 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==3.0.2 - psutil==5.4.0 - py-cpuinfo==3.2.0 - pytest-benchmark==5.1.0 - tabulate==0.8.1 - thespian==3.9.2 - urllib3==1.22 prefix: /opt/conda/envs/rally
[ "tests/config_test.py::ConfigFactoryTests::test_create_simple_config", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_16_to_17" ]
[]
[ "tests/config_test.py::ConfigTests::test_add_all_in_section", "tests/config_test.py::ConfigTests::test_load_all_opts_in_section", "tests/config_test.py::ConfigTests::test_load_existing_config", "tests/config_test.py::ConfigTests::test_load_non_existing_config", "tests/config_test.py::AutoLoadConfigTests::test_can_create_non_existing_config", "tests/config_test.py::AutoLoadConfigTests::test_can_load_and_amend_existing_config", "tests/config_test.py::AutoLoadConfigTests::test_can_migrate_outdated_config", "tests/config_test.py::ConfigFactoryTests::test_create_advanced_config", "tests/config_test.py::ConfigMigrationTests::test_does_not_migrate_outdated_config", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_12_to_13_with_gradle_and_jdk8_ask_user_and_skip", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_12_to_13_with_gradle_and_jdk8_ask_user_enter_valid", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_12_to_13_with_gradle_and_jdk8_autodetect_jdk9", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_12_to_13_with_gradle_and_jdk9", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_12_to_13_without_gradle", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_13_to_14_with_gradle_and_jdk10", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_13_to_14_with_gradle_and_jdk8_ask_user_and_skip", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_13_to_14_with_gradle_and_jdk8_ask_user_enter_valid", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_13_to_14_with_gradle_and_jdk8_autodetect_jdk10", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_13_to_14_without_gradle", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_14_to_15_with_gradle", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_14_to_15_with_source_plugin_definition", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_14_to_15_without_gradle", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_15_to_16", "tests/config_test.py::ConfigMigrationTests::test_migrate_from_earliest_supported_to_latest" ]
[]
Apache License 2.0
2,666
503
[ "esrally/config.py" ]
joke2k__faker-772
da96379c07dbd22bea070db5a8a3e1ad85e4cf04
2018-06-15 02:21:52
29dff0a0f2a31edac21a18cfa50b5bc9206304b2
diff --git a/faker/providers/ssn/en_US/__init__.py b/faker/providers/ssn/en_US/__init__.py index 4357535c..a6930f4a 100644 --- a/faker/providers/ssn/en_US/__init__.py +++ b/faker/providers/ssn/en_US/__init__.py @@ -1,19 +1,169 @@ # coding=utf-8 from __future__ import unicode_literals + +import random from .. import Provider as BaseProvider class Provider(BaseProvider): + SSN_TYPE = 'SSN' + ITIN_TYPE = 'ITIN' + EIN_TYPE = 'EIN' + + def itin(self): + """Generate a random United States Individual Taxpayer Identification Number (ITIN). + + An United States Individual Taxpayer Identification Number + (ITIN) is a tax processing number issued by the Internal + Revenue Service. It is a nine-digit number that always begins + with the number 9 and has a range of 70-88 in the fourth and + fifth digit. Effective April 12, 2011, the range was extended + to include 900-70-0000 through 999-88-9999, 900-90-0000 + through 999-92-9999 and 900-94-0000 through 999-99-9999. + https://www.irs.gov/individuals/international-taxpayers/general-itin-information + """ + + area = self.random_int(min=900, max=999) + serial = self.random_int(min=0, max=9999) + + # The group number must be between 70 and 99 inclusively but not 89 or 93 + group = random.choice([x for x in range(70,100) if x not in [89, 93]]) + + itin = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial) + return itin + + def ein(self): + """Generate a random United States Employer Identification Number (EIN). + + An United States An Employer Identification Number (EIN) is + also known as a Federal Tax Identification Number, and is + used to identify a business entity. EINs follow a format of a + two-digit prefix followed by a hyphen and a seven-digit sequence: + ##-###### + + https://www.irs.gov/businesses/small-businesses-self-employed/employer-id-numbers + """ + + # Only certain EIN Prefix values are assigned: + # + # https://www.irs.gov/businesses/small-businesses-self-employed/how-eins-are-assigned-and-valid-ein-prefixes + + ein_prefix_choices = [ + '01', + '02', + '03', + '04', + '05', + '06', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '20', + '21', + '22', + '23', + '24', + '25', + '26', + '27', + '30', + '31', + '32', + '33', + '34', + '35', + '36', + '37', + '38', + '39', + '40', + '41', + '42', + '43', + '44', + '45', + '46', + '47', + '48', + '50', + '51', + '52', + '53', + '54', + '55', + '56', + '57', + '58', + '59', + '60', + '61', + '62', + '63', + '64', + '65', + '66', + '67', + '68', + '71', + '72', + '73', + '74', + '75', + '76', + '77', + '80', + '81', + '82', + '83', + '84', + '85', + '86', + '87', + '88', + '90', + '91', + '92', + '93', + '94', + '95', + '98', + '99'] + + ein_prefix = random.choice(ein_prefix_choices) + sequence = self.random_int(min=0, max=9999999) + + ein = "{0:s}-{1:07d}".format(ein_prefix, sequence) + return ein + + def ssn(self, taxpayer_identification_number_type=SSN_TYPE): + """ Generate a random United States Taxpayer Identification Number of the specified type. + + If no type is specified, a US SSN is returned. + """ + + if taxpayer_identification_number_type == self.ITIN_TYPE: + return self.itin() + elif taxpayer_identification_number_type == self.EIN_TYPE: + return self.ein() + elif taxpayer_identification_number_type == self.SSN_TYPE: + + # Certain numbers are invalid for United States Social Security + # Numbers. The area (first 3 digits) cannot be 666 or 900-999. + # The group number (middle digits) cannot be 00. The serial + # (last 4 digits) cannot be 0000. + + area = self.random_int(min=1, max=899) + if area == 666: + area += 1 + group = self.random_int(1, 99) + serial = self.random_int(1, 9999) - def ssn(self): - # Certain numbers are invalid for U.S. SSNs. The area (first 3 digits) - # cannot be 666 or 900-999. The group number (middle digits) cannot be - # 00. The serial (last 4 digits) cannot be 0000 - area = self.random_int(min=1, max=899) - if area == 666: - area += 1 - group = self.random_int(1, 99) - serial = self.random_int(1, 9999) - - ssn = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial) - return ssn + ssn = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial) + return ssn + + else: + raise ValueError("taxpayer_identification_number_type must be one of 'SSN', 'EIN', or 'ITIN'.")
Support United States ITIN and EIN tax identification numbers While United States SSNs are used by naturalized aliens and citizens, but businesses are identified by EINs and IRS issues ITINs to foreign nationals and others who have federal tax reporting or filing requirements and do not qualify for SSNs. Each type of tax identification number follows specific rules.
joke2k/faker
diff --git a/tests/providers/test_ssn.py b/tests/providers/test_ssn.py index ea58fcf8..06234fd5 100644 --- a/tests/providers/test_ssn.py +++ b/tests/providers/test_ssn.py @@ -15,6 +15,7 @@ from faker.providers.ssn.pt_BR import checksum as pt_checksum from faker.providers.ssn.pl_PL import checksum as pl_checksum, calculate_month as pl_calculate_mouth from faker.providers.ssn.no_NO import checksum as no_checksum, Provider as no_Provider + class TestEnCA(unittest.TestCase): def setUp(self): self.factory = Faker('en_CA') @@ -26,11 +27,207 @@ class TestEnCA(unittest.TestCase): # Ensure that generated SINs are 11 characters long # including spaces, consist of spaces and digits only, and - # satisfy the validation algorithm. + # satisfy the validation algorithm. assert len(sin) == 11 - assert sin.replace(' ','').isdigit() + assert sin.replace(' ', '').isdigit() assert ca_checksum(sin) == int(sin[-1]) + +class TestEnUS(unittest.TestCase): + def setUp(self): + self.factory = Faker('en_US') + self.factory.seed(0) + + def test_ssn(self): + for _ in range(100): + ssn = self.factory.ssn(taxpayer_identification_number_type='SSN') + + # Ensure that generated SINs are 11 characters long + # including dashes, consist of dashes and digits only, and + # satisfy these requirements: + # + # An United States Social Security Number + # (SSN) is a tax processing number issued by the Internal + # Revenue Service with the format "AAA-GG-SSSS". The + # number is divided into three parts: the first three + # digits, known as the area number because they were + # formerly assigned by geographical region; the middle two + # digits, known as the group number; and the final four + # digits, known as the serial number. SSNs with the + # following characteristics are not allocated: + # + # 1) Numbers with all zeros in any digit group + # (000-##-####, ###-00-####, ###-##-0000). + # + # 2) Numbers with 666 or 900-999 in the first digit group. + # + # https://en.wikipedia.org/wiki/Social_Security_number + + assert len(ssn) == 11 + assert ssn.replace('-', '').isdigit() + + [area, group, serial] = ssn.split('-') + + assert 1 <= int(area) <= 899 and int(area) != 666 + assert 1 <= int(group) <= 99 + assert 1 <= int(serial) <= 9999 + assert area != '666' + + def test_prohibited_ssn_value(self): + # 666 is a prohibited value. The magic number selected as a seed + # is one that would (if not specifically checked for) return an + # SSN with an area of '666'. + + self.factory.seed(19031) + ssn = self.factory.ssn() + [area, group, serial] = ssn.split('-') + assert area != '666' + + def test_itin(self): + for _ in range(100): + itin = self.factory.ssn(taxpayer_identification_number_type='ITIN') + + # Ensure that generated SINs are 11 characters long + # including dashes, consist of dashes and digits only, and + # satisfy these requirements: + # + # An United States Individual Taxpayer Identification Number + # (ITIN) is a tax processing number issued by the Internal + # Revenue Service. It is a nine-digit number that always begins + # with the number 9 and has a range of 70-88 in the fourth and + # fifth digit. Effective April 12, 2011, the range was extended + # to include 900-70-0000 through 999-88-9999, 900-90-0000 + # through 999-92-9999 and 900-94-0000 through 999-99-9999. + # https://www.irs.gov/individuals/international-taxpayers/general-itin-information + + assert len(itin) == 11 + assert itin.replace('-', '').isdigit() + + [area, group, serial] = itin.split('-') + + assert 900 <= int(area) <= 999 + assert 70 <= int(group) <= 88 or 90 <= int(group) <= 92 or 94 <= int(group) <= 99 + assert 0 <= int(serial) <= 9999 + + def test_ein(self): + ein_prefix_choices = [ + '01', + '02', + '03', + '04', + '05', + '06', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '20', + '21', + '22', + '23', + '24', + '25', + '26', + '27', + '30', + '31', + '32', + '33', + '34', + '35', + '36', + '37', + '38', + '39', + '40', + '41', + '42', + '43', + '44', + '45', + '46', + '47', + '48', + '50', + '51', + '52', + '53', + '54', + '55', + '56', + '57', + '58', + '59', + '60', + '61', + '62', + '63', + '64', + '65', + '66', + '67', + '68', + '71', + '72', + '73', + '74', + '75', + '76', + '77', + '80', + '81', + '82', + '83', + '84', + '85', + '86', + '87', + '88', + '90', + '91', + '92', + '93', + '94', + '95', + '98', + '99'] + + for _ in range(100): + ein = self.factory.ssn(taxpayer_identification_number_type='EIN') + + # An United States An Employer Identification Number (EIN) is + # also known as a Federal Tax Identification Number, and is + # used to identify a business entity. EINs follow a format of a + # two-digit prefix followed by a hyphen and a seven-digit sequence. + # https://www.irs.gov/businesses/small-businesses-self-employed/employer-id-numbers + # + # Ensure that generated EINs are 10 characters long + # including a dash, consist of dashes and digits only, and + # satisfy these requirements: + # + # There are only certain EIN Prefix values assigned: + # https://www.irs.gov/businesses/small-businesses-self-employed/how-eins-are-assigned-and-valid-ein-prefixes + + assert len(ein) == 10 + assert ein.replace('-', '').isdigit() + + [prefix, sequence] = ein.split('-') + + assert prefix in ein_prefix_choices + assert 0 <= int(sequence) <= 9999999 + + def test_bad_tin_type(self): + with self.assertRaises(ValueError): + self.factory.ssn(taxpayer_identification_number_type='badValue') + + def test_wrong_tin_type_case(self): + with self.assertRaises(ValueError): + self.factory.ssn(taxpayer_identification_number_type='ssn') + + class TestEtEE(unittest.TestCase): """ Tests SSN in the et_EE locale """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tests/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 dnspython==2.2.1 email-validator==1.0.3 execnet==1.9.0 -e git+https://github.com/joke2k/faker.git@da96379c07dbd22bea070db5a8a3e1ad85e4cf04#egg=Faker idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 mock==2.0.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 six==1.17.0 text-unidecode==1.2 tomli==1.2.3 typing_extensions==4.1.1 UkPostcodeParser==1.1.2 zipp==3.6.0
name: faker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - dnspython==2.2.1 - email-validator==1.0.3 - execnet==1.9.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==2.0.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - six==1.17.0 - text-unidecode==1.2 - tomli==1.2.3 - typing-extensions==4.1.1 - ukpostcodeparser==1.1.2 - zipp==3.6.0 prefix: /opt/conda/envs/faker
[ "tests/providers/test_ssn.py::TestEnUS::test_bad_tin_type", "tests/providers/test_ssn.py::TestEnUS::test_ein", "tests/providers/test_ssn.py::TestEnUS::test_itin", "tests/providers/test_ssn.py::TestEnUS::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_wrong_tin_type_case" ]
[]
[ "tests/providers/test_ssn.py::TestEnCA::test_ssn", "tests/providers/test_ssn.py::TestEnUS::test_prohibited_ssn_value", "tests/providers/test_ssn.py::TestEtEE::test_ssn", "tests/providers/test_ssn.py::TestEtEE::test_ssn_checksum", "tests/providers/test_ssn.py::TestFiFI::test_artifical_ssn", "tests/providers/test_ssn.py::TestFiFI::test_century_code", "tests/providers/test_ssn.py::TestFiFI::test_ssn_sanity", "tests/providers/test_ssn.py::TestFiFI::test_valid_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn", "tests/providers/test_ssn.py::TestHrHR::test_ssn_checksum", "tests/providers/test_ssn.py::TestHuHU::test_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_cpf", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn", "tests/providers/test_ssn.py::TestPtBR::test_pt_BR_ssn_checksum", "tests/providers/test_ssn.py::TestPlPL::test_calculate_month", "tests/providers/test_ssn.py::TestPlPL::test_ssn", "tests/providers/test_ssn.py::TestPlPL::test_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_checksum", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_gender_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_dob_passed", "tests/providers/test_ssn.py::TestNoNO::test_no_NO_ssn_invalid_gender_passed" ]
[]
MIT License
2,669
1,760
[ "faker/providers/ssn/en_US/__init__.py" ]
elastic__rally-526
085e3d482717d88dfc2d41aa34502eb108abbfe9
2018-06-18 12:07:22
085e3d482717d88dfc2d41aa34502eb108abbfe9
diff --git a/esrally/mechanic/supplier.py b/esrally/mechanic/supplier.py index fa001711..a59d640f 100644 --- a/esrally/mechanic/supplier.py +++ b/esrally/mechanic/supplier.py @@ -293,8 +293,8 @@ class ElasticsearchDistributionSupplier: def fetch(self): io.ensure_dir(self.distributions_root) - distribution_path = "%s/elasticsearch-%s.tar.gz" % (self.distributions_root, self.version) download_url = self.repo.download_url + distribution_path = os.path.join(self.distributions_root, self.repo.file_name) self.logger.info("Resolved download URL [%s] for version [%s]", download_url, self.version) if not os.path.isfile(distribution_path) or not self.repo.cache: try: @@ -487,6 +487,11 @@ class DistributionRepository: override_key = "{}.url".format(self.name) return self._url_for(override_key, default_key) + @property + def file_name(self): + url = self.download_url + return url[url.rfind("/") + 1:] + def plugin_download_url(self, plugin_name): # team repo default_key = "plugin_{}_{}_url".format(plugin_name, self.name)
Rally cannot differentiate between default and OSS distribution after download **Rally version** (get with `esrally --version`): all versions **Description of the problem including expected versus actual behavior**: When we run a benchmark first with the OSS distribution and then one with the default one, Rally raises the following error: ``` FileNotFoundError: [Errno 2] No such file or directory: '/home/user/.rally/benchmarks/races/2018-06-18-05-44-23/rally-node-0/install/elasticsearch-6.3.0/bin/elasticsearch-certgen' ``` **Steps to reproduce**: 1. Ensure that `~/.rally/benchmarks/distributions/` is empty 2. Run one benchmark with the OSS distribution: ``` esrally --test-mode --distribution-version=6.3.0 --car="defaults" ``` 3. Run one benchmark with the default distribution and enable X-Pack Security: ``` esrally --test-mode --distribution-version=6.3.0 --car="defaults,x-pack-security" --client-options="basic_auth_user:'rally',basic_auth_password:'rally-password',use_ssl:true,verify_certs:false,timeout:60,request_timeout:60" ```
elastic/rally
diff --git a/tests/mechanic/supplier_test.py b/tests/mechanic/supplier_test.py index cbd5dbe6..af16e456 100644 --- a/tests/mechanic/supplier_test.py +++ b/tests/mechanic/supplier_test.py @@ -512,6 +512,7 @@ class DistributionRepositoryTests(TestCase): "release.cache": "true" }, version="5.5.0") self.assertEqual("https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.5.0.tar.gz", repo.download_url) + self.assertEqual("elasticsearch-5.5.0.tar.gz", repo.file_name) self.assertTrue(repo.cache) def test_release_repo_config_with_user_url(self): @@ -522,6 +523,7 @@ class DistributionRepositoryTests(TestCase): "release.cache": "false" }, version="2.4.3") self.assertEqual("https://es-mirror.example.org/downloads/elasticsearch/elasticsearch-2.4.3.tar.gz", repo.download_url) + self.assertEqual("elasticsearch-2.4.3.tar.gz", repo.file_name) self.assertFalse(repo.cache) def test_missing_url(self):
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@085e3d482717d88dfc2d41aa34502eb108abbfe9#egg=esrally importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==2.0.1 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==5.4.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work py-cpuinfo==3.2.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-benchmark==3.4.1 tabulate==0.8.1 thespian==3.9.2 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.22 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - elasticsearch==6.2.0 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==2.0.1 - psutil==5.4.0 - py-cpuinfo==3.2.0 - pytest-benchmark==3.4.1 - tabulate==0.8.1 - thespian==3.9.2 - urllib3==1.22 prefix: /opt/conda/envs/rally
[ "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_release_repo_config_with_default_url", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_release_repo_config_with_user_url" ]
[]
[ "tests/mechanic/supplier_test.py::RevisionExtractorTests::test_invalid_revisions", "tests/mechanic/supplier_test.py::RevisionExtractorTests::test_multiple_revisions", "tests/mechanic/supplier_test.py::RevisionExtractorTests::test_single_revision", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_checkout_current", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_checkout_revision", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_checkout_revision_for_local_only_repo", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_checkout_ts", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_intial_checkout_latest", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_is_commit_hash", "tests/mechanic/supplier_test.py::SourceRepositoryTests::test_is_not_commit_hash", "tests/mechanic/supplier_test.py::BuilderTests::test_build_on_jdk_10", "tests/mechanic/supplier_test.py::BuilderTests::test_build_on_jdk_8", "tests/mechanic/supplier_test.py::ElasticsearchSourceSupplierTests::test_add_elasticsearch_binary", "tests/mechanic/supplier_test.py::ElasticsearchSourceSupplierTests::test_build", "tests/mechanic/supplier_test.py::ElasticsearchSourceSupplierTests::test_no_build", "tests/mechanic/supplier_test.py::ElasticsearchSourceSupplierTests::test_raises_error_on_missing_car_variable", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_add_binary_built_along_elasticsearch", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_along_es_plugin_keeps_build_dir", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_invalid_config_duplicate_source", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_invalid_config_no_source", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_resolve_plugin_binary_built_standalone", "tests/mechanic/supplier_test.py::ExternalPluginSourceSupplierTests::test_standalone_plugin_overrides_build_dir", "tests/mechanic/supplier_test.py::CorePluginSourceSupplierTests::test_resolve_plugin_binary", "tests/mechanic/supplier_test.py::PluginDistributionSupplierTests::test_resolve_plugin_url", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_create_suppliers_for_es_and_plugin_source_build", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_create_suppliers_for_es_distribution_plugin_source_build", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_create_suppliers_for_es_distribution_plugin_source_skip", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_create_suppliers_for_es_missing_distribution_plugin_source_skip", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_create_suppliers_for_es_only_config", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_and_plugin_source_build", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_distribution", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_distribution_and_plugin_source_build", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_distribution_and_plugin_source_skip", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_source_build", "tests/mechanic/supplier_test.py::CreateSupplierTests::test_derive_supply_requirements_es_source_skip", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_invalid_cache_value", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_missing_cache", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_missing_plugin_config", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_missing_url", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_plugin_config_with_default_url", "tests/mechanic/supplier_test.py::DistributionRepositoryTests::test_plugin_config_with_user_url" ]
[]
Apache License 2.0
2,679
310
[ "esrally/mechanic/supplier.py" ]
pysmt__pysmt-502
b0324e68bee72c862db9620206a34f2e20c38160
2018-06-22 15:19:32
b0324e68bee72c862db9620206a34f2e20c38160
diff --git a/pysmt/smtlib/parser/parser.py b/pysmt/smtlib/parser/parser.py index bf093d6..abbca6e 100644 --- a/pysmt/smtlib/parser/parser.py +++ b/pysmt/smtlib/parser/parser.py @@ -876,7 +876,6 @@ class SmtLibParser(object): "command." % command, tokens.pos_info) res.append(current) - for _ in xrange(min_size, max_size + 1): current = tokens.consume() if current == ")": @@ -1170,16 +1169,18 @@ class SmtLibParser(object): var = self.parse_atom(tokens, current) namedparams = self.parse_named_params(tokens, current) rtype = self.parse_type(tokens, current) - + bindings = [] for (x,t) in namedparams: - v = self._get_var(x, t) + v = self.env.formula_manager.FreshSymbol(typename=t, + template="__"+x+"%d") self.cache.bind(x, v) - formal.append(v) + formal.append(v) #remember the variable + bindings.append(x) #remember the name # Parse expression using also parameters ebody = self.get_expression(tokens) - # Discard parameters - for x in formal: - self.cache.unbind(x.symbol_name()) + #Discard parameters + for x in bindings: + self.cache.unbind(x) # Finish Parsing self.consume_closing(tokens, current) self.cache.define(var, formal, ebody)
PysmtTypeError when reusing symbols in SMT-LIB define-fun In the following SMT-LIB definitions, I am using `n` as an Int parameter for `f` and as a Real parameter for `g`: ``` (define-fun f ((n Int)) Int n) (define-fun g ((n Real)) Real n) ``` This yields PysmtTypeError, saying: `Trying to redefine symbol 'n' with a new type. Previous type was 'Int' new type is 'Real'`. This should not happen - according to the [standard](http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf) (p. 62), `(define-fun f ((n Int)) n)` is equivalent to: ``` (declare-fun f ((n Int) n) (assert (forall ((n Int)) (= (f n) n))) ``` And so there shouldn't be a problem re-using n. To reproduce: `python tmp.py` for `tmp.py` with the following content: ``` from pysmt.smtlib.parser import SmtLibParser import os def main(): smtlib_script = '\n'.join(['(define-fun f ((n Int)) Int n)', '(define-fun g ((n Real)) Real n)']) tmp_file_name = "tmp.smt2" tmp_file = open(tmp_file_name, 'w') tmp_file.write(smtlib_script) tmp_file.close() parser = SmtLibParser() script = parser.get_script_fname(tmp_file_name) os.remove(tmp_file_name) if __name__ == "__main__": main() ```
pysmt/pysmt
diff --git a/pysmt/test/smtlib/test_smtlibscript.py b/pysmt/test/smtlib/test_smtlibscript.py index 2f97538..bcb66cf 100644 --- a/pysmt/test/smtlib/test_smtlibscript.py +++ b/pysmt/test/smtlib/test_smtlibscript.py @@ -16,7 +16,6 @@ # limitations under the License. # from six.moves import cStringIO - import pysmt.smtlib.commands as smtcmd from pysmt.shortcuts import And, Or, Symbol, GT, Real, Not from pysmt.typing import REAL @@ -122,6 +121,19 @@ class TestSmtLibScript(TestCase): f = get_formula_strict(stream_in) + #n is defined once as an Int and once as a Real + def test_define_funs_same_args(self): + smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(define-fun f ((n Real)) Real n)']) + stream = cStringIO(smtlib_script) + parser = SmtLibParser() + script = parser.get_script(stream) + + def test_define_funs_arg_and_fun(self): + smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(declare-fun n () Real)']) + stream = cStringIO(smtlib_script) + parser = SmtLibParser() + script = parser.get_script(stream) + def test_evaluate_command(self): class SmtLibIgnore(SmtLibIgnoreMixin): pass @@ -207,6 +219,12 @@ DEMO_SMTSCRIPT = [ "(declare-fun a () Bool)", "(define-sort G (H) (F Int H))", "(define-fun f ((a Bool)) B a)", "(define-fun g ((a Bool)) B (f a))", + "(define-fun h ((a Int)) Int a)", + "(declare-const x Bool)", + "(declare-const y Int)", + "(assert (= (h y) y))", + "(assert (= (f x) x))", + "(check-sat)", "(define-fun-rec f ((a A)) B a)", "(define-fun-rec g ((a A)) B (g a))", """(define-funs-rec ((h ((a A)) B) (i ((a A)) B) ) diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py index a33c576..da2f2b6 100644 --- a/pysmt/test/test_regressions.py +++ b/pysmt/test/test_regressions.py @@ -393,7 +393,7 @@ class TestRegressions(TestCase): s = parser.get_script(buffer_) for c in s: res = c.serialize_to_string(daggify=False) - self.assertEqual(res, smtlib_input) + self.assertEqual(res.replace('__x0', 'x'), smtlib_input) @skipIfSolverNotAvailable("z3") def test_z3_nary_back(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/pysmt/pysmt.git@b0324e68bee72c862db9620206a34f2e20c38160#egg=PySMT pytest==8.3.5 six==1.17.0 tomli==2.2.1
name: pysmt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/pysmt
[ "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_all_parsing" ]
[ "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_define_funs_arg_and_fun", "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_define_funs_same_args", "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_get_strict_formula", "pysmt/test/test_regressions.py::TestRegressions::test_parse_bvconst_width", "pysmt/test/test_regressions.py::TestRegressions::test_parse_bvx_var", "pysmt/test/test_regressions.py::TestRegressions::test_parse_declare_const", "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun", "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun_bind", "pysmt/test/test_regressions.py::TestRegressions::test_smtlib_define_fun_serialization", "pysmt/test/test_regressions.py::TestRegressions::test_string_constant_quote_escaping_parsing" ]
[ "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_basic_operations", "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_evaluate_command", "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_from_formula", "pysmt/test/smtlib/test_smtlibscript.py::TestSmtLibScript::test_smtlibignore_mixin", "pysmt/test/test_regressions.py::TestRegressions::test_array_initialization_printing", "pysmt/test/test_regressions.py::TestRegressions::test_cnf_as_set", "pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal", "pysmt/test/test_regressions.py::TestRegressions::test_determinism", "pysmt/test/test_regressions.py::TestRegressions::test_empty_string_symbol", "pysmt/test/test_regressions.py::TestRegressions::test_equality_typing", "pysmt/test/test_regressions.py::TestRegressions::test_exactly_one_unpacking", "pysmt/test/test_regressions.py::TestRegressions::test_exactlyone_w_generator", "pysmt/test/test_regressions.py::TestRegressions::test_git_version", "pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le", "pysmt/test/test_regressions.py::TestRegressions::test_is_one", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_declaration_w_same_functiontype", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_exit", "pysmt/test/test_regressions.py::TestRegressions::test_parse_exception", "pysmt/test/test_regressions.py::TestRegressions::test_qf_bool_smt2", "pysmt/test/test_regressions.py::TestRegressions::test_simplify_times", "pysmt/test/test_regressions.py::TestRegressions::test_simplifying_int_plus_changes_type_of_expression", "pysmt/test/test_regressions.py::TestRegressions::test_smtlib_info_quoting", "pysmt/test/test_regressions.py::TestRegressions::test_string_constant_quote_escaping_hr_printer", "pysmt/test/test_regressions.py::TestRegressions::test_string_constant_quote_escaping_smtlib_printer", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_to_real" ]
[]
Apache License 2.0
2,692
367
[ "pysmt/smtlib/parser/parser.py" ]
pennmem__cmlreaders-79
93f826340ac27413c13d0151b1297d8c0a344b92
2018-06-25 15:58:17
93f826340ac27413c13d0151b1297d8c0a344b92
diff --git a/cmlreaders/base_reader.py b/cmlreaders/base_reader.py index 37ef9ea..06e3f98 100644 --- a/cmlreaders/base_reader.py +++ b/cmlreaders/base_reader.py @@ -1,4 +1,5 @@ -from typing import Optional +from pathlib import Path +from typing import Optional, Union from .path_finder import PathFinder from .exc import UnsupportedOutputFormat, ImproperlyDefinedReader @@ -72,6 +73,22 @@ class BaseCMLReader(object, metaclass=_MetaReader): self.data_type = data_type self.rootdir = rootdir + @classmethod + def fromfile(cls, path: Union[str, Path]): + """Directly load data from a file using the default representation. + This is equivalent to creating a reader with the ``file_path`` keyword + argument given but without the need to then call ``load`` or specify + other, unnecessary arguments. + + Parameters + ---------- + path + Path to the file to load. + + """ + reader = cls("", "", "", -1, file_path=str(path)) + return reader.load() + def load(self): """ Load data into memory """ method_name = "_".join(["as", self.default_representation]) diff --git a/cmlreaders/readers/electrodes.py b/cmlreaders/readers/electrodes.py index 4d4c4c4..9c0f245 100644 --- a/cmlreaders/readers/electrodes.py +++ b/cmlreaders/readers/electrodes.py @@ -1,4 +1,5 @@ import json +import os.path from typing import List import pandas as pd @@ -31,7 +32,17 @@ class MontageReader(BaseCMLReader): from multiprocessing import cpu_count with open(self._file_path) as f: - data = json.load(f)[self.subject][self.data_type] + raw = json.load(f) + + # we're using fromfile, so we need to infer subject/data_type + if not len(self.data_type): + self.subject = list(raw.keys())[0] + self.data_type = ( + "contacts" if "contacts" in os.path.basename(self._file_path) + else "pairs" + ) + + data = raw[self.subject][self.data_type] labels = [l for l in data]
Improve usability of specific readers Generally, we want to use `CMLReader` to interact with specific readers indirectly. But there are some use cases where other readers are useful, such as the one for reading Ramulator event log files (this is helpful for me when analyzing output from tests). At present, it's a bit awkward to use: ```python reader = RamulatorEventLogReader("experiment_log", "fake subject", "fake experiment", 0, file_path="event_log.json") events = reader.as_dataframe() ``` All that I *really* need to pass in this case is that path to the file, but the constructor requires subject, experiment, and session. I propose we add a new class method which works like this: ```python events = RamulatorEventLogReader.fromfile("event_log.json") ``` This has the advantage of not making the constructor overly complicated (e.g., arguments are optional if `file_path` is not specified, otherwise they are required).
pennmem/cmlreaders
diff --git a/cmlreaders/test/test_readers.py b/cmlreaders/test/test_readers.py index 5895cb4..826b4ab 100644 --- a/cmlreaders/test/test_readers.py +++ b/cmlreaders/test/test_readers.py @@ -379,3 +379,14 @@ class TestClassifierContainerReader: callable_method(exp_output, overwrite=True) assert os.path.exists(exp_output) os.remove(exp_output) + + [email protected]("cls,path,dtype", [ + (ElectrodeCategoriesReader, datafile("electrode_categories.txt"), dict), + (MontageReader, datafile("pairs.json"), pd.DataFrame), + (MontageReader, datafile("contacts.json"), pd.DataFrame), + (RamulatorEventLogReader, datafile("event_log.json"), pd.DataFrame), +]) +def test_fromfile(cls, path, dtype): + data = cls.fromfile(path) + assert isinstance(data, dtype)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@93f826340ac27413c13d0151b1297d8c0a344b92#egg=cmlreaders codecov==2.1.13 coverage==6.2 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 MarkupSafe==2.0.1 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - markupsafe==2.0.1 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_readers.py::test_fromfile[ElectrodeCategoriesReader-/cmlreaders/cmlreaders/test/data/electrode_categories.txt-dict]", "cmlreaders/test/test_readers.py::test_fromfile[MontageReader-/cmlreaders/cmlreaders/test/data/pairs.json-DataFrame]", "cmlreaders/test/test_readers.py::test_fromfile[MontageReader-/cmlreaders/cmlreaders/test/data/contacts.json-DataFrame]", "cmlreaders/test/test_readers.py::test_fromfile[RamulatorEventLogReader-/cmlreaders/cmlreaders/test/data/event_log.json-DataFrame]" ]
[ "cmlreaders/test/test_readers.py::TestElectrodeCategoriesReader::test_load[R1111M-lens0]", "cmlreaders/test/test_readers.py::TestElectrodeCategoriesReader::test_load[R1052E-lens1]", "cmlreaders/test/test_readers.py::TestBaseReportDataReader::test_as_methods[R1409D-catFR1-1-classifier_summary-pyobject]", "cmlreaders/test/test_readers.py::TestBaseReportDataReader::test_as_methods[R1409D-catFR1-1-classifier_summary-dataframe]", "cmlreaders/test/test_readers.py::TestBaseReportDataReader::test_as_methods[R1409D-catFR1-1-classifier_summary-dict]", "cmlreaders/test/test_readers.py::TestBaseReportDataReader::test_as_methods[R1409D-catFR1-1-classifier_summary-recarray]", "cmlreaders/test/test_readers.py::TestBaseReportDataReader::test_to_methods[classifier_summary-hdf]", "cmlreaders/test/test_readers.py::TestReportSummaryReader::test_as_methods[session_summary-pyobject]", "cmlreaders/test/test_readers.py::TestReportSummaryReader::test_as_methods[session_summary-dataframe]", "cmlreaders/test/test_readers.py::TestReportSummaryReader::test_as_methods[session_summary-recarray]", "cmlreaders/test/test_readers.py::TestReportSummaryReader::test_as_methods[session_summary-dict]", "cmlreaders/test/test_readers.py::TestReportSummaryReader::test_load_nonstim_session", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_as_methods[baseline_classifier-pyobject]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_as_methods[used_classifier-pyobject]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_to_methods[baseline_classifier-binary]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_to_methods[used_classifier-binary]" ]
[ "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_read_jacksheet", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-voxel_coordinates-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-voxel_coordinates-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-classifier_excluded_leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-classifier_excluded_leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-good_leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-good_leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-jacksheet-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-jacksheet-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-area-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-area-csv]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-electrode_coordinates-dataframe]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-electrode_coordinates-recarray]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-electrode_coordinates-dict]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-prior_stim_results-dataframe]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-prior_stim_results-recarray]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-prior_stim_results-dict]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-target_selection_table-dataframe]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-target_selection_table-recarray]", "cmlreaders/test/test_readers.py::TestCSVReader::test_as_methods[R1409D-0-target_selection_table-dict]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-electrode_coordinates-json]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-electrode_coordinates-csv]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-prior_stim_results-json]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-prior_stim_results-csv]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-target_selection_table-json]", "cmlreaders/test/test_readers.py::TestCSVReader::test_to_methods[R1409D-0-target_selection_table-csv]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-dataframe]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-recarray]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-dict]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_to_methods[R1409D-catFR1-1-event_log-json]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_to_methods[R1409D-catFR1-1-event_log-csv]", "cmlreaders/test/test_readers.py::TestBasicJSONReader::test_load", "cmlreaders/test/test_readers.py::TestEEGMetaReader::test_load", "cmlreaders/test/test_readers.py::TestEventReader::test_load", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[contacts]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[pairs]", "cmlreaders/test/test_readers.py::TestLocalizationReader::test_load" ]
[]
null
2,703
575
[ "cmlreaders/base_reader.py", "cmlreaders/readers/electrodes.py" ]
ucfopen__canvasapi-191
141962439d0a22318c1ae339fbf0e71a725d51a9
2018-06-25 16:23:33
4b14ed0ad55ff1e729ecfb678b40f3a0306c2a83
diff --git a/canvasapi/canvas.py b/canvasapi/canvas.py index ca9a6e8..2e684fa 100644 --- a/canvasapi/canvas.py +++ b/canvasapi/canvas.py @@ -39,6 +39,13 @@ class Canvas(object): "Rewriting `base_url` to {}".format(new_url), DeprecationWarning ) + + if 'http://' in base_url: + warnings.warn( + "Canvas may respond unexpectedly when making requests to HTTP " + "URLs. If possible, please use HTTPS.", + UserWarning + ) base_url = new_url + '/api/v1/' self.__requester = Requester(base_url, access_token)
Warn users that POST requests sent over non-HTTPS may fail In some cases, Canvas's API responds unpredictably when sending POST requests over HTTP instead of HTTPS. For example, the `account.create_course` call will return the `GET` response if made over HTTP instead of HTTPS. This breaks `CanvasObject`'s attempts to automatically create an object: ``` >>> a.create_course(course={'name': 'JSA_TST1337_Jesse_McBride'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/canvasapi/account.py", line 77, in create_course return Course(self._requester, response.json()) File "/usr/local/lib/python2.7/site-packages/canvasapi/canvas_object.py", line 28, in __init__ self.set_attributes(attributes) File "/usr/local/lib/python2.7/site-packages/canvasapi/canvas_object.py", line 68, in set_attributes for attribute, value in attributes.items(): AttributeError: 'list' object has no attribute 'items' ``` It seems wrong to stop users at every POST call if they've set their `CANVAS_URL` to `http://*`. Instead, I think we should hook into `Requester._post_request` and raise a warning that the API call may not succeed.
ucfopen/canvasapi
diff --git a/tests/fixtures/account.json b/tests/fixtures/account.json index c2675e0..b0a7a13 100644 --- a/tests/fixtures/account.json +++ b/tests/fixtures/account.json @@ -204,7 +204,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/courses?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/courses?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -259,7 +259,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/external_tools?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/external_tools?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -319,7 +319,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/accounts/1/groups?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/groups?page=2&per_page=2>; rel=\"next\"" } }, "get_groups_context2": { @@ -403,7 +403,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/reports?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/reports?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -434,7 +434,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/reports/sis_export_csv?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/reports/sis_export_csv?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -467,7 +467,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/sub_accounts?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/sub_accounts?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -510,7 +510,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/users?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/users?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -543,7 +543,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/users/1/account_notifications?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/users/1/account_notifications?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -644,7 +644,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/roles/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/roles/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -720,7 +720,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/logins/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/logins/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -957,7 +957,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/authentication_providers/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/authentication_providers/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/fixtures/assignment.json b/tests/fixtures/assignment.json index aec1393..0e2f6ba 100644 --- a/tests/fixtures/assignment.json +++ b/tests/fixtures/assignment.json @@ -80,7 +80,7 @@ "id": 1, "assignment_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload" }, "status_code": 200 diff --git a/tests/fixtures/authentication_providers.json b/tests/fixtures/authentication_providers.json index 446fae1..9daf87b 100644 --- a/tests/fixtures/authentication_providers.json +++ b/tests/fixtures/authentication_providers.json @@ -15,7 +15,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/authentication_providers/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/authentication_providers/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/fixtures/conversation.json b/tests/fixtures/conversation.json index 3c1bc71..8fe3902 100644 --- a/tests/fixtures/conversation.json +++ b/tests/fixtures/conversation.json @@ -32,7 +32,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/conversations?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/conversations?page=2&per_page=2>; rel=\"next\"" } }, "get_conversations_2": { diff --git a/tests/fixtures/course.json b/tests/fixtures/course.json index 2c97bd4..da52dd4 100644 --- a/tests/fixtures/course.json +++ b/tests/fixtures/course.json @@ -13,7 +13,7 @@ "data": { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, "status_code": 200 }, @@ -62,7 +62,7 @@ "data": { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, "status_code": 200 }, @@ -96,7 +96,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/list_assignments?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/list_assignments?page=2&per_page=2>; rel=\"next\"" } }, "get_all_assignments2": { @@ -199,7 +199,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/1/external_tools?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/external_tools?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -262,7 +262,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/1/recent_students?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/recent_students?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -351,7 +351,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/1/sections?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/sections?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -405,7 +405,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/1/search_users?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/search_users?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -443,7 +443,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" } }, "list_enrollments_2": { @@ -472,12 +472,12 @@ { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, { "id": 2, "display_name": "My Blog 2", - "url": "http://example.com/myblog2.rss" + "url": "https://example.com/myblog2.rss" } ], "status_code": 200 @@ -490,18 +490,18 @@ "id": 1, "size": 2939, "display_name": "File1.txt", - "url": "http://example.com/file_download" + "url": "https://example.com/file_download" }, { "id": 2, "size": 18380, "display_name": "File_2.png", - "url": "http://example.com/file_download2" + "url": "https://example.com/file_download2" } ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/files?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/files?page=2&per_page=2>; rel=\"next\"" } }, "list_course_files2": { @@ -512,13 +512,13 @@ "id": 3, "display_name": "File 3.jpg", "size": 1298, - "url": "http://example.com/file_download3" + "url": "https://example.com/file_download3" }, { "id": 4, "display_name": "File 4.docx", "size": 88920, - "url": "http://example.com/file_download4" + "url": "https://example.com/file_download4" } ], "status_code": 200 @@ -559,7 +559,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/list_quizzes?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/list_quizzes?page=2&per_page=2>; rel=\"next\"" } }, "list_quizzes2": { @@ -603,7 +603,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -741,14 +741,14 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/list_modules?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/list_modules?page=2&per_page=2>; rel=\"next\"" } }, "upload": { "method": "POST", "endpoint": "courses/1/files", "data": { - "upload_url": "http://example.com/api/v1/files/upload_response_upload_url", + "upload_url": "https://example.com/api/v1/files/upload_response_upload_url", "upload_params": { "some_param": "param123", "a_different_param": "param456" @@ -838,7 +838,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/get_pages?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/get_pages?page=2&per_page=2>; rel=\"next\"" } }, "get_pages2": { @@ -922,7 +922,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/groups?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/groups?page=2&per_page=2>; rel=\"next\"" } }, "list_groups_context2": { @@ -1259,14 +1259,14 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload" }, { "id": 2, "assignments_id": 1, "user_id": 2, - "html_url": "http://example.com/courses/1/assignments/1/submissions/2", + "html_url": "https://example.com/courses/1/assignments/1/submissions/2", "submission_type": "online_upload" } ], @@ -1307,7 +1307,7 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload", "excused": true }, diff --git a/tests/fixtures/current_user.json b/tests/fixtures/current_user.json index 1bc6111..ff86ca8 100644 --- a/tests/fixtures/current_user.json +++ b/tests/fixtures/current_user.json @@ -23,7 +23,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/self/groups?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/self/groups?page=2&per_page=2>; rel=\"next\"" } }, "list_groups2": { diff --git a/tests/fixtures/external_tool.json b/tests/fixtures/external_tool.json index 1912a62..76d8ac5 100644 --- a/tests/fixtures/external_tool.json +++ b/tests/fixtures/external_tool.json @@ -95,7 +95,7 @@ "data": { "id": "1", "name": "External Tool #1 (Course)", - "url": "http://example.com/courses/1/external_tools/sessionless_launch/?verifier=1337" + "url": "https://example.com/courses/1/external_tools/sessionless_launch/?verifier=1337" }, "status_code": 200 }, diff --git a/tests/fixtures/folder.json b/tests/fixtures/folder.json index b7c2b00..7d015a0 100644 --- a/tests/fixtures/folder.json +++ b/tests/fixtures/folder.json @@ -39,7 +39,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/folders/1/files?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/folders/1/files?page=2&per_page=2>; rel=\"next\"" } }, "list_folder_files2": { diff --git a/tests/fixtures/group.json b/tests/fixtures/group.json index 27d2abd..6f08d97 100644 --- a/tests/fixtures/group.json +++ b/tests/fixtures/group.json @@ -108,7 +108,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/groups/1/get_pages?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/groups/1/get_pages?page=2&per_page=2>; rel=\"next\"" } }, "get_pages2": { @@ -185,7 +185,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/groups/1/users?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/groups/1/users?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -208,7 +208,7 @@ "method": "POST", "endpoint": "groups/1/files", "data": { - "upload_url": "http://example.com/api/v1/files/upload_response_upload_url", + "upload_url": "https://example.com/api/v1/files/upload_response_upload_url", "upload_params": { "some_param": "param123", "a_different_param": "param456" @@ -271,7 +271,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/groups/1/memberships?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/groups/1/memberships?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -685,7 +685,7 @@ "data": { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, "status_code": 200 }, @@ -696,12 +696,12 @@ { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, { "id": 2, "display_name": "My Blog 2", - "url": "http://example.com/myblog2.rss" + "url": "https://example.com/myblog2.rss" } ], "status_code": 200 @@ -712,7 +712,7 @@ "data": { "id": 1, "display_name": "My Blog", - "url": "http://example.com/myblog.rss" + "url": "https://example.com/myblog.rss" }, "status_code": 200 }, @@ -733,7 +733,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/groups/1/files?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/groups/1/files?page=2&per_page=2>; rel=\"next\"" } }, "list_group_files2": { diff --git a/tests/fixtures/login.json b/tests/fixtures/login.json index 3e572bd..8942470 100644 --- a/tests/fixtures/login.json +++ b/tests/fixtures/login.json @@ -22,7 +22,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/logins/?page=2&per_page=1>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/logins/?page=2&per_page=1>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/fixtures/module.json b/tests/fixtures/module.json index 9369b5a..c7da4c2 100644 --- a/tests/fixtures/module.json +++ b/tests/fixtures/module.json @@ -52,7 +52,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/modules/1/items/list_module_items?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/modules/1/items/list_module_items?page=2&per_page=2>; rel=\"next\"" } }, "list_module_items2": { diff --git a/tests/fixtures/outcome.json b/tests/fixtures/outcome.json index 139d684..25a3444 100644 --- a/tests/fixtures/outcome.json +++ b/tests/fixtures/outcome.json @@ -69,7 +69,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/accounts/1/outcome_groups?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/accounts/1/outcome_groups?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -259,7 +259,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/courses/1/outcome_groups?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/outcome_groups?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/fixtures/page.json b/tests/fixtures/page.json index c09d753..dac500f 100644 --- a/tests/fixtures/page.json +++ b/tests/fixtures/page.json @@ -44,7 +44,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/courses/1/pages/my-url/revisions?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/courses/1/pages/my-url/revisions?page=2&per_page=2>; rel=\"next\"" } }, "list_revisions2": { diff --git a/tests/fixtures/paginated_list.json b/tests/fixtures/paginated_list.json index 904906d..e37006f 100644 --- a/tests/fixtures/paginated_list.json +++ b/tests/fixtures/paginated_list.json @@ -45,7 +45,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/four_objects_two_pages?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/four_objects_two_pages?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -78,7 +78,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/six_objects_three_pages?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/six_objects_three_pages?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -96,7 +96,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/six_objects_three_pages?page=3&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/six_objects_three_pages?page=3&per_page=2>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/fixtures/section.json b/tests/fixtures/section.json index c4caecb..5c7df15 100644 --- a/tests/fixtures/section.json +++ b/tests/fixtures/section.json @@ -37,7 +37,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/sections/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/sections/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" } }, "list_enrollments_2": { @@ -101,7 +101,7 @@ "id": 1, "assignment_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload" }, "status_code": 200 @@ -114,14 +114,14 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload" }, { "id": 2, "assignments_id": 1, "user_id": 2, - "html_url": "http://example.com/sections/1/assignments/1/submissions/2", + "html_url": "https://example.com/sections/1/assignments/1/submissions/2", "submission_type": "online_upload" } ], @@ -135,14 +135,14 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload" }, { "id": 2, "assignments_id": 1, "user_id": 2, - "html_url": "http://example.com/sections/1/assignments/1/submissions/2", + "html_url": "https://example.com/sections/1/assignments/1/submissions/2", "submission_type": "online_upload" } ], @@ -155,7 +155,7 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload" }, "status_code": 200 @@ -167,7 +167,7 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload", "excused": true }, diff --git a/tests/fixtures/submission.json b/tests/fixtures/submission.json index 1d18224..f2610b3 100644 --- a/tests/fixtures/submission.json +++ b/tests/fixtures/submission.json @@ -6,7 +6,7 @@ "id": 1, "assignment_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload" }, "status_code": 200 @@ -18,7 +18,7 @@ "id": 1, "assignment_id": 1, "user_id": 1, - "html_url": "http://example.com/sections/1/assignments/1/submissions/1", + "html_url": "https://example.com/sections/1/assignments/1/submissions/1", "submission_type": "online_upload" }, "status_code": 200 @@ -31,14 +31,14 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload" }, { "id": 2, "assignments_id": 1, "user_id": 2, - "html_url": "http://example.com/courses/1/assignments/1/submissions/2", + "html_url": "https://example.com/courses/1/assignments/1/submissions/2", "submission_type": "online_upload" } ], @@ -48,7 +48,7 @@ "method": "POST", "endpoint": "courses/1/assignments/1/submissions/1/comments/files", "data": { - "upload_url": "http://example.com/api/v1/files/upload_response_upload_url", + "upload_url": "https://example.com/api/v1/files/upload_response_upload_url", "upload_params": { "some_param": "param123", "a_different_param": "param456" @@ -70,7 +70,7 @@ "id": 1, "assignments_id": 1, "user_id": 1, - "html_url": "http://example.com/courses/1/assignments/1/submissions/1", + "html_url": "https://example.com/courses/1/assignments/1/submissions/1", "submission_type": "online_upload", "excused": true }, diff --git a/tests/fixtures/uploader.json b/tests/fixtures/uploader.json index efcdb10..ccea364 100644 --- a/tests/fixtures/uploader.json +++ b/tests/fixtures/uploader.json @@ -3,7 +3,7 @@ "method": "POST", "endpoint": "upload_response", "data": { - "upload_url": "http://example.com/api/v1/upload_response_upload_url", + "upload_url": "https://example.com/api/v1/upload_response_upload_url", "upload_params": { "some_param": "param123", "a_different_param": "param456" @@ -35,7 +35,7 @@ "method": "POST", "endpoint": "upload_response_fail", "data": { - "upload_url": "http://example.com/api/v1/upload_fail", + "upload_url": "https://example.com/api/v1/upload_fail", "upload_params": { "some_param": "param123", "a_different_param": "param456" diff --git a/tests/fixtures/user.json b/tests/fixtures/user.json index 4aa36b0..3f9bb01 100644 --- a/tests/fixtures/user.json +++ b/tests/fixtures/user.json @@ -32,7 +32,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/avatars?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/avatars?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -117,7 +117,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/self/course_nicknames?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/self/course_nicknames?page=2&per_page=2>; rel=\"next\"" } }, "course_nicknames_delete": { @@ -161,7 +161,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/courses?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/courses?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -287,7 +287,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/1/courses/1/list_assignments?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/courses/1/list_assignments?page=2&per_page=2>; rel=\"next\"" } }, "get_user_assignments2": { @@ -326,7 +326,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/1/files?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/files?page=2&per_page=2>; rel=\"next\"" } }, "get_user_files2": { @@ -386,7 +386,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/1/communication_channels?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/communication_channels?page=2&per_page=2>; rel=\"next\"" } }, "list_comm_channels2": { @@ -427,7 +427,7 @@ ], "status_code": 200, "headers": { - "Link": "<http://example.com/api/v1/users/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/list_enrollments?page=2&per_page=2>; rel=\"next\"" } }, "list_enrollments_2": { @@ -490,7 +490,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/missing_submissions?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/missing_submissions?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -517,19 +517,19 @@ "data": [ { "id": "123fb561-c9ce-7ed9-8e42-31e0aab47e18", - "url": "http://example.com/test", + "url": "https://example.com/test", "created_at": "2013-01-01T12:00:00Z", "context_type": "Course" }, { "id": "4c7f44f9-41b9-ff59-03ad-3215cb246966", - "url": "http://example.com/hello", + "url": "https://example.com/hello", "created_at": "2014-01-01T12:00:00Z", "context_type": "User" } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/page_views?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/page_views?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -539,13 +539,13 @@ "data": [ { "id": "77f111c9-5b0b-46cb-92a2-34108ebe7b5b", - "url": "http://example.com/login", + "url": "https://example.com/login", "created_at": "2015-01-01T12:00:00Z", "context_type": null }, { "id": "69ec8b6f-e123-2af8-dafb-561fdc711f6b", - "url": "http://example.com/logout", + "url": "https://example.com/logout", "created_at": "2016-01-01T12:00:00Z", "context_type": "UserProfile" } @@ -620,7 +620,7 @@ "method": "POST", "endpoint": "users/1/files", "data": { - "upload_url": "http://example.com/api/v1/files/upload_response_upload_url", + "upload_url": "https://example.com/api/v1/files/upload_response_upload_url", "upload_params": { "some_param": "param123", "a_different_param": "param456" @@ -649,7 +649,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/logins/?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/logins/?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, @@ -683,7 +683,7 @@ } ], "headers": { - "Link": "<http://example.com/api/v1/users/1/observees?page=2&per_page=2>; rel=\"next\"" + "Link": "<https://example.com/api/v1/users/1/observees?page=2&per_page=2>; rel=\"next\"" }, "status_code": 200 }, diff --git a/tests/settings.py b/tests/settings.py index e67c5f6..ad1593f 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -1,7 +1,8 @@ from __future__ import absolute_import, division, print_function, unicode_literals -BASE_URL = 'http://example.com' -BASE_URL_WITH_VERSION = 'http://example.com/api/v1/' +BASE_URL = 'https://example.com' +BASE_URL_WITH_VERSION = 'https://example.com/api/v1/' +BASE_URL_AS_HTTP = 'http://example.com' API_KEY = '123' INVALID_ID = 9001 diff --git a/tests/test_canvas.py b/tests/test_canvas.py index 058bb46..4af23e9 100644 --- a/tests/test_canvas.py +++ b/tests/test_canvas.py @@ -40,6 +40,12 @@ class TestCanvas(unittest.TestCase): Canvas(settings.BASE_URL_WITH_VERSION, settings.API_KEY) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) + # Canvas() + def test_init_warns_when_url_is_http(self, m): + with warnings.catch_warnings(record=True) as w: + Canvas(settings.BASE_URL_AS_HTTP, settings.API_KEY) + self.assertTrue(issubclass(w[0].category, UserWarning)) + # create_account() def test_create_account(self, m): register_uris({'account': ['create']}, m) diff --git a/tests/test_course.py b/tests/test_course.py index 5e679eb..667c05b 100644 --- a/tests/test_course.py +++ b/tests/test_course.py @@ -1029,7 +1029,7 @@ class TestCourse(unittest.TestCase): def test_create_external_feed(self, m): register_uris({'course': ['create_external_feed']}, m) - url_str = "http://example.com/myblog.rss" + url_str = "https://example.com/myblog.rss" response = self.course.create_external_feed(url=url_str) self.assertIsInstance(response, ExternalFeed) diff --git a/tests/test_group.py b/tests/test_group.py index ade9c8e..4a41acc 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -419,7 +419,7 @@ class TestGroup(unittest.TestCase): def test_create_external_feed(self, m): register_uris({'group': ['create_external_feed']}, m) - url_str = "http://example.com/myblog.rss" + url_str = "https://example.com/myblog.rss" response = self.group.create_external_feed(url=url_str) self.assertIsInstance(response, ExternalFeed)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "flake8", "pycodestyle", "pyflakes", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt", "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 -e git+https://github.com/ucfopen/canvasapi.git@141962439d0a22318c1ae339fbf0e71a725d51a9#egg=canvasapi certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 docutils==0.17.1 flake8==5.0.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.2.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 requests==2.27.1 requests-mock==1.12.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==4.3.2 sphinx-rtd-theme==1.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: canvasapi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - coverage==6.2 - docutils==0.17.1 - flake8==5.0.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.2.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - requests==2.27.1 - requests-mock==1.12.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==4.3.2 - sphinx-rtd-theme==1.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/canvasapi
[ "tests/test_canvas.py::TestCanvas::test_init_warns_when_url_is_http" ]
[ "tests/test_canvas.py::TestCanvas::test_init_deprecate_url_contains_version", "tests/test_canvas.py::TestCanvas::test_list_appointment_groups", "tests/test_canvas.py::TestCanvas::test_list_calendar_events", "tests/test_canvas.py::TestCanvas::test_list_group_participants", "tests/test_canvas.py::TestCanvas::test_list_user_participants", "tests/test_course.py::TestCourse::test_get_submission", "tests/test_course.py::TestCourse::test_list_assignment_groups", "tests/test_course.py::TestCourse::test_list_external_feeds", "tests/test_course.py::TestCourse::test_list_files", "tests/test_course.py::TestCourse::test_list_folders", "tests/test_course.py::TestCourse::test_list_gradeable_students", "tests/test_course.py::TestCourse::test_list_group_categories", "tests/test_course.py::TestCourse::test_list_groups", "tests/test_course.py::TestCourse::test_list_multiple_submissions", "tests/test_course.py::TestCourse::test_list_rubrics", "tests/test_course.py::TestCourse::test_list_sections", "tests/test_course.py::TestCourse::test_list_submissions", "tests/test_course.py::TestCourse::test_list_tabs", "tests/test_course.py::TestCourse::test_mark_submission_as_read", "tests/test_course.py::TestCourse::test_mark_submission_as_unread", "tests/test_course.py::TestCourse::test_submit_assignment", "tests/test_course.py::TestCourse::test_submit_assignment_fail", "tests/test_course.py::TestCourse::test_update_submission", "tests/test_course.py::TestCourse::test_update_tab", "tests/test_group.py::TestGroup::test_list_external_feeds", "tests/test_group.py::TestGroup::test_list_files", "tests/test_group.py::TestGroup::test_list_folders", "tests/test_group.py::TestGroup::test_list_memberships", "tests/test_group.py::TestGroup::test_list_tabs", "tests/test_group.py::TestGroup::test_list_users", "tests/test_group.py::TestGroupCategory::test_list_groups", "tests/test_group.py::TestGroupCategory::test_list_users" ]
[ "tests/test_canvas.py::TestCanvas::test_clear_course_nicknames", "tests/test_canvas.py::TestCanvas::test_conversations_batch_update", "tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_event", "tests/test_canvas.py::TestCanvas::test_conversations_batch_updated_fail_on_ids", "tests/test_canvas.py::TestCanvas::test_conversations_get_running_batches", "tests/test_canvas.py::TestCanvas::test_conversations_mark_all_as_read", "tests/test_canvas.py::TestCanvas::test_conversations_unread_count", "tests/test_canvas.py::TestCanvas::test_create_account", "tests/test_canvas.py::TestCanvas::test_create_appointment_group", "tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_context_codes", "tests/test_canvas.py::TestCanvas::test_create_appointment_group_fail_on_title", "tests/test_canvas.py::TestCanvas::test_create_calendar_event", "tests/test_canvas.py::TestCanvas::test_create_calendar_event_fail", "tests/test_canvas.py::TestCanvas::test_create_conversation", "tests/test_canvas.py::TestCanvas::test_create_conversation_multiple_people", "tests/test_canvas.py::TestCanvas::test_create_group", "tests/test_canvas.py::TestCanvas::test_get_account", "tests/test_canvas.py::TestCanvas::test_get_account_fail", "tests/test_canvas.py::TestCanvas::test_get_account_sis_id", "tests/test_canvas.py::TestCanvas::test_get_accounts", "tests/test_canvas.py::TestCanvas::test_get_activity_stream_summary", "tests/test_canvas.py::TestCanvas::test_get_announcements", "tests/test_canvas.py::TestCanvas::test_get_appointment_group", "tests/test_canvas.py::TestCanvas::test_get_appointment_groups", "tests/test_canvas.py::TestCanvas::test_get_calendar_event", "tests/test_canvas.py::TestCanvas::test_get_calendar_events", "tests/test_canvas.py::TestCanvas::test_get_conversation", "tests/test_canvas.py::TestCanvas::test_get_conversations", "tests/test_canvas.py::TestCanvas::test_get_course", "tests/test_canvas.py::TestCanvas::test_get_course_accounts", "tests/test_canvas.py::TestCanvas::test_get_course_fail", "tests/test_canvas.py::TestCanvas::test_get_course_nickname", "tests/test_canvas.py::TestCanvas::test_get_course_nickname_fail", "tests/test_canvas.py::TestCanvas::test_get_course_nicknames", "tests/test_canvas.py::TestCanvas::test_get_course_non_unicode_char", "tests/test_canvas.py::TestCanvas::test_get_course_sis_id", "tests/test_canvas.py::TestCanvas::test_get_course_with_start_date", "tests/test_canvas.py::TestCanvas::test_get_courses", "tests/test_canvas.py::TestCanvas::test_get_file", "tests/test_canvas.py::TestCanvas::test_get_group", "tests/test_canvas.py::TestCanvas::test_get_group_category", "tests/test_canvas.py::TestCanvas::test_get_group_participants", "tests/test_canvas.py::TestCanvas::test_get_group_sis_id", "tests/test_canvas.py::TestCanvas::test_get_outcome", "tests/test_canvas.py::TestCanvas::test_get_outcome_group", "tests/test_canvas.py::TestCanvas::test_get_progress", "tests/test_canvas.py::TestCanvas::test_get_root_outcome_group", "tests/test_canvas.py::TestCanvas::test_get_section", "tests/test_canvas.py::TestCanvas::test_get_section_sis_id", "tests/test_canvas.py::TestCanvas::test_get_todo_items", "tests/test_canvas.py::TestCanvas::test_get_upcoming_events", "tests/test_canvas.py::TestCanvas::test_get_user", "tests/test_canvas.py::TestCanvas::test_get_user_by_id_type", "tests/test_canvas.py::TestCanvas::test_get_user_fail", "tests/test_canvas.py::TestCanvas::test_get_user_participants", "tests/test_canvas.py::TestCanvas::test_get_user_self", "tests/test_canvas.py::TestCanvas::test_reserve_time_slot", "tests/test_canvas.py::TestCanvas::test_reserve_time_slot_by_participant_id", "tests/test_canvas.py::TestCanvas::test_search_accounts", "tests/test_canvas.py::TestCanvas::test_search_all_courses", "tests/test_canvas.py::TestCanvas::test_search_recipients", "tests/test_canvas.py::TestCanvas::test_set_course_nickname", "tests/test_course.py::TestCourse::test__str__", "tests/test_course.py::TestCourse::test_add_grading_standards", "tests/test_course.py::TestCourse::test_add_grading_standards_empty_list", "tests/test_course.py::TestCourse::test_add_grading_standards_missing_name_key", "tests/test_course.py::TestCourse::test_add_grading_standards_missing_value_key", "tests/test_course.py::TestCourse::test_add_grading_standards_non_dict_list", "tests/test_course.py::TestCourse::test_conclude", "tests/test_course.py::TestCourse::test_create_assignment", "tests/test_course.py::TestCourse::test_create_assignment_fail", "tests/test_course.py::TestCourse::test_create_assignment_group", "tests/test_course.py::TestCourse::test_create_content_migration", "tests/test_course.py::TestCourse::test_create_content_migration_bad_migration_type", "tests/test_course.py::TestCourse::test_create_content_migration_migrator", "tests/test_course.py::TestCourse::test_create_course_section", "tests/test_course.py::TestCourse::test_create_discussion_topic", "tests/test_course.py::TestCourse::test_create_external_feed", "tests/test_course.py::TestCourse::test_create_external_tool", "tests/test_course.py::TestCourse::test_create_folder", "tests/test_course.py::TestCourse::test_create_group_category", "tests/test_course.py::TestCourse::test_create_module", "tests/test_course.py::TestCourse::test_create_module_fail", "tests/test_course.py::TestCourse::test_create_page", "tests/test_course.py::TestCourse::test_create_page_fail", "tests/test_course.py::TestCourse::test_create_quiz", "tests/test_course.py::TestCourse::test_create_quiz_fail", "tests/test_course.py::TestCourse::test_delete", "tests/test_course.py::TestCourse::test_delete_external_feed", "tests/test_course.py::TestCourse::test_edit_front_page", "tests/test_course.py::TestCourse::test_enroll_user", "tests/test_course.py::TestCourse::test_get_assignment", "tests/test_course.py::TestCourse::test_get_assignment_group", "tests/test_course.py::TestCourse::test_get_assignment_groups", "tests/test_course.py::TestCourse::test_get_assignments", "tests/test_course.py::TestCourse::test_get_content_migration", "tests/test_course.py::TestCourse::test_get_content_migrations", "tests/test_course.py::TestCourse::test_get_course_level_assignment_data", "tests/test_course.py::TestCourse::test_get_course_level_participation_data", "tests/test_course.py::TestCourse::test_get_course_level_student_summary_data", "tests/test_course.py::TestCourse::test_get_discussion_topic", "tests/test_course.py::TestCourse::test_get_discussion_topics", "tests/test_course.py::TestCourse::test_get_enrollments", "tests/test_course.py::TestCourse::test_get_external_feeds", "tests/test_course.py::TestCourse::test_get_external_tool", "tests/test_course.py::TestCourse::test_get_external_tools", "tests/test_course.py::TestCourse::test_get_file", "tests/test_course.py::TestCourse::test_get_files", "tests/test_course.py::TestCourse::test_get_folder", "tests/test_course.py::TestCourse::test_get_folders", "tests/test_course.py::TestCourse::test_get_full_discussion_topic", "tests/test_course.py::TestCourse::test_get_grading_standards", "tests/test_course.py::TestCourse::test_get_group_categories", "tests/test_course.py::TestCourse::test_get_groups", "tests/test_course.py::TestCourse::test_get_migration_systems", "tests/test_course.py::TestCourse::test_get_module", "tests/test_course.py::TestCourse::test_get_modules", "tests/test_course.py::TestCourse::test_get_multiple_submissions", "tests/test_course.py::TestCourse::test_get_multiple_submissions_grouped_param", "tests/test_course.py::TestCourse::test_get_outcome_group", "tests/test_course.py::TestCourse::test_get_outcome_groups_in_context", "tests/test_course.py::TestCourse::test_get_outcome_links_in_context", "tests/test_course.py::TestCourse::test_get_outcome_result_rollups", "tests/test_course.py::TestCourse::test_get_outcome_results", "tests/test_course.py::TestCourse::test_get_page", "tests/test_course.py::TestCourse::test_get_pages", "tests/test_course.py::TestCourse::test_get_quiz", "tests/test_course.py::TestCourse::test_get_quiz_fail", "tests/test_course.py::TestCourse::test_get_quizzes", "tests/test_course.py::TestCourse::test_get_recent_students", "tests/test_course.py::TestCourse::test_get_root_outcome_group", "tests/test_course.py::TestCourse::test_get_rubric", "tests/test_course.py::TestCourse::test_get_rubrics", "tests/test_course.py::TestCourse::test_get_section", "tests/test_course.py::TestCourse::test_get_sections", "tests/test_course.py::TestCourse::test_get_settings", "tests/test_course.py::TestCourse::test_get_single_grading_standard", "tests/test_course.py::TestCourse::test_get_tabs", "tests/test_course.py::TestCourse::test_get_user", "tests/test_course.py::TestCourse::test_get_user_id_type", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_assignment_data", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_messaging_data", "tests/test_course.py::TestCourse::test_get_user_in_a_course_level_participation_data", "tests/test_course.py::TestCourse::test_get_users", "tests/test_course.py::TestCourse::test_preview_html", "tests/test_course.py::TestCourse::test_reorder_pinned_topics", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_comma_separated_string", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_invalid_input", "tests/test_course.py::TestCourse::test_reorder_pinned_topics_tuple", "tests/test_course.py::TestCourse::test_reset", "tests/test_course.py::TestCourse::test_set_extensions_empty_list", "tests/test_course.py::TestCourse::test_set_extensions_missing_key", "tests/test_course.py::TestCourse::test_set_extensions_non_dicts", "tests/test_course.py::TestCourse::test_set_extensions_not_list", "tests/test_course.py::TestCourse::test_set_quiz_extensions", "tests/test_course.py::TestCourse::test_show_front_page", "tests/test_course.py::TestCourse::test_submissions_bulk_update", "tests/test_course.py::TestCourse::test_update", "tests/test_course.py::TestCourse::test_update_settings", "tests/test_course.py::TestCourse::test_upload", "tests/test_course.py::TestCourseNickname::test__str__", "tests/test_course.py::TestCourseNickname::test_remove", "tests/test_group.py::TestGroup::test__str__", "tests/test_group.py::TestGroup::test_create_content_migration", "tests/test_group.py::TestGroup::test_create_content_migration_bad_migration_type", "tests/test_group.py::TestGroup::test_create_content_migration_migrator", "tests/test_group.py::TestGroup::test_create_discussion_topic", "tests/test_group.py::TestGroup::test_create_external_feed", "tests/test_group.py::TestGroup::test_create_folder", "tests/test_group.py::TestGroup::test_create_membership", "tests/test_group.py::TestGroup::test_create_page", "tests/test_group.py::TestGroup::test_create_page_fail", "tests/test_group.py::TestGroup::test_delete", "tests/test_group.py::TestGroup::test_delete_external_feed", "tests/test_group.py::TestGroup::test_edit", "tests/test_group.py::TestGroup::test_edit_front_page", "tests/test_group.py::TestGroup::test_get_activity_stream_summary", "tests/test_group.py::TestGroup::test_get_content_migration", "tests/test_group.py::TestGroup::test_get_content_migrations", "tests/test_group.py::TestGroup::test_get_discussion_topic", "tests/test_group.py::TestGroup::test_get_discussion_topics", "tests/test_group.py::TestGroup::test_get_external_feeds", "tests/test_group.py::TestGroup::test_get_file", "tests/test_group.py::TestGroup::test_get_files", "tests/test_group.py::TestGroup::test_get_folder", "tests/test_group.py::TestGroup::test_get_folders", "tests/test_group.py::TestGroup::test_get_full_discussion_topic", "tests/test_group.py::TestGroup::test_get_membership", "tests/test_group.py::TestGroup::test_get_memberships", "tests/test_group.py::TestGroup::test_get_migration_systems", "tests/test_group.py::TestGroup::test_get_page", "tests/test_group.py::TestGroup::test_get_pages", "tests/test_group.py::TestGroup::test_get_tabs", "tests/test_group.py::TestGroup::test_get_users", "tests/test_group.py::TestGroup::test_invite", "tests/test_group.py::TestGroup::test_preview_processed_html", "tests/test_group.py::TestGroup::test_remove_user", "tests/test_group.py::TestGroup::test_reorder_pinned_topics", "tests/test_group.py::TestGroup::test_reorder_pinned_topics_comma_separated_string", "tests/test_group.py::TestGroup::test_reorder_pinned_topics_invalid_input", "tests/test_group.py::TestGroup::test_reorder_pinned_topics_tuple", "tests/test_group.py::TestGroup::test_show_front_page", "tests/test_group.py::TestGroup::test_update_membership", "tests/test_group.py::TestGroup::test_upload", "tests/test_group.py::TestGroupMembership::test__str__", "tests/test_group.py::TestGroupMembership::test_remove_self", "tests/test_group.py::TestGroupMembership::test_remove_user", "tests/test_group.py::TestGroupMembership::test_update", "tests/test_group.py::TestGroupCategory::test__str__", "tests/test_group.py::TestGroupCategory::test_assign_members", "tests/test_group.py::TestGroupCategory::test_create_group", "tests/test_group.py::TestGroupCategory::test_delete_category", "tests/test_group.py::TestGroupCategory::test_get_groups", "tests/test_group.py::TestGroupCategory::test_get_users", "tests/test_group.py::TestGroupCategory::test_update" ]
[]
MIT License
2,704
174
[ "canvasapi/canvas.py" ]
google__docker-explorer-43
2fa6d1707b8654252ffee92be71877c5e50ea6cb
2018-06-29 09:31:39
2fa6d1707b8654252ffee92be71877c5e50ea6cb
diff --git a/docker_explorer/de.py b/docker_explorer/de.py index 4817867..c42b89c 100644 --- a/docker_explorer/de.py +++ b/docker_explorer/de.py @@ -41,7 +41,7 @@ class DockerExplorer(object): self._argument_parser = None self.container_config_filename = 'config.v2.json' self.containers_directory = None - self.docker_directory = None + self.docker_directory = '/var/lib/docker' self.docker_version = 2 def _SetDockerDirectory(self, docker_path): @@ -136,15 +136,49 @@ class DockerExplorer(object): """Parses the command line options.""" self.docker_directory = os.path.abspath(options.docker_directory) - def GetContainer(self, container_id): - """Returns a Container object given a container_id. + def _GetFullContainerID(self, short_id): + """Searches for a container ID from its first characters. Args: - container_id (str): the ID of the container. + short_id (str): the first few characters of a container ID. + Returns: + str: the full container ID + Raises: + errors.DockerExplorerError: when we couldn't map the short version to + exactly one full container ID. + """ + if len(short_id) == 64: + return short_id + + containers_dir = os.path.join(self.docker_directory, 'containers') + possible_cids = [] + for container_dirs in sorted(os.listdir(containers_dir)): + possible_cid = os.path.basename(container_dirs) + if possible_cid.startswith(short_id): + possible_cids.append(possible_cid) + + possible_cids_len = len(possible_cids) + if possible_cids_len == 0: + raise errors.DockerExplorerError( + 'Could not find any container ID starting with "{0}"'.format( + short_id)) + if possible_cids_len > 1: + raise errors.DockerExplorerError( + 'Too many container IDs starting with "{0}": {1}'.format( + short_id, ', '.join(possible_cids))) + + return possible_cids[0] + + def GetContainer(self, container_id_part): + """Returns a Container object given the first characters of a container_id. + + Args: + container_id_part (str): the first characters of a container ID. Returns: container.Container: the container object. """ + container_id = self._GetFullContainerID(container_id_part) return container.Container( self.docker_directory, container_id, docker_version=self.docker_version)
Have DE auto complete partial docker ID ie use `0ddf71064` for `0ddf710643b47e581dbce3e17677c9a557b82943bacee2dfbc19f178a99ad374`
google/docker-explorer
diff --git a/tests.py b/tests.py index c3689d9..6d73370 100644 --- a/tests.py +++ b/tests.py @@ -250,6 +250,31 @@ class TestAufsStorage(DockerTestCase): 'with command : /bin/sh -c #(nop) CMD ["sh"]') self.assertEqual(expected_string, container_obj.GetHistory()) + def testGetFullContainerID(self): + """Tests the DockerExplorer._GetFullContainerID function on AuFS.""" + self.assertEqual( + '2cc4b0d9c1dfdf71099c5e9a109e6a0fe286152a5396bd1850689478e8f70625', + self.de_object._GetFullContainerID('2cc4b0d')) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('') + self.assertEqual( + 'Too many container IDs starting with "": ' + '1171e9631158156ba2b984d335b2bf31838403700df3882c51aed70beebb604f, ' + '2cc4b0d9c1dfdf71099c5e9a109e6a0fe286152a5396bd1850689478e8f70625, ' + '7b02fb3e8a665a63e32b909af5babb7d6ba0b64e10003b2d9534c7d5f2af8966, ' + '986c6e682f30550512bc2f7243f5a57c91b025e543ef703c426d732585209945, ' + 'b6f881bfc566ed604da1dc9bc8782a3540380c094154d703a77113b1ecfca660, ' + 'c8a38b6c29b0c901c37c2bb17bfcd73942c44bb71cc528505385c62f3c6fff35, ' + 'dd39804186d4f649f1e9cec89df1583e7a12a48193223a16cc40958f7e76b858', + err.exception.message) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('xx') + self.assertEqual( + 'Could not find any container ID starting with "xx"', + err.exception.message) + class TestOverlayStorage(DockerTestCase): """Tests methods in the OverlayStorage object.""" @@ -378,6 +403,26 @@ class TestOverlayStorage(DockerTestCase): 'with command : /bin/sh -c #(nop) CMD ["sh"]') self.assertEqual(expected_string, container_obj.GetHistory()) + def testGetFullContainerID(self): + """Tests the DockerExplorer._GetFullContainerID function on Overlay.""" + self.assertEqual( + '5dc287aa80b460652a5584e80a5c8c1233b0c0691972d75424cf5250b917600a', + self.de_object._GetFullContainerID('5dc287aa80')) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('4') + self.assertEqual( + 'Too many container IDs starting with "4": ' + '42e8679f78d6ea623391cdbcb928740ed804f928bd94f94e1d98687f34c48311, ' + '4ad09bee61dcc675bf41085dbf38c31426a7ed6666fdd47521bfb8f5e67a7e6d', + err.exception.message) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('xx') + self.assertEqual( + 'Could not find any container ID starting with "xx"', + err.exception.message) + class TestOverlay2Storage(DockerTestCase): """Tests methods in the Overlay2Storage object.""" @@ -516,6 +561,30 @@ class TestOverlay2Storage(DockerTestCase): 'with command : /bin/sh -c #(nop) CMD ["sh"]') self.assertEqual(expected_string, container_obj.GetHistory(container_obj)) + def testGetFullContainerID(self): + """Tests the DockerExplorer._GetFullContainerID function on Overlay2.""" + self.assertEqual( + '61ba4e6c012c782186c649466157e05adfd7caa5b551432de51043893cae5353', + self.de_object._GetFullContainerID('61ba4e6c012c782')) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('') + self.assertEqual( + 'Too many container IDs starting with "": ' + '10acac0b3466813c9e1f85e2aa7d06298e51fbfe86bbcb6b7a19dd33d3798f6a, ' + '61ba4e6c012c782186c649466157e05adfd7caa5b551432de51043893cae5353, ' + '8e8b7f23eb7cbd4dfe7e91646ddd0e0f524218e25d50113559f078dfb2690206, ' + '9949fa153b778e39d6cab0a4e0ba60fa34a13fedb1f256d613a2f88c0c98408a, ' + 'f83f963c67cbd36055f690fc988c1e42be06c1253e80113d1d516778c06b2841', + err.exception.message) + + with self.assertRaises(Exception) as err: + self.de_object._GetFullContainerID('xx') + self.assertEqual( + 'Could not find any container ID starting with "xx"', + err.exception.message) + + del DockerTestCase if __name__ == '__main__':
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/google/docker-explorer.git@2fa6d1707b8654252ffee92be71877c5e50ea6cb#egg=docker_explorer exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: docker-explorer channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/docker-explorer
[ "tests.py::TestAufsStorage::testGetFullContainerID", "tests.py::TestOverlayStorage::testGetFullContainerID", "tests.py::TestOverlay2Storage::testGetFullContainerID" ]
[]
[ "tests.py::UtilsTests::testFormatDatetime", "tests.py::UtilsTests::testPrettyPrintJSON", "tests.py::TestDEMain::testDetectStorageFail", "tests.py::TestDEMain::testParseArguments", "tests.py::TestAufsStorage::testDetectStorage", "tests.py::TestAufsStorage::testGetAllContainers", "tests.py::TestAufsStorage::testGetContainersString", "tests.py::TestAufsStorage::testGetHistory", "tests.py::TestAufsStorage::testGetLayerInfo", "tests.py::TestAufsStorage::testGetOrderedLayers", "tests.py::TestAufsStorage::testGetRepositoriesString", "tests.py::TestAufsStorage::testGetRunningContainersList", "tests.py::TestAufsStorage::testMakeMountCommands", "tests.py::TestOverlayStorage::testDetectStorage", "tests.py::TestOverlayStorage::testGetAllContainers", "tests.py::TestOverlayStorage::testGetContainersString", "tests.py::TestOverlayStorage::testGetHistory", "tests.py::TestOverlayStorage::testGetLayerInfo", "tests.py::TestOverlayStorage::testGetOrderedLayers", "tests.py::TestOverlayStorage::testGetRepositoriesString", "tests.py::TestOverlayStorage::testGetRunningContainersList", "tests.py::TestOverlayStorage::testMakeMountCommands", "tests.py::TestOverlay2Storage::testDetectStorage", "tests.py::TestOverlay2Storage::testGetAllContainers", "tests.py::TestOverlay2Storage::testGetContainersString", "tests.py::TestOverlay2Storage::testGetHistory", "tests.py::TestOverlay2Storage::testGetLayerInfo", "tests.py::TestOverlay2Storage::testGetOrderedLayers", "tests.py::TestOverlay2Storage::testGetRepositoriesString", "tests.py::TestOverlay2Storage::testGetRunningContainersList", "tests.py::TestOverlay2Storage::testMakeMountCommands" ]
[]
Apache License 2.0
2,719
612
[ "docker_explorer/de.py" ]
tmontes__ppytty-54
36a1a711020ff143e761f203127ccebc627b85c5
2018-07-02 14:17:41
36a1a711020ff143e761f203127ccebc627b85c5
diff --git a/src/ppytty/kernel/common.py b/src/ppytty/kernel/common.py index 2796add..a730fcb 100644 --- a/src/ppytty/kernel/common.py +++ b/src/ppytty/kernel/common.py @@ -11,7 +11,9 @@ from . state import state def runnable_task(task): - return task() if callable(task) else task + runnable = task() if callable(task) else task + state.spawned_objects[runnable] = task + return runnable diff --git a/src/ppytty/kernel/scheduler.py b/src/ppytty/kernel/scheduler.py index a392f8b..b4e6052 100644 --- a/src/ppytty/kernel/scheduler.py +++ b/src/ppytty/kernel/scheduler.py @@ -162,7 +162,9 @@ def process_task_completion(task, success, result): if not candidate_parent and task is not state.top_task: log.error('%r completed with no parent', task) if candidate_parent in state.tasks_waiting_child: - common.trap_will_return(candidate_parent, (task, success, result)) + spawned_object = state.spawned_objects[task] + common.trap_will_return(candidate_parent, (spawned_object, success, result)) + del state.spawned_objects[task] del state.parent_task[task] state.child_tasks[candidate_parent].remove(task) common.clear_tasks_children(candidate_parent) diff --git a/src/ppytty/kernel/state.py b/src/ppytty/kernel/state.py index ac6aee0..824c939 100644 --- a/src/ppytty/kernel/state.py +++ b/src/ppytty/kernel/state.py @@ -51,6 +51,12 @@ class _State(object): self.tasks_waiting_time = [] self.tasks_waiting_time_hq = [] + # --------------------------------------------------------------------- + # Spawned objects + + # Maps running tasks to objects passed to scheduler.run / task-spawn. + self.spawned_objects = {} + # --------------------------------------------------------------------- # Task trap tracking. diff --git a/src/ppytty/kernel/trap_handlers.py b/src/ppytty/kernel/trap_handlers.py index f367e08..f148354 100644 --- a/src/ppytty/kernel/trap_handlers.py +++ b/src/ppytty/kernel/trap_handlers.py @@ -139,7 +139,9 @@ def task_wait(task): success, result = state.completed_tasks[child] break if child is not None: - common.trap_will_return(task, (child, success, result)) + spawned_object = state.spawned_objects[child] + common.trap_will_return(task, (spawned_object, success, result)) + del state.spawned_objects[child] del state.parent_task[child] state.child_tasks[task].remove(child) common.clear_tasks_children(task) @@ -198,7 +200,8 @@ def message_send(task, to_task, message): if to_task in state.tasks_waiting_inbox: state.tasks_waiting_inbox.remove(to_task) - common.trap_will_return(to_task, (task, message)) + spawned_object = state.spawned_objects[task] + common.trap_will_return(to_task, (spawned_object, message)) state.runnable_tasks.append(to_task) else: state.task_inbox[to_task].append((task, message)) @@ -212,7 +215,8 @@ def message_wait(task): task_inbox = state.task_inbox[task] if task_inbox: sender_task, message = task_inbox.popleft() - common.trap_will_return(task, (sender_task, message)) + spawned_object = state.spawned_objects[sender_task] + common.trap_will_return(task, (spawned_object, message)) state.runnable_tasks.append(task) else: state.tasks_waiting_inbox.append(task)
Traps returning tasks need fixing. Summary: * Traps like `task-wait` and `message-wait` return, among other things, a reference to a task. * The returned value is, however, not necessarily the same that was used in `task-spawn`. Motive: * The kernel will call the passed in task object if it is callable (assuming it is a generator function) which is then used in those traps results. Failing example: ``` def child(): yield ('sleep',) def parent(): yield ('task-spawn', child) completed_task, success, result = yield ('task-wait',) # This fails because completed_task is actually the generator object obtained by calling assert completed_task is childchild ``` Possible solutions: * Have the kernel require passed in tasks (to top-level `run`/`task-spawn`) to be a *generator object* or alike. * Have the kernel track what it was passed vs. what it uses internally. Let's sleep on this for a while.
tmontes/ppytty
diff --git a/tests/kernel/tasks.py b/tests/kernel/tasks.py index c66aa2e..2397d6b 100644 --- a/tests/kernel/tasks.py +++ b/tests/kernel/tasks.py @@ -13,11 +13,13 @@ def sleep_zero(): -def spawn_wait(task): +def spawn_wait(task, sleep_before_wait=False): yield ('task-spawn', task) - _, success, result = yield ('task-wait',) - return success, result + if sleep_before_wait: + yield ('sleep', 0) + completed_task, success, result = yield ('task-wait',) + return completed_task, success, result diff --git a/tests/kernel/test_state.py b/tests/kernel/test_state.py index 0a66aa6..6537cb3 100644 --- a/tests/kernel/test_state.py +++ b/tests/kernel/test_state.py @@ -79,6 +79,7 @@ STATE_ATTRS = { 'tasks_waiting_key_hq': (_assert_empty_list, _change_list), 'tasks_waiting_time': (_assert_empty_list, _change_list), 'tasks_waiting_time_hq': (_assert_empty_list, _change_list), + 'spawned_objects': (_assert_empty_dict, _change_dict), 'trap_call': (_assert_empty_dict, _change_dict), 'trap_success': (_assert_empty_dict, _change_dict), 'trap_result': (_assert_empty_dict, _change_dict), diff --git a/tests/kernel/test_task_api_msgs.py b/tests/kernel/test_task_api_msgs.py index ccb15bc..adfc29b 100644 --- a/tests/kernel/test_task_api_msgs.py +++ b/tests/kernel/test_task_api_msgs.py @@ -119,4 +119,72 @@ class TestChildToParent(io_bypass.NoOutputTestCase): self.assertEqual(result['received-message'], 'child-to-parent-message') + +class TestSenderTaskIsChildTask(io_bypass.NoOutputTestCase): + + def _fast_child(self): + + yield ('message-send', None, 'hi-from-child') + + + def _slow_child(self): + + yield ('sleep', 0) + yield ('message-send', None, 'hi-from-child') + + + def _parent(self, child_object): + + yield ('task-spawn', child_object) + sender_task, message = yield ('message-wait',) + completed_child, child_success, child_result = yield ('task-wait',) + return sender_task, message, completed_child, child_success, child_result + + + def _assert_parent_result(self, child_object, result): + + sender_task, message, completed_child, child_success, child_result = result + self.assertIs(sender_task, child_object) + self.assertEqual(message, 'hi-from-child') + self.assertIs(completed_child, child_object) + self.assertTrue(child_success) + self.assertIsNone(child_result) + + + def test_gen_function_child_parent_waits_1st(self): + + child_gen_function = self._slow_child + parent = self._parent(child_gen_function) + success, result = run(parent) + self.assertTrue(success) + self._assert_parent_result(child_gen_function, result) + + + def test_gen_function_child_parent_waits_2nd(self): + + child_gen_function = self._fast_child + parent = self._parent(child_gen_function) + success, result = run(parent) + self.assertTrue(success) + self._assert_parent_result(child_gen_function, result) + + + def test_gen_object_child_parent_waits_1st(self): + + child_gen_object = self._slow_child() + parent = self._parent(child_gen_object) + success, result = run(parent) + self.assertTrue(success) + self._assert_parent_result(child_gen_object, result) + + + def test_gen_object_child_parent_waits_2nd(self): + + child_gen_object = self._fast_child() + parent = self._parent(child_gen_object) + success, result = run(parent) + self.assertTrue(success) + self._assert_parent_result(child_gen_object, result) + + # ---------------------------------------------------------------------------- diff --git a/tests/kernel/test_task_api_tasks.py b/tests/kernel/test_task_api_tasks.py index d26946e..9893e37 100644 --- a/tests/kernel/test_task_api_tasks.py +++ b/tests/kernel/test_task_api_tasks.py @@ -14,20 +14,54 @@ from . import tasks -class TestSpawn(io_bypass.NoOutputTestCase): +class TestSpawnWaitObjects(io_bypass.NoOutputTestCase): - def test_spawn_gen_function(self): + def test_spawn_wait_gen_function_child_completes_1st(self): generator_function = tasks.sleep_zero task = tasks.spawn_wait(generator_function) - run(task) + success, result = run(task) + self.assertTrue(success) + completed_child, child_success, child_result = result + self.assertIs(completed_child, generator_function) + self.assertTrue(child_success) + self.assertIsNone(child_result) - def test_spawn_gen_object(self): + def test_spawn_wait_gen_object_child_completes_1st(self): generator_object = tasks.sleep_zero() task = tasks.spawn_wait(generator_object) - run(task) + success, result = run(task) + self.assertTrue(success) + completed_child, child_success, child_result = result + self.assertIs(completed_child, generator_object) + self.assertTrue(child_success) + self.assertIsNone(child_result) + + + def test_spawn_wait_gen_function_child_completes_2nd(self): + + generator_function = tasks.sleep_zero + task = tasks.spawn_wait(generator_function, sleep_before_wait=True) + success, result = run(task) + self.assertTrue(success) + completed_child, child_success, child_result = result + self.assertIs(completed_child, generator_function) + self.assertTrue(child_success) + self.assertIsNone(child_result) + + + def test_spawn_wait_gen_object_child_completes_2nd(self): + + generator_object = tasks.sleep_zero() + task = tasks.spawn_wait(generator_object, sleep_before_wait=True) + success, result = run(task) + self.assertTrue(success) + completed_child, child_success, child_result = result + self.assertIs(completed_child, generator_object) + self.assertTrue(child_success) + self.assertIsNone(child_result) @@ -38,7 +72,7 @@ class TestWait(io_bypass.NoOutputTestCase): task = tasks.spawn_wait(tasks.sleep_zero_return_42_idiv_arg(42)) parent_sucess, parent_result = run(task) self.assertTrue(parent_sucess) - child_success, child_result = parent_result + _completed_child, child_success, child_result = parent_result self.assertTrue(child_success) self.assertEqual(child_result, 1) @@ -48,7 +82,7 @@ class TestWait(io_bypass.NoOutputTestCase): task = tasks.spawn_wait(tasks.sleep_zero_return_42_idiv_arg(0)) parent_success, parent_result = run(task) self.assertTrue(parent_success) - child_success, child_result = parent_result + _completed_child, child_success, child_result = parent_result self.assertFalse(child_success) self.assertIsInstance(child_result, ZeroDivisionError) @@ -58,15 +92,10 @@ class TestWaitChildException(io_bypass.NoOutputTestCase): def parent_spawn_wait_child_exception(self, child_task, expected_exc_class): - def parent(): - yield ('task-spawn', child_task) - completed_task, child_success, child_result = yield ('task-wait',) - return completed_task is child_task, child_success, child_result - - success, result = run(parent) + success, result = run(tasks.spawn_wait(child_task)) self.assertTrue(success) - correct_task_completed, child_task_success, child_task_result = result - self.assertTrue(correct_task_completed) + completed_child, child_task_success, child_task_result = result + self.assertIs(completed_child, child_task) self.assertFalse(child_task_success) self.assertIsInstance(child_task_result, expected_exc_class)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 4 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 blessings==1.7 coverage==7.8.0 dill==0.3.9 exceptiongroup==1.2.2 iniconfig==2.1.0 isort==6.0.1 mccabe==0.7.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 -e git+https://github.com/tmontes/ppytty.git@36a1a711020ff143e761f203127ccebc627b85c5#egg=ppytty pylint==3.3.6 pyte==0.8.2 pytest==8.3.5 six==1.17.0 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 wcwidth==0.2.13
name: ppytty channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - blessings==1.7 - coverage==7.8.0 - dill==0.3.9 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pylint==3.3.6 - pyte==0.8.2 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - wcwidth==0.2.13 prefix: /opt/conda/envs/ppytty
[ "tests/kernel/test_state.py::TestRun::test_state_attrs_are_clean", "tests/kernel/test_state.py::TestRun::test_state_attrs_are_these", "tests/kernel/test_state.py::TestRun::test_state_reset" ]
[ "tests/kernel/test_task_api_msgs.py::TestParentToChild::test_parent_spawn_child_message_wait_parent_send", "tests/kernel/test_task_api_msgs.py::TestParentToChild::test_parent_spawn_send_child_message_wait", "tests/kernel/test_task_api_msgs.py::TestChildToParent::test_parent_spawn_child_message_send_parent_message_wait", "tests/kernel/test_task_api_msgs.py::TestChildToParent::test_parent_spawn_message_wait_child_message_send", "tests/kernel/test_task_api_msgs.py::TestSenderTaskIsChildTask::test_gen_function_child_parent_waits_1st", "tests/kernel/test_task_api_msgs.py::TestSenderTaskIsChildTask::test_gen_function_child_parent_waits_2nd", "tests/kernel/test_task_api_msgs.py::TestSenderTaskIsChildTask::test_gen_object_child_parent_waits_1st", "tests/kernel/test_task_api_msgs.py::TestSenderTaskIsChildTask::test_gen_object_child_parent_waits_2nd", "tests/kernel/test_task_api_tasks.py::TestSpawnWaitObjects::test_spawn_wait_gen_function_child_completes_1st", "tests/kernel/test_task_api_tasks.py::TestSpawnWaitObjects::test_spawn_wait_gen_function_child_completes_2nd", "tests/kernel/test_task_api_tasks.py::TestSpawnWaitObjects::test_spawn_wait_gen_object_child_completes_1st", "tests/kernel/test_task_api_tasks.py::TestSpawnWaitObjects::test_spawn_wait_gen_object_child_completes_2nd", "tests/kernel/test_task_api_tasks.py::TestWait::test_wait_child_exception", "tests/kernel/test_task_api_tasks.py::TestWait::test_wait_child_success", "tests/kernel/test_task_api_tasks.py::TestWaitChildException::test_parent_spawn_wait_child_exception", "tests/kernel/test_task_api_tasks.py::TestWaitChildException::test_parent_spawn_wait_child_trap_arg_count_wrong_exception", "tests/kernel/test_task_api_tasks.py::TestWaitChildException::test_parent_spawn_wait_child_trap_does_not_exist_exception", "tests/kernel/test_task_api_tasks.py::TestSpawnDontWait::test_child_spawn_crash_no_grand_child_wait_child_completes_1st", "tests/kernel/test_task_api_tasks.py::TestSpawnDontWait::test_child_spawn_crash_no_grand_child_wait_child_completes_2nd", "tests/kernel/test_task_api_tasks.py::TestSpawnDontWait::test_parent_spawn_crash_no_child_wait_parent_completes_1st", "tests/kernel/test_task_api_tasks.py::TestSpawnDontWait::test_parent_spawn_crash_no_child_wait_parent_completes_2nd" ]
[]
[]
MIT License
2,732
915
[ "src/ppytty/kernel/common.py", "src/ppytty/kernel/scheduler.py", "src/ppytty/kernel/state.py", "src/ppytty/kernel/trap_handlers.py" ]
Azure__msrestazure-for-python-107
bc59bae35d784f0aad8d1e26ebfd9c20897dca46
2018-07-02 21:27:59
0f372b60f9add4c245c323e24acca038936e472f
diff --git a/msrestazure/azure_active_directory.py b/msrestazure/azure_active_directory.py index 48ac41c..88c3744 100644 --- a/msrestazure/azure_active_directory.py +++ b/msrestazure/azure_active_directory.py @@ -685,6 +685,8 @@ class MSIAuthentication(BasicTokenAuthentication): elif "MSI_ENDPOINT" not in os.environ: # Use IMDS if no MSI_ENDPOINT self._vm_msi = _ImdsTokenProvider(self.resource, self.msi_conf) + # Follow the same convention as all Credentials class to check for the token at creation time #106 + self.set_token() def set_token(self): if _is_app_service():
MSIAuthentication should set toekn on instance creation All msrestazure instance set the token on instance creation, except MSIAuthentication. This presents a few issues: - Unlike all other usages, authentication exception will be raised at usage, not at creation level - This creates weird bug in KeyVault which is doing some magic inside credentials: https://github.com/Azure/azure-sdk-for-python/issues/2852
Azure/msrestazure-for-python
diff --git a/tests/test_auth.py b/tests/test_auth.py index ed5ae77..56baf9c 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -240,7 +240,7 @@ class TestServicePrincipalCredentials(unittest.TestCase): ServicePrincipalCredentials, '_setup_session', return_value=session): proxies = {'http': 'http://myproxy:80'} - creds = ServicePrincipalCredentials("client_id", "secret", + creds = ServicePrincipalCredentials("client_id", "secret", verify=False, tenant="private", proxies=proxies) @@ -311,7 +311,7 @@ class TestServicePrincipalCredentials(unittest.TestCase): UserPassCredentials, '_setup_session', return_value=session): proxies = {'http': 'http://myproxy:8080'} - creds = UserPassCredentials("my_username", "my_password", + creds = UserPassCredentials("my_username", "my_password", verify=False, tenant="private", resource='resource', proxies=proxies) @@ -381,7 +381,7 @@ class TestServicePrincipalCredentials(unittest.TestCase): assert token_type == "TokenType" assert access_token == "AccessToken" assert token_entry == json_payload - + httpretty.register_uri(httpretty.POST, 'http://localhost:42/oauth2/token', status=503, @@ -419,10 +419,9 @@ class TestServicePrincipalCredentials(unittest.TestCase): content_type="application/json") credentials = MSIAuthentication() - credentials.set_token() assert credentials.scheme == "TokenTypeIMDS" assert credentials.token == json_payload - + # Test MSIAuthentication with MSI_ENDPOINT and no APPSETTING_WEBSITE_SITE_NAME is MSI_ENDPOINT json_payload = { @@ -436,7 +435,6 @@ class TestServicePrincipalCredentials(unittest.TestCase): with mock.patch('os.environ', {'MSI_ENDPOINT': 'http://random.org/yadadada'}): credentials = MSIAuthentication() - credentials.set_token() assert credentials.scheme == "TokenTypeMSI_ENDPOINT" assert credentials.token == json_payload @@ -458,14 +456,13 @@ class TestServicePrincipalCredentials(unittest.TestCase): } with mock.patch.dict('os.environ', app_service_env): credentials = MSIAuthentication(resource="foo") - credentials.set_token() assert credentials.scheme == "TokenTypeWebApp" assert credentials.token == json_payload @httpretty.activate def test_msi_vm_imds_retry(self): - + json_payload = { 'token_type': "TokenTypeIMDS", "access_token": "AccessToken" @@ -484,20 +481,18 @@ class TestServicePrincipalCredentials(unittest.TestCase): body=json.dumps(json_payload), content_type="application/json") credentials = MSIAuthentication() - credentials.set_token() assert credentials.scheme == "TokenTypeIMDS" assert credentials.token == json_payload @httpretty.activate def test_msi_vm_imds_no_retry_on_bad_error(self): - + httpretty.register_uri(httpretty.GET, 'http://169.254.169.254/metadata/identity/oauth2/token', status=499) - credentials = MSIAuthentication() with self.assertRaises(HTTPError) as cm: - credentials.set_token() + credentials = MSIAuthentication() @pytest.mark.slow @@ -515,7 +510,7 @@ def test_refresh_userpassword_no_common_session(user_password): # Hacking the token time creds.token['expires_on'] = time.time() - 10 creds.token['expires_at'] = creds.token['expires_on'] - + try: session = creds.signed_session() response = session.get("https://management.azure.com/subscriptions?api-version=2016-06-01") @@ -541,7 +536,7 @@ def test_refresh_userpassword_common_session(user_password): # Hacking the token time creds.token['expires_on'] = time.time() - 10 creds.token['expires_at'] = creds.token['expires_on'] - + try: session = creds.signed_session(root_session) response = session.get("https://management.azure.com/subscriptions?api-version=2016-06-01") @@ -573,7 +568,7 @@ def test_refresh_aadtokencredentials_no_common_session(user_password): # Hacking the token time creds.token['expires_on'] = time.time() - 10 creds.token['expires_at'] = creds.token['expires_on'] - + try: session = creds.signed_session() response = session.get("https://management.azure.com/subscriptions?api-version=2016-06-01") @@ -607,7 +602,7 @@ def test_refresh_aadtokencredentials_common_session(user_password): # Hacking the token time creds.token['expires_on'] = time.time() - 10 creds.token['expires_at'] = creds.token['expires_on'] - + try: session = creds.signed_session(root_session) response = session.get("https://management.azure.com/subscriptions?api-version=2016-06-01")
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "httpretty", "pytest", "pytest-cov", "pylint" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libunwind8-dev" ], "python": "3.6", "reqs_path": [ "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
adal==1.2.7 astroid==2.11.7 attrs==22.2.0 azure-core==1.24.2 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 coverage==6.2 cryptography==40.0.2 dill==0.3.4 httpretty==1.1.4 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 isort==5.10.1 jeepney==0.7.1 keyring==23.4.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==5.2.0 msrest==0.7.1 -e git+https://github.com/Azure/msrestazure-for-python.git@bc59bae35d784f0aad8d1e26ebfd9c20897dca46#egg=msrestazure oauthlib==3.2.2 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycparser==2.21 PyJWT==2.4.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 requests==2.27.1 requests-oauthlib==2.0.0 SecretStorage==3.3.3 six==1.17.0 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 wrapt==1.16.0 zipp==3.6.0
name: msrestazure-for-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - adal==1.2.7 - astroid==2.11.7 - attrs==22.2.0 - azure-core==1.24.2 - cffi==1.15.1 - charset-normalizer==2.0.12 - coverage==6.2 - cryptography==40.0.2 - dill==0.3.4 - httpretty==1.1.4 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - isort==5.10.1 - jeepney==0.7.1 - keyring==23.4.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==5.2.0 - msrest==0.7.1 - oauthlib==3.2.2 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pyjwt==2.4.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - requests==2.27.1 - requests-oauthlib==2.0.0 - secretstorage==3.3.3 - six==1.17.0 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/msrestazure-for-python
[ "tests/test_auth.py::TestServicePrincipalCredentials::test_msi_vm", "tests/test_auth.py::TestServicePrincipalCredentials::test_msi_vm_imds_no_retry_on_bad_error", "tests/test_auth.py::TestServicePrincipalCredentials::test_msi_vm_imds_retry" ]
[]
[ "tests/test_auth.py::TestServicePrincipalCredentials::test_adal_authentication", "tests/test_auth.py::TestServicePrincipalCredentials::test_check_state", "tests/test_auth.py::TestServicePrincipalCredentials::test_clear_token", "tests/test_auth.py::TestServicePrincipalCredentials::test_convert_token", "tests/test_auth.py::TestServicePrincipalCredentials::test_credentials_get_stored_auth", "tests/test_auth.py::TestServicePrincipalCredentials::test_credentials_retrieve_session", "tests/test_auth.py::TestServicePrincipalCredentials::test_http", "tests/test_auth.py::TestServicePrincipalCredentials::test_https", "tests/test_auth.py::TestServicePrincipalCredentials::test_service_principal", "tests/test_auth.py::TestServicePrincipalCredentials::test_store_token", "tests/test_auth.py::TestServicePrincipalCredentials::test_store_token_boom", "tests/test_auth.py::TestServicePrincipalCredentials::test_user_pass_credentials" ]
[]
MIT License
2,734
176
[ "msrestazure/azure_active_directory.py" ]
force-h2020__force-bdss-166
29c664514d096b9d3eb764b6167c2d77b7b129c6
2018-07-03 12:28:35
b568104378264a3c3d365f577a90820af50f0346
diff --git a/force_bdss/data_sources/base_data_source_model.py b/force_bdss/data_sources/base_data_source_model.py index d210f94..a5df537 100644 --- a/force_bdss/data_sources/base_data_source_model.py +++ b/force_bdss/data_sources/base_data_source_model.py @@ -1,4 +1,6 @@ -from traits.api import ABCHasStrictTraits, Instance, List, Event +from traits.api import ( + ABCHasStrictTraits, Instance, List, Event, on_trait_change +) from force_bdss.core.input_slot_info import InputSlotInfo from force_bdss.core.output_slot_info import OutputSlotInfo @@ -49,3 +51,10 @@ class BaseDataSourceModel(ABCHasStrictTraits): x.__getstate__() for x in self.output_slot_info ] return state + + @on_trait_change("+changes_slots") + def _trigger_changes_slots(self, obj, name, new): + changes_slots = self.traits()[name].changes_slots + + if changes_slots: + self.changes_slots = True
use traits metadata to indicate if a trait changes the slots. Currently we require users to bind the traits that can change the slots to a handler that invokes changes_slots event. We can achieve the same by requiring a metadata entry on those traits that change the slots, and implement the binding with the event in the base class.
force-h2020/force-bdss
diff --git a/force_bdss/data_sources/tests/test_base_data_source_model.py b/force_bdss/data_sources/tests/test_base_data_source_model.py index a9be54b..dde26ea 100644 --- a/force_bdss/data_sources/tests/test_base_data_source_model.py +++ b/force_bdss/data_sources/tests/test_base_data_source_model.py @@ -1,7 +1,10 @@ import unittest +from traits.api import Int +from traits.testing.api import UnittestTools from force_bdss.core.input_slot_info import InputSlotInfo from force_bdss.core.output_slot_info import OutputSlotInfo +from force_bdss.data_sources.base_data_source_model import BaseDataSourceModel from force_bdss.tests.dummy_classes.data_source import DummyDataSourceModel try: @@ -13,9 +16,18 @@ from force_bdss.data_sources.base_data_source_factory import \ BaseDataSourceFactory -class TestBaseDataSourceModel(unittest.TestCase): +class ChangesSlotsModel(BaseDataSourceModel): + a = Int() + b = Int(changes_slots=True) + c = Int(changes_slots=False) + + +class TestBaseDataSourceModel(unittest.TestCase, UnittestTools): + def setUp(self): + self.mock_factory = mock.Mock(spec=BaseDataSourceFactory) + def test_getstate(self): - model = DummyDataSourceModel(mock.Mock(spec=BaseDataSourceFactory)) + model = DummyDataSourceModel(self.mock_factory) self.assertEqual( model.__getstate__(), { @@ -64,3 +76,15 @@ class TestBaseDataSourceModel(unittest.TestCase): } ] }) + + def test_changes_slots(self): + model = ChangesSlotsModel(self.mock_factory) + + with self.assertTraitDoesNotChange(model, "changes_slots"): + model.a = 5 + + with self.assertTraitChanges(model, "changes_slots"): + model.b = 5 + + with self.assertTraitDoesNotChange(model, "changes_slots"): + model.c = 5
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": [], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
apptools==5.3.0 click==8.1.8 coverage==7.8.0 envisage==7.0.3 exceptiongroup==1.2.2 execnet==2.1.1 -e git+https://github.com/force-h2020/force-bdss.git@29c664514d096b9d3eb764b6167c2d77b7b129c6#egg=force_bdss importlib_metadata==8.6.1 iniconfig==2.1.0 packaging==24.2 pbr==6.1.1 pluggy==1.5.0 pyface==8.0.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 six==1.17.0 stevedore==5.4.1 tomli==2.2.1 traits==7.0.2 traitsui==8.0.0 typing_extensions==4.13.0 zipp==3.21.0
name: force-bdss channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - apptools==5.3.0 - click==8.1.8 - coverage==7.8.0 - envisage==7.0.3 - exceptiongroup==1.2.2 - execnet==2.1.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - packaging==24.2 - pbr==6.1.1 - pluggy==1.5.0 - pyface==8.0.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - six==1.17.0 - stevedore==5.4.1 - tomli==2.2.1 - traits==7.0.2 - traitsui==8.0.0 - typing-extensions==4.13.0 - zipp==3.21.0 prefix: /opt/conda/envs/force-bdss
[ "force_bdss/data_sources/tests/test_base_data_source_model.py::TestBaseDataSourceModel::test_changes_slots" ]
[ "force_bdss/data_sources/tests/test_base_data_source_model.py::TestBaseDataSourceModel::test_getstate" ]
[]
[]
BSD 2-Clause "Simplified" License
2,738
258
[ "force_bdss/data_sources/base_data_source_model.py" ]
mesonbuild__meson-3860
8cfb8fd02c86e1667ded9a7841d77204f96a4a6d
2018-07-09 18:17:21
4ff7b65f9be936ef406aa839958c1db991ba8272
diff --git a/mesonbuild/mesonmain.py b/mesonbuild/mesonmain.py index 1aca9c61a..011ac14b1 100644 --- a/mesonbuild/mesonmain.py +++ b/mesonbuild/mesonmain.py @@ -41,8 +41,8 @@ def create_parser(): help='Special wrap mode to use') p.add_argument('--profile-self', action='store_true', dest='profile', help=argparse.SUPPRESS) - p.add_argument('builddir', nargs='?', default='..') - p.add_argument('sourcedir', nargs='?', default='.') + p.add_argument('builddir', nargs='?', default=None) + p.add_argument('sourcedir', nargs='?', default=None) return p def wrapmodetype(string): @@ -331,6 +331,15 @@ def run(original_args, mainfile): dir1 = options.builddir dir2 = options.sourcedir try: + if dir1 is None: + if dir2 is None: + if not os.path.exists('meson.build') and os.path.exists('../meson.build'): + dir2 = '..' + else: + raise MesonException('Must specify at least one directory name.') + dir1 = os.getcwd() + if dir2 is None: + dir2 = os.getcwd() app = MesonApp(dir1, dir2, handshake, options) except Exception as e: # Log directory does not exist, so just print
Running `meson` in the source dir without any arguments takes the parent directory as the build dir This is a major regression over 0.46. The parent dir implicit selection should only be for finding the source directory, not the build directory.
mesonbuild/meson
diff --git a/run_unittests.py b/run_unittests.py index 4a47d5eab..df4603e3a 100755 --- a/run_unittests.py +++ b/run_unittests.py @@ -2406,6 +2406,24 @@ recommended as it is not supported on some platforms''') self.assertEqual(f.read().strip(), b'') self.assertRegex(out, r"DEPRECATION:.*\['array'\] is invalid.*dict") + def test_dirs(self): + with tempfile.TemporaryDirectory() as containing: + with tempfile.TemporaryDirectory(dir=containing) as srcdir: + mfile = os.path.join(srcdir, 'meson.build') + of = open(mfile, 'w') + of.write("project('foobar', 'c')\n") + of.close() + pc = subprocess.run(self.setup_command, + cwd=srcdir, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + self.assertIn(b'Must specify at least one directory name', pc.stdout) + with tempfile.TemporaryDirectory(dir=srcdir) as builddir: + subprocess.run(self.setup_command, + check=True, + cwd=builddir, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) class FailureTests(BasePlatformTests): '''
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.47
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y ninja-build" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/mesonbuild/meson.git@8cfb8fd02c86e1667ded9a7841d77204f96a4a6d#egg=meson packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: meson channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/meson
[ "run_unittests.py::AllPlatformTests::test_dirs" ]
[ "run_unittests.py::AllPlatformTests::test_absolute_prefix_libdir", "run_unittests.py::AllPlatformTests::test_always_prefer_c_compiler_for_asm", "run_unittests.py::AllPlatformTests::test_check_module_linking", "run_unittests.py::AllPlatformTests::test_compiler_detection", "run_unittests.py::AllPlatformTests::test_compiler_options_documented", "run_unittests.py::AllPlatformTests::test_default_options_prefix", "run_unittests.py::AllPlatformTests::test_preprocessor_checks_CPPFLAGS", "run_unittests.py::AllPlatformTests::test_templates", "run_unittests.py::FailureTests::test_boost_BOOST_ROOT_dependency", "run_unittests.py::FailureTests::test_boost_notfound_dependency", "run_unittests.py::FailureTests::test_dependency_invalid_method", "run_unittests.py::FailureTests::test_gnustep_notfound_dependency", "run_unittests.py::FailureTests::test_llvm_dependency", "run_unittests.py::FailureTests::test_sdl2_notfound_dependency", "run_unittests.py::FailureTests::test_using_recent_feature", "run_unittests.py::FailureTests::test_using_too_recent_feature", "run_unittests.py::FailureTests::test_using_too_recent_feature_dependency", "run_unittests.py::FailureTests::test_wx_notfound_dependency", "run_unittests.py::WindowsTests::test_find_program", "run_unittests.py::WindowsTests::test_rc_depends_files", "run_unittests.py::LinuxlikeTests::test_build_rpath", "run_unittests.py::LinuxlikeTests::test_compiler_check_flags_order", "run_unittests.py::LinuxlikeTests::test_compiler_cpp_stds", "run_unittests.py::LinuxlikeTests::test_cpp_std_override", "run_unittests.py::LinuxlikeTests::test_order_of_l_arguments", "run_unittests.py::LinuxArmCrossCompileTests::test_cflags_cross_environment_pollution", "run_unittests.py::LinuxArmCrossCompileTests::test_cross_file_overrides_always_args", "run_unittests.py::RewriterTests::test_basic", "run_unittests.py::RewriterTests::test_subdir" ]
[ "run_unittests.py::InternalTests::test_compiler_args_class", "run_unittests.py::InternalTests::test_extract_as_list", "run_unittests.py::InternalTests::test_find_library_patterns", "run_unittests.py::InternalTests::test_listify", "run_unittests.py::InternalTests::test_mode_symbolic_to_bits", "run_unittests.py::InternalTests::test_needs_exe_wrapper_override", "run_unittests.py::InternalTests::test_pkgconfig_module", "run_unittests.py::InternalTests::test_snippets", "run_unittests.py::InternalTests::test_string_templates_substitution", "run_unittests.py::InternalTests::test_version_number", "run_unittests.py::AllPlatformTests::test_all_forbidden_targets_tested", "run_unittests.py::AllPlatformTests::test_array_option_bad_change", "run_unittests.py::AllPlatformTests::test_array_option_change", "run_unittests.py::AllPlatformTests::test_array_option_empty_equivalents", "run_unittests.py::AllPlatformTests::test_build_by_default", "run_unittests.py::AllPlatformTests::test_command_line", "run_unittests.py::AllPlatformTests::test_compiler_run_command", "run_unittests.py::AllPlatformTests::test_configure_file_warnings", "run_unittests.py::AllPlatformTests::test_conflicting_d_dash_option", "run_unittests.py::AllPlatformTests::test_cpu_families_documented", "run_unittests.py::AllPlatformTests::test_cross_file_system_paths", "run_unittests.py::AllPlatformTests::test_custom_target_changes_cause_rebuild", "run_unittests.py::AllPlatformTests::test_custom_target_exe_data_deterministic", "run_unittests.py::AllPlatformTests::test_dash_d_dedup", "run_unittests.py::AllPlatformTests::test_default_options_prefix_dependent_defaults", "run_unittests.py::AllPlatformTests::test_dist_git", "run_unittests.py::AllPlatformTests::test_dist_hg", "run_unittests.py::AllPlatformTests::test_feature_check_usage_subprojects", "run_unittests.py::AllPlatformTests::test_flock", "run_unittests.py::AllPlatformTests::test_forcefallback", "run_unittests.py::AllPlatformTests::test_free_stringarray_setting", "run_unittests.py::AllPlatformTests::test_guessed_linker_dependencies", "run_unittests.py::AllPlatformTests::test_identical_target_name_in_subdir_flat_layout", "run_unittests.py::AllPlatformTests::test_identical_target_name_in_subproject_flat_layout", "run_unittests.py::AllPlatformTests::test_install_introspection", "run_unittests.py::AllPlatformTests::test_internal_include_order", "run_unittests.py::AllPlatformTests::test_libdir_must_be_inside_prefix", "run_unittests.py::AllPlatformTests::test_markdown_files_in_sitemap", "run_unittests.py::AllPlatformTests::test_ndebug_if_release_disabled", "run_unittests.py::AllPlatformTests::test_ndebug_if_release_enabled", "run_unittests.py::AllPlatformTests::test_permitted_method_kwargs", "run_unittests.py::AllPlatformTests::test_prebuilt_object", "run_unittests.py::AllPlatformTests::test_prebuilt_shared_lib", "run_unittests.py::AllPlatformTests::test_prebuilt_static_lib", "run_unittests.py::AllPlatformTests::test_prefix_dependent_defaults", "run_unittests.py::AllPlatformTests::test_rpath_uses_ORIGIN", "run_unittests.py::AllPlatformTests::test_run_target_files_path", "run_unittests.py::AllPlatformTests::test_same_d_option_twice", "run_unittests.py::AllPlatformTests::test_same_d_option_twice_configure", "run_unittests.py::AllPlatformTests::test_same_dash_option_twice", "run_unittests.py::AllPlatformTests::test_same_dash_option_twice_configure", "run_unittests.py::AllPlatformTests::test_same_project_d_option_twice", "run_unittests.py::AllPlatformTests::test_same_project_d_option_twice_configure", "run_unittests.py::AllPlatformTests::test_source_changes_cause_rebuild", "run_unittests.py::AllPlatformTests::test_static_compile_order", "run_unittests.py::AllPlatformTests::test_static_library_lto", "run_unittests.py::AllPlatformTests::test_static_library_overwrite", "run_unittests.py::AllPlatformTests::test_subproject_promotion", "run_unittests.py::AllPlatformTests::test_suite_selection", "run_unittests.py::AllPlatformTests::test_testsetup_selection", "run_unittests.py::AllPlatformTests::test_uninstall", "run_unittests.py::AllPlatformTests::test_warning_location", "run_unittests.py::FailureTests::test_dict_forbids_duplicate_keys", "run_unittests.py::FailureTests::test_dict_forbids_integer_key", "run_unittests.py::FailureTests::test_dict_requires_key_value_pairs", "run_unittests.py::FailureTests::test_exception_exit_status", "run_unittests.py::FailureTests::test_objc_cpp_detection", "run_unittests.py::FailureTests::test_subproject_variables", "run_unittests.py::LinuxlikeTests::test_basic_soname", "run_unittests.py::LinuxlikeTests::test_compiler_c_stds", "run_unittests.py::LinuxlikeTests::test_cross_find_program", "run_unittests.py::LinuxlikeTests::test_custom_soname", "run_unittests.py::LinuxlikeTests::test_install_umask", "run_unittests.py::LinuxlikeTests::test_installed_modes", "run_unittests.py::LinuxlikeTests::test_installed_modes_extended", "run_unittests.py::LinuxlikeTests::test_installed_soname", "run_unittests.py::LinuxlikeTests::test_pch_with_address_sanitizer", "run_unittests.py::LinuxlikeTests::test_pic", "run_unittests.py::LinuxlikeTests::test_pkg_unfound", "run_unittests.py::LinuxlikeTests::test_reconfigure", "run_unittests.py::LinuxlikeTests::test_run_installed", "run_unittests.py::LinuxlikeTests::test_soname", "run_unittests.py::LinuxlikeTests::test_unity_subproj" ]
[]
Apache License 2.0
2,753
360
[ "mesonbuild/mesonmain.py" ]
ELIFE-ASU__Neet-114
5a45a92c1b3a564290487ecc1483b4866e26eaf5
2018-07-09 19:03:36
5a45a92c1b3a564290487ecc1483b4866e26eaf5
diff --git a/neet/synchronous.py b/neet/synchronous.py index 1c6ed88..8f59454 100644 --- a/neet/synchronous.py +++ b/neet/synchronous.py @@ -35,7 +35,7 @@ def trajectory(net, state, timesteps=1, encode=False): :param state: the network state :param timesteps: the number of steps in the trajectory :param encode: encode the states as integers - :yields: the next state in the trajectory + :returns: the trajectory as a list :raises TypeError: if net is not a network :raises ValueError: if ``timesteps < 1`` """ @@ -44,6 +44,7 @@ def trajectory(net, state, timesteps=1, encode=False): if timesteps < 1: raise ValueError("number of steps must be positive, non-zero") + traj = [] state = copy.copy(state) if encode: if is_fixed_sized(net): @@ -51,23 +52,24 @@ def trajectory(net, state, timesteps=1, encode=False): else: state_space = net.state_space(len(state)) - yield state_space._unsafe_encode(state) + traj.append(state_space._unsafe_encode(state)) net.update(state) - yield state_space._unsafe_encode(state) + traj.append(state_space._unsafe_encode(state)) for _ in range(1,timesteps): net._unsafe_update(state) - yield state_space._unsafe_encode(state) + traj.append(state_space._unsafe_encode(state)) else: - yield copy.copy(state) + traj.append(copy.copy(state)) net.update(state) - yield copy.copy(state) + traj.append(copy.copy(state)) for _ in range(1, timesteps): net._unsafe_update(state) - yield copy.copy(state) + traj.append(copy.copy(state)) + return traj def transitions(net, size=None, encode=False): """ @@ -94,7 +96,7 @@ def transitions(net, size=None, encode=False): :param net: the network :param size: the size of the network (``None`` if fixed sized) :param encode: encode the states as integers - :yields: the one-state transitions + :returns: the one-state transitions as an array :raises TypeError: if ``net`` is not a network :raises ValueError: if ``net`` is fixed sized and ``size`` is not ``None`` :raises ValueError: if ``net`` is not fixed sized and ``size`` is ``None`` @@ -111,12 +113,15 @@ def transitions(net, size=None, encode=False): raise ValueError("size must not be None for variable sized networks") state_space = net.state_space(size) + trans = [] for state in state_space: net._unsafe_update(state) if encode: - yield state_space._unsafe_encode(state) + trans.append(state_space._unsafe_encode(state)) else: - yield state + trans.append(state) + + return trans def transition_graph(net, size=None): """ @@ -172,15 +177,14 @@ def attractors(net, size=None): :param net: the network or the transition graph :param size: the size of the network (``None`` if fixed sized) - :returns: a generator of attractors + :returns: a list of attractor cycles :raises TypeError: if ``net`` is not a network or a ``networkx.DiGraph`` :raises ValueError: if ``net`` is fixed sized and ``size`` is not ``None`` :raises ValueError: if ``net`` is a transition graph and ``size`` is not ``None`` :raises ValueError: if ``net`` is not fixed sized and ``size`` is ``None`` """ if isinstance(net, nx.DiGraph): - for attr in nx.simple_cycles(net): - yield attr + return list(nx.simple_cycles(net)) elif not is_network(net): raise TypeError("net must be a network or a networkx DiGraph") elif is_fixed_sized(net) and size is not None: @@ -188,6 +192,7 @@ def attractors(net, size=None): elif not is_fixed_sized(net) and size is None: raise ValueError("variable sized networks require a size") else: + cycles = [] # Get the state transitions # (array of next state indexed by current state) trans = list(transitions(net, size=size, encode=True)) @@ -259,7 +264,8 @@ def attractors(net, size=None): # Yield the cycle if we found one if len(cycle) != 0: - yield cycle + cycles.append(cycle) + return cycles def basins(net, size=None): """
Death to Generators Generators are great when you may have to iterate over computations that are too large to store in memory. This is certainly a possibility for much of Neet's algorithms. It was for this reason that @dglmoore over-engineered Neet's functions to `yield` instead of `return` where possible. While it may seem like this is a good thing, it is really just cumbersome for users, implementers and maintainers. The problem it aimed to solve is a non-issue as most of the time there are computational limits other than memory that come into play around the same time as memory issues. We should refactor to use lists in place of generators unless it makes sense to do otherwise.
ELIFE-ASU/Neet
diff --git a/test/test_synchronous.py b/test/test_synchronous.py index ec1bb85..eed14a2 100644 --- a/test/test_synchronous.py +++ b/test/test_synchronous.py @@ -20,13 +20,13 @@ class TestSynchronous(unittest.TestCase): ``trajectory`` should raise a type error if ``net`` is not a network """ with self.assertRaises(TypeError): - list(trajectory(5, [1, 2, 3])) + trajectory(5, [1, 2, 3]) with self.assertRaises(TypeError): - list(trajectory(MockObject(), [1, 2, 3])) + trajectory(MockObject(), [1, 2, 3]) with self.assertRaises(TypeError): - list(trajectory(MockFixedSizedNetwork, [1, 2, 3])) + trajectory(MockFixedSizedNetwork, [1, 2, 3]) def test_trajectory_too_short(self): """ @@ -34,10 +34,10 @@ class TestSynchronous(unittest.TestCase): than 1 """ with self.assertRaises(ValueError): - list(trajectory(MockFixedSizedNetwork(), [1, 2, 3], timesteps=0)) + trajectory(MockFixedSizedNetwork(), [1, 2, 3], timesteps=0) with self.assertRaises(ValueError): - list(trajectory(MockFixedSizedNetwork(), [1, 2, 3], timesteps=-1)) + trajectory(MockFixedSizedNetwork(), [1, 2, 3], timesteps=-1) def test_trajectory_eca(self): """ @@ -45,14 +45,14 @@ class TestSynchronous(unittest.TestCase): """ rule30 = ECA(30) with self.assertRaises(ValueError): - list(trajectory(rule30, [])) + trajectory(rule30, []) xs = [0, 1, 0] - got = list(trajectory(rule30, xs)) + got = trajectory(rule30, xs) self.assertEqual([0, 1, 0], xs) self.assertEqual([[0, 1, 0], [1, 1, 1]], got) - got = list(trajectory(rule30, xs, timesteps=2)) + got = trajectory(rule30, xs, timesteps=2) self.assertEqual([0, 1, 0], xs) self.assertEqual([[0, 1, 0], [1, 1, 1], [0, 0, 0]], got) @@ -62,14 +62,14 @@ class TestSynchronous(unittest.TestCase): """ rule30 = ECA(30) with self.assertRaises(ValueError): - list(trajectory(rule30, [], encode=True)) + trajectory(rule30, [], encode=True) state = [0, 1, 0] - got = list(trajectory(rule30, state, encode=True)) + got = trajectory(rule30, state, encode=True) self.assertEqual([0, 1, 0], state) self.assertEqual([2, 7], got) - got = list(trajectory(rule30, state, timesteps=2, encode=True)) + got = trajectory(rule30, state, timesteps=2, encode=True) self.assertEqual([0, 1, 0], state) self.assertEqual([2, 7, 0], got) @@ -84,11 +84,11 @@ class TestSynchronous(unittest.TestCase): ) state = [0, 0] - got = list(trajectory(net, state)) + got = trajectory(net, state) self.assertEqual([0, 0], state) self.assertEqual([[0, 0], [0, 1]], got) - got = list(trajectory(net, state, timesteps=3)) + got = trajectory(net, state, timesteps=3) self.assertEqual([0, 0], state) self.assertEqual([[0, 0], [0, 1], [0, 1], [0, 1]], got) @@ -103,11 +103,11 @@ class TestSynchronous(unittest.TestCase): ) state = [0, 0] - got = list(trajectory(net, state, encode=True)) + got = trajectory(net, state, encode=True) self.assertEqual([0, 0], state) self.assertEqual([0, 2], got) - got = list(trajectory(net, state, timesteps=3, encode=True)) + got = trajectory(net, state, timesteps=3, encode=True) self.assertEqual([0, 0], state) self.assertEqual([0, 2, 2, 2], got) @@ -119,7 +119,7 @@ class TestSynchronous(unittest.TestCase): ((0, 2), {'01', '10', '11'}), ((0, 1), {'11'})]) state = [0, 1, 0] - got = list(trajectory(net, state, 3)) + got = trajectory(net, state, 3) self.assertEqual([[0, 1, 0], [1, 0, 0], [0, 1, 0], [1, 0, 0]], got) self.assertEqual([0, 1, 0], state) @@ -131,7 +131,7 @@ class TestSynchronous(unittest.TestCase): ``transitions`` should raise a type error if ``net`` is not a network """ with self.assertRaises(TypeError): - list(transitions(MockObject(), 5)) + transitions(MockObject(), 5) def test_transitions_not_fixed_sized(self): """ @@ -139,7 +139,7 @@ class TestSynchronous(unittest.TestCase): and ``size`` is ``None`` """ with self.assertRaises(ValueError): - list(transitions(ECA(30), size=None)) + transitions(ECA(30), size=None) def test_transitions_fixed_sized(self): """ @@ -147,7 +147,7 @@ class TestSynchronous(unittest.TestCase): ``size`` is not ``None`` """ with self.assertRaises(ValueError): - list(transitions(MockFixedSizedNetwork, size=3)) + transitions(MockFixedSizedNetwork, size=3) def test_transitions_eca(self): """ @@ -155,13 +155,13 @@ class TestSynchronous(unittest.TestCase): """ rule30 = ECA(30) - got = list(transitions(rule30, size=1)) + got = transitions(rule30, size=1) self.assertEqual([[0], [0]], got) - got = list(transitions(rule30, size=2)) + got = transitions(rule30, size=2) self.assertEqual([[0, 0], [1, 0], [0, 1], [0, 0]], got) - got = list(transitions(rule30, size=3)) + got = transitions(rule30, size=3) self.assertEqual([[0, 0, 0], [1, 1, 1], [1, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [0, 1, 0], [0, 0, 0]], got) @@ -171,13 +171,13 @@ class TestSynchronous(unittest.TestCase): """ rule30 = ECA(30) - got = list(transitions(rule30, size=1, encode=True)) + got = transitions(rule30, size=1, encode=True) self.assertEqual([0, 0], got) - got = list(transitions(rule30, size=2, encode=True)) + got = transitions(rule30, size=2, encode=True) self.assertEqual([0, 1, 2, 0], got) - got = list(transitions(rule30, size=3, encode=True)) + got = transitions(rule30, size=3, encode=True) self.assertEqual([0, 7, 7, 1, 7, 4, 2, 0], got) def test_transitions_wtnetwork(self): @@ -190,7 +190,7 @@ class TestSynchronous(unittest.TestCase): theta=WTNetwork.positive_threshold ) - got = list(transitions(net)) + got = transitions(net) self.assertEqual([[0, 1], [1, 0], [0, 1], [1, 1]], got) def test_transitions_wtnetwork_encoded(self): @@ -203,7 +203,7 @@ class TestSynchronous(unittest.TestCase): theta=WTNetwork.positive_threshold ) - got = list(transitions(net, encode=True)) + got = transitions(net, encode=True) self.assertEqual([2, 1, 2, 3], got) def test_transitions_logicnetwork(self): @@ -211,7 +211,7 @@ class TestSynchronous(unittest.TestCase): test `transitions` on `LogicNetwork`s """ net = LogicNetwork([((1,), {'0', '1'}), ((0,), {'1'})]) - got = list(transitions(net)) + got = transitions(net) self.assertEqual([[1, 0], [1, 1], [1, 0], [1, 1]], got) def test_transitions_logicnetwork_encoded(self): @@ -219,7 +219,7 @@ class TestSynchronous(unittest.TestCase): test `transitions` on `LogicNetwork`s, states encoded """ net = LogicNetwork([((1,), {'0', '1'}), ((0,), {'1'})]) - got = list(transitions(net, encode=True)) + got = transitions(net, encode=True) self.assertEqual([1, 3, 1, 3], got) def test_transition_graph_not_network(self): @@ -268,13 +268,13 @@ class TestSynchronous(unittest.TestCase): nor a networkx digraph """ with self.assertRaises(TypeError): - list(attractors('blah')) + attractors('blah') with self.assertRaises(TypeError): - list(attractors(MockObject())) + attractors(MockObject()) with self.assertRaises(TypeError): - list(attractors(nx.Graph())) + attractors(nx.Graph()) def test_attractors_variable_sized(self): """ @@ -282,7 +282,7 @@ class TestSynchronous(unittest.TestCase): network and ``size`` is ``None`` """ with self.assertRaises(ValueError): - list(attractors(ECA(30), size=None)) + attractors(ECA(30), size=None) def test_attractors_fixed_sized(self): """ @@ -290,10 +290,10 @@ class TestSynchronous(unittest.TestCase): network or a networkx digraph, and ``size`` is not ``None`` """ with self.assertRaises(ValueError): - list(attractors(MockFixedSizedNetwork(), size=5)) + attractors(MockFixedSizedNetwork(), size=5) # with self.assertRaises(ValueError): - # list(attractors(nx.DiGraph(), size=5)) + # attractors(nx.DiGraph(), size=5) def test_attractors_eca(self): """ @@ -304,7 +304,7 @@ class TestSynchronous(unittest.TestCase): (ECA(110), 3, 1), (ECA(110), 4, 3), (ECA(110), 5, 1), (ECA(110), 6, 3)] for rule, width, size in networks: - self.assertEqual(size, len(list(attractors(rule, width)))) + self.assertEqual(size, len(attractors(rule, width))) def test_attractors_wtnetworks(self): """ @@ -312,14 +312,14 @@ class TestSynchronous(unittest.TestCase): """ networks = [(s_pombe, 13), (s_cerevisiae, 7), (c_elegans, 5)] for net, size in networks: - self.assertEqual(size, len(list(attractors(net)))) + self.assertEqual(size, len(attractors(net))) def test_attractors_transition_graph(self): """ test ``attractors`` on ``s_pombe`` transition graph """ - att_from_graph = list(attractors(transition_graph(s_pombe))) - att_from_network = list(attractors(s_pombe)) + att_from_graph = attractors(transition_graph(s_pombe)) + att_from_network = attractors(s_pombe) for (a, b) in zip(att_from_graph, att_from_network): a.sort()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==4.4.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/ELIFE-ASU/Neet.git@5a45a92c1b3a564290487ecc1483b4866e26eaf5#egg=neet networkx==2.5.1 nose==1.3.7 numpy==1.19.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyinform==0.2.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: Neet channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==4.4.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - networkx==2.5.1 - nose==1.3.7 - numpy==1.19.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyinform==0.2.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/Neet
[ "test/test_synchronous.py::TestSynchronous::test_attractors_eca", "test/test_synchronous.py::TestSynchronous::test_attractors_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_attractors_invalid_net", "test/test_synchronous.py::TestSynchronous::test_attractors_transition_graph", "test/test_synchronous.py::TestSynchronous::test_attractors_variable_sized", "test/test_synchronous.py::TestSynchronous::test_attractors_wtnetworks", "test/test_synchronous.py::TestSynchronous::test_trajectory_eca", "test/test_synchronous.py::TestSynchronous::test_trajectory_eca_encoded", "test/test_synchronous.py::TestSynchronous::test_trajectory_logicnetwork", "test/test_synchronous.py::TestSynchronous::test_trajectory_not_network", "test/test_synchronous.py::TestSynchronous::test_trajectory_too_short", "test/test_synchronous.py::TestSynchronous::test_trajectory_wtnetwork", "test/test_synchronous.py::TestSynchronous::test_trajectory_wtnetwork_encoded", "test/test_synchronous.py::TestSynchronous::test_transitions_eca", "test/test_synchronous.py::TestSynchronous::test_transitions_eca_encoded", "test/test_synchronous.py::TestSynchronous::test_transitions_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_transitions_logicnetwork", "test/test_synchronous.py::TestSynchronous::test_transitions_logicnetwork_encoded", "test/test_synchronous.py::TestSynchronous::test_transitions_not_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_transitions_not_network", "test/test_synchronous.py::TestSynchronous::test_transitions_wtnetwork", "test/test_synchronous.py::TestSynchronous::test_transitions_wtnetwork_encoded" ]
[ "test/test_synchronous.py::TestSynchronous::test_basin_entropy_eca", "test/test_synchronous.py::TestSynchronous::test_basin_entropy_transition_graph", "test/test_synchronous.py::TestSynchronous::test_basin_entropy_wtnetwork", "test/test_synchronous.py::TestSynchronous::test_basin_entropy_wtnetwork_base10", "test/test_synchronous.py::TestSynchronous::test_basins_eca", "test/test_synchronous.py::TestSynchronous::test_basins_transition_graph", "test/test_synchronous.py::TestSynchronous::test_basins_wtnetwork" ]
[ "test/test_synchronous.py::TestSynchronous::test_basin_entropy_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_basin_entropy_invalid_net", "test/test_synchronous.py::TestSynchronous::test_basin_entropy_variable_sized", "test/test_synchronous.py::TestSynchronous::test_basins_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_basins_invalid_net", "test/test_synchronous.py::TestSynchronous::test_basins_variable_sized", "test/test_synchronous.py::TestSynchronous::test_timeseries_eca", "test/test_synchronous.py::TestSynchronous::test_timeseries_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_timeseries_not_network", "test/test_synchronous.py::TestSynchronous::test_timeseries_too_short", "test/test_synchronous.py::TestSynchronous::test_timeseries_variable_sized", "test/test_synchronous.py::TestSynchronous::test_timeseries_wtnetworks", "test/test_synchronous.py::TestSynchronous::test_transition_graph_eca", "test/test_synchronous.py::TestSynchronous::test_transition_graph_fixed_sized", "test/test_synchronous.py::TestSynchronous::test_transition_graph_not_network", "test/test_synchronous.py::TestSynchronous::test_transition_graph_s_pombe", "test/test_synchronous.py::TestSynchronous::test_transition_graph_variable_sized", "test/test_synchronous.py::TestLandscape::test_attractor_lengths", "test/test_synchronous.py::TestLandscape::test_attractors_eca", "test/test_synchronous.py::TestLandscape::test_attractors_wtnetworks", "test/test_synchronous.py::TestLandscape::test_basin_entropy_eca", "test/test_synchronous.py::TestLandscape::test_basin_entropy_wtnetwork", "test/test_synchronous.py::TestLandscape::test_basin_sizes", "test/test_synchronous.py::TestLandscape::test_basins_eca", "test/test_synchronous.py::TestLandscape::test_canary", "test/test_synchronous.py::TestLandscape::test_graph_eca", "test/test_synchronous.py::TestLandscape::test_graph_wtnetworks", "test/test_synchronous.py::TestLandscape::test_heights", "test/test_synchronous.py::TestLandscape::test_in_degree", "test/test_synchronous.py::TestLandscape::test_init_fixed_sized", "test/test_synchronous.py::TestLandscape::test_init_not_fixed_sized", "test/test_synchronous.py::TestLandscape::test_init_not_network", "test/test_synchronous.py::TestLandscape::test_is_state_space", "test/test_synchronous.py::TestLandscape::test_recurrence_times", "test/test_synchronous.py::TestLandscape::test_timeseries_eca", "test/test_synchronous.py::TestLandscape::test_timeseries_too_short", "test/test_synchronous.py::TestLandscape::test_timeseries_wtnetworks", "test/test_synchronous.py::TestLandscape::test_trajectory_eca", "test/test_synchronous.py::TestLandscape::test_trajectory_logicnetwork", "test/test_synchronous.py::TestLandscape::test_trajectory_too_short", "test/test_synchronous.py::TestLandscape::test_trajectory_wtnetwork", "test/test_synchronous.py::TestLandscape::test_transitions_eca", "test/test_synchronous.py::TestLandscape::test_transitions_logicnetwork", "test/test_synchronous.py::TestLandscape::test_transitions_spombe", "test/test_synchronous.py::TestLandscape::test_transitions_wtnetwork" ]
[]
MIT License
2,755
1,115
[ "neet/synchronous.py" ]
PlasmaPy__PlasmaPy-510
d22b5a2d70a10c0e8e145c096cc691450c6a0f05
2018-07-10 07:31:43
24113f1659d809930288374f6b1f95dc573aff47
diff --git a/plasmapy/atomic/particle_class.py b/plasmapy/atomic/particle_class.py index 0a5d2c92..b7e7ed5c 100644 --- a/plasmapy/atomic/particle_class.py +++ b/plasmapy/atomic/particle_class.py @@ -658,6 +658,42 @@ def element_name(self) -> str: raise InvalidElementError(_category_errmsg(self, 'element')) return self._attributes['element name'] + @property + def isotope_name(self) -> str: + """ + Return the name of the element along with the isotope + symbol if the particle corresponds to an isotope, and + `None` otherwise. + + If the particle is not a valid element, then this + attribute will raise an `~plasmapy.utils.InvalidElementError`. + If it is not an isotope, then this attribute will raise an + `~plasmapy.utils.InvalidIsotopeError`. + + Examples + -------- + >>> deuterium = Particle("D") + >>> deuterium.isotope_name + 'deuterium' + >>> iron_isotope = Particle("Fe-56", Z=16) + >>> iron_isotope.isotope_name + 'iron-56' + + """ + if not self.element: + raise InvalidElementError(_category_errmsg(self.particle, 'element')) + elif not self.isotope: + raise InvalidIsotopeError(_category_errmsg(self, 'isotope')) + + if self.isotope == "D": + isotope_name = "deuterium" + elif self.isotope == "T": + isotope_name = "tritium" + else: + isotope_name = f"{self.element_name}-{self.mass_number}" + + return isotope_name + @property def integer_charge(self) -> int: """
Add an `isotope_name` attribute on `Particle` class > We could definitely add an `isotope_name` attribute as well, which for isotopes in general would return something like `'iodine-131'` plus `'deuterium'` and `'tritium'` for those special cases. The `element` and `element_name` attributes just return the name of the element without respect to the isotope. I'll try to remember to create a separate issue for this. [as mentioned here](https://github.com/PlasmaPy/PlasmaPy/pull/468/files#r189747292) by @namurphy.
PlasmaPy/PlasmaPy
diff --git a/plasmapy/atomic/tests/test_particle_class.py b/plasmapy/atomic/tests/test_particle_class.py index 17558a58..9d3308e0 100644 --- a/plasmapy/atomic/tests/test_particle_class.py +++ b/plasmapy/atomic/tests/test_particle_class.py @@ -31,6 +31,7 @@ {'particle': 'n', 'element': None, 'isotope': None, + 'isotope_name': InvalidElementError, 'ionic_symbol': None, 'roman_symbol': None, 'is_ion': False, @@ -51,6 +52,7 @@ 'element': 'H', 'element_name': 'hydrogen', 'isotope': 'H-1', + 'isotope_name': 'hydrogen-1', 'ionic_symbol': 'p+', 'roman_symbol': 'H-1 II', 'is_ion': True, @@ -85,6 +87,7 @@ 'element': None, 'element_name': InvalidElementError, 'isotope': None, + 'isotope_name': InvalidElementError, 'ionic_symbol': None, 'roman_symbol': None, 'is_ion': False, @@ -106,6 +109,7 @@ 'element': None, 'element_name': InvalidElementError, 'isotope': None, + 'isotope_name': InvalidElementError, 'ionic_symbol': None, 'roman_symbol': None, 'is_ion': False, @@ -129,6 +133,7 @@ {'particle': 'e+', 'element': None, 'isotope': None, + 'isotope_name': InvalidElementError, 'ionic_symbol': None, 'roman_symbol': None, 'is_ion': False, @@ -156,6 +161,7 @@ {'particle': 'H', 'element': 'H', 'isotope': None, + 'isotope_name': InvalidIsotopeError, 'ionic_symbol': None, 'roman_symbol': ChargeError, 'is_ion': False, @@ -177,6 +183,7 @@ {'particle': 'H 1-', 'element': 'H', 'isotope': None, + 'isotope_name': InvalidIsotopeError, 'ionic_symbol': 'H 1-', 'roman_symbol': roman.OutOfRangeError, 'is_ion': True, @@ -196,6 +203,7 @@ 'particle': 'H-1 0+', 'element': 'H', 'isotope': 'H-1', + 'isotope_name': 'hydrogen-1', 'ionic_symbol': 'H-1 0+', 'roman_symbol': 'H-1 I', 'is_ion': False, @@ -218,6 +226,7 @@ 'element': 'H', 'element_name': 'hydrogen', 'isotope': 'D', + 'isotope_name': 'deuterium', 'ionic_symbol': 'D 1+', 'roman_symbol': 'D II', 'is_ion': True, @@ -238,6 +247,7 @@ {'particle': 'T 1+', 'element': 'H', 'isotope': 'T', + 'isotope_name': 'tritium', 'ionic_symbol': 'T 1+', 'roman_symbol': 'T II', 'is_ion': True, @@ -257,6 +267,7 @@ 'element': 'Fe', 'element_name': 'iron', 'isotope': 'Fe-56', + 'isotope_name': 'iron-56', 'ionic_symbol': 'Fe-56 17+', 'roman_symbol': 'Fe-56 XVIII', 'is_electron': False, @@ -277,6 +288,7 @@ 'element': 'He', 'element_name': 'helium', 'isotope': 'He-4', + 'isotope_name': 'helium-4', 'ionic_symbol': 'He-4 2+', 'roman_symbol': 'He-4 III', 'is_ion': True, @@ -293,6 +305,7 @@ 'element': 'Li', 'element_name': 'lithium', 'isotope': 'Li-7', + 'isotope_name': 'lithium-7', 'ionic_symbol': None, 'roman_symbol': ChargeError, 'is_ion': False, @@ -309,6 +322,7 @@ {'particle': 'Cn-276 22+', 'element': 'Cn', 'isotope': 'Cn-276', + 'isotope_name': 'copernicium-276', 'ionic_symbol': 'Cn-276 22+', 'roman_symbol': 'Cn-276 XXIII', 'is_ion': True, @@ -324,6 +338,7 @@ {'particle': 'mu-', 'element': None, 'isotope': None, + 'isotope_name': InvalidElementError, 'ionic_symbol': None, 'roman_symbol': None, 'is_ion': False, @@ -338,6 +353,7 @@ {'particle': 'nu_tau', 'element': None, 'isotope': None, + 'isotope_name': InvalidElementError, 'mass': MissingAtomicDataError, 'integer_charge': 0, 'mass_number': InvalidIsotopeError,
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[optional]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asteval==0.9.31 astropy==4.3.1 certifi @ file:///croot/certifi_1671487769961/work/certifi colorama==0.4.6 cycler==0.11.0 Cython==3.0.12 exceptiongroup==1.2.2 fonttools==4.38.0 future==1.0.0 h5py==3.8.0 importlib-metadata==6.7.0 iniconfig==2.0.0 kiwisolver==1.4.5 lmfit==1.2.2 matplotlib==3.5.3 mpmath==1.3.0 numpy==1.21.6 packaging==24.0 Pillow==9.5.0 -e git+https://github.com/PlasmaPy/PlasmaPy.git@d22b5a2d70a10c0e8e145c096cc691450c6a0f05#egg=plasmapy pluggy==1.2.0 pyerfa==2.0.0.3 pyparsing==3.1.4 pytest==7.4.4 python-dateutil==2.9.0.post0 roman==4.2 scipy==1.7.3 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 uncertainties==3.1.7 zipp==3.15.0
name: PlasmaPy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - asteval==0.9.31 - astropy==4.3.1 - colorama==0.4.6 - cycler==0.11.0 - cython==3.0.12 - exceptiongroup==1.2.2 - fonttools==4.38.0 - future==1.0.0 - h5py==3.8.0 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - kiwisolver==1.4.5 - lmfit==1.2.2 - matplotlib==3.5.3 - mpmath==1.3.0 - numpy==1.21.6 - packaging==24.0 - pillow==9.5.0 - pluggy==1.2.0 - pyerfa==2.0.0.3 - pyparsing==3.1.4 - pytest==7.4.4 - python-dateutil==2.9.0.post0 - roman==4.2 - scipy==1.7.3 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - uncertainties==3.1.7 - zipp==3.15.0 prefix: /opt/conda/envs/PlasmaPy
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[neutron-kwargs0-expected_dict0]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[p+-kwargs1-expected_dict1]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[p--kwargs2-expected_dict2]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[e--kwargs3-expected_dict3]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[e+-kwargs4-expected_dict4]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H-kwargs5-expected_dict5]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H-1", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[D+-kwargs8-expected_dict8]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[tritium-kwargs9-expected_dict9]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Fe-kwargs10-expected_dict10]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[alpha-kwargs11-expected_dict11]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Cn-276-kwargs13-expected_dict13]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[muon-kwargs14-expected_dict14]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[nu_tau-kwargs15-expected_dict15]" ]
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Li-kwargs12-expected_dict12]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[a-kwargs0--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[d+-kwargs1--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[H-kwargs2--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-818-kwargs3--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-12-kwargs4--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-kwargs5--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-kwargs6--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs7--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs8-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[alpha-kwargs9-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Fe-56-kwargs10-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs11-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[tau--kwargs12-.element_name-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[tau+-kwargs13-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[neutron-kwargs14-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[H-kwargs15-.mass_number-InvalidIsotopeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[neutron-kwargs16-.mass_number-InvalidIsotopeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[He-kwargs17-.charge-ChargeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[He-kwargs18-.integer_charge-ChargeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Fe-kwargs19-.spin-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[nu_e-kwargs20-.mass-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Og-kwargs21-.standard_atomic_weight-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[arg22-kwargs22--TypeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[H-----kwargs0--AtomicWarning]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[alpha-kwargs1--AtomicWarning]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[alpha-kwargs2--AtomicWarning]" ]
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles0]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles1]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles2]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles3]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles4]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles5]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles6]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles7]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles8]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles9]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles10]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_cmp", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[n-neutron]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[p+-proton]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[H-1-p+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[H-1", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[D-D+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[T-T+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[He-4-alpha]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[Fe-56-Fe-56", "plasmapy/atomic/tests/test_particle_class.py::test_particle_half_life_string", "plasmapy/atomic/tests/test_particle_class.py::test_particle_is_electron[Particle(\"e-\")-True]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_is_electron[Particle(\"p+\")-False]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_bool_error", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[p+-p-]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[n-antineutron]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[e--e+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[mu--mu+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[tau--tau+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_e-anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_mu-anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_tau-anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[p+-p-]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[n-antineutron]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[e--e+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[mu--mu+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[tau--tau+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_e-anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_mu-anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_tau-anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::test_unary_operator_for_elements", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_e]" ]
[]
BSD 3-Clause "New" or "Revised" License
2,756
455
[ "plasmapy/atomic/particle_class.py" ]
conan-io__conan-3187
c3baafb780b6e5498f8bd460426901d9d5ab10e1
2018-07-10 10:30:23
f59b0d5773ca17e222236b1b6b55785f03539216
diff --git a/.ci/jenkins/conf.py b/.ci/jenkins/conf.py index f59d4441e..02c9bc118 100644 --- a/.ci/jenkins/conf.py +++ b/.ci/jenkins/conf.py @@ -9,7 +9,7 @@ winpylocation = {"py27": "C:\\Python27\\python.exe", macpylocation = {"py27": "/usr/bin/python", # /Users/jenkins_ci/.pyenv/versions/2.7.11/bin/python", "py34": "/Users/jenkins_ci/.pyenv/versions/3.4.7/bin/python", - "py36": "/Users/jenkins_ci/.pyenv/versions/3.6.3/bin/python"} + "py36": "/Users/jenkins_ci/.pyenv/versions/3.6.5/bin/python"} linuxpylocation = {"py27": "/usr/bin/python2.7", "py34": "/usr/bin/python3.4", diff --git a/conans/client/generators/visualstudio.py b/conans/client/generators/visualstudio.py index 1b91d7a0e..37c7597bd 100644 --- a/conans/client/generators/visualstudio.py +++ b/conans/client/generators/visualstudio.py @@ -1,5 +1,8 @@ +import os + from conans.model import Generator from conans.paths import BUILD_INFO_VISUAL_STUDIO +import re class VisualStudioGenerator(Generator): @@ -76,4 +79,8 @@ class VisualStudioGenerator(Generator): 'exe_flags': " ".join(self._deps_build_info.exelinkflags) } formatted_template = self.template.format(**fields) + userprofile = os.getenv("USERPROFILE") + if userprofile: + userprofile = userprofile.replace("\\", "/") + formatted_template = re.sub(userprofile, "$(USERPROFILE)", formatted_template, flags=re.I) return formatted_template diff --git a/conans/client/remote_manager.py b/conans/client/remote_manager.py index bd37186bf..929174655 100644 --- a/conans/client/remote_manager.py +++ b/conans/client/remote_manager.py @@ -12,7 +12,7 @@ from conans.model.manifest import gather_files from conans.paths import PACKAGE_TGZ_NAME, CONANINFO, CONAN_MANIFEST, CONANFILE, EXPORT_TGZ_NAME, \ rm_conandir, EXPORT_SOURCES_TGZ_NAME, EXPORT_SOURCES_DIR_OLD from conans.util.files import gzopen_without_timestamps, is_dirty,\ - make_read_only + make_read_only, set_dirty, clean_dirty from conans.util.files import tar_extract, rmdir, exception_message_safe, mkdir from conans.util.files import touch_folder from conans.util.log import logger @@ -23,6 +23,7 @@ from conans.util.tracer import (log_package_upload, log_recipe_upload, log_package_download) from conans.client.source import merge_directories from conans.util.env_reader import get_env +from conans.search.search import filter_packages class RemoteManager(object): @@ -39,6 +40,14 @@ class RemoteManager(object): t1 = time.time() export_folder = self._client_cache.export(conan_reference) + + for f in (EXPORT_TGZ_NAME, EXPORT_SOURCES_TGZ_NAME): + tgz_path = os.path.join(export_folder, f) + if is_dirty(tgz_path): + self._output.warn("%s: Removing %s, marked as dirty" % (str(conan_reference), f)) + os.remove(tgz_path) + clean_dirty(tgz_path) + files, symlinks = gather_files(export_folder) if CONANFILE not in files or CONAN_MANIFEST not in files: raise ConanException("Cannot upload corrupted recipe '%s'" % str(conan_reference)) @@ -99,6 +108,11 @@ class RemoteManager(object): "Remove it with 'conan remove %s -p=%s'" % (package_reference, package_reference.conan, package_reference.package_id)) + tgz_path = os.path.join(package_folder, PACKAGE_TGZ_NAME) + if is_dirty(tgz_path): + self._output.warn("%s: Removing %s, marked as dirty" % (str(package_reference), PACKAGE_TGZ_NAME)) + os.remove(tgz_path) + clean_dirty(tgz_path) # Get all the files in that directory files, symlinks = gather_files(package_folder) @@ -188,7 +202,8 @@ class RemoteManager(object): t1 = time.time() def filter_function(urls): - file_url = urls.get(EXPORT_SOURCES_TGZ_NAME) + file_url = urls.pop(EXPORT_SOURCES_TGZ_NAME, None) + check_compressed_files(EXPORT_SOURCES_TGZ_NAME, urls) if file_url: urls = {EXPORT_SOURCES_TGZ_NAME: file_url} else: @@ -254,7 +269,9 @@ class RemoteManager(object): return self._call_remote(remote, "search", pattern, ignorecase) def search_packages(self, remote, reference, query): - return self._call_remote(remote, "search_packages", reference, query) + packages = self._call_remote(remote, "search_packages", reference, query) + packages = filter_packages(query, packages) + return packages def remove(self, conan_ref, remote): """ @@ -324,11 +341,10 @@ def compress_package_files(files, symlinks, dest_folder, output): def compress_files(files, symlinks, name, dest_dir): - """Compress the package and returns the new dict (name => content) of files, - only with the conanXX files and the compressed file""" t1 = time.time() # FIXME, better write to disk sequentially and not keep tgz contents in memory tgz_path = os.path.join(dest_dir, name) + set_dirty(tgz_path) with open(tgz_path, "wb") as tgz_handle: # tgz_contents = BytesIO() tgz = gzopen_without_timestamps(name, mode="w", fileobj=tgz_handle) @@ -354,17 +370,27 @@ def compress_files(files, symlinks, name, dest_dir): tgz.close() + clean_dirty(tgz_path) duration = time.time() - t1 log_compressed_files(files, duration, tgz_path) return tgz_path +def check_compressed_files(tgz_name, files): + bare_name = os.path.splitext(tgz_name)[0] + for f in files: + if bare_name == os.path.splitext(f)[0]: + raise ConanException("This Conan version is not prepared to handle '%s' file format. " + "Please upgrade conan client." % f) + + def unzip_and_get_files(files, destination_dir, tgz_name): """Moves all files from package_files, {relative_name: tmp_abs_path} to destination_dir, unzipping the "tgz_name" if found""" tgz_file = files.pop(tgz_name, None) + check_compressed_files(tgz_name, files) if tgz_file: uncompress_file(tgz_file, destination_dir) os.remove(tgz_file) diff --git a/conans/client/runner.py b/conans/client/runner.py index a598e9721..a71a8f942 100644 --- a/conans/client/runner.py +++ b/conans/client/runner.py @@ -1,6 +1,7 @@ import io import os import sys +from contextlib import contextmanager from subprocess import Popen, PIPE, STDOUT from conans.util.files import decode_text from conans.errors import ConanException @@ -37,18 +38,19 @@ class ConanRunner(object): if self._print_commands_to_output and stream_output and self._log_run_to_output: stream_output.write(call_message) - # No output has to be redirected to logs or buffer or omitted - if output is True and not log_filepath and self._log_run_to_output and not subprocess: - return self._simple_os_call(command, cwd) - elif log_filepath: - if stream_output: - stream_output.write("Logging command output to file '%s'\n" % log_filepath) - with open(log_filepath, "a+") as log_handler: - if self._print_commands_to_output: - log_handler.write(call_message) - return self._pipe_os_call(command, stream_output, log_handler, cwd) - else: - return self._pipe_os_call(command, stream_output, None, cwd) + with pyinstaller_bundle_env_cleaned(): + # No output has to be redirected to logs or buffer or omitted + if output is True and not log_filepath and self._log_run_to_output and not subprocess: + return self._simple_os_call(command, cwd) + elif log_filepath: + if stream_output: + stream_output.write("Logging command output to file '%s'\n" % log_filepath) + with open(log_filepath, "a+") as log_handler: + if self._print_commands_to_output: + log_handler.write(call_message) + return self._pipe_os_call(command, stream_output, log_handler, cwd) + else: + return self._pipe_os_call(command, stream_output, None, cwd) def _pipe_os_call(self, command, stream_output, log_handler, cwd): @@ -69,7 +71,7 @@ class ConanRunner(object): if stream_output and self._log_run_to_output: try: stream_output.write(decoded_line) - except UnicodeEncodeError: # be agressive on text encoding + except UnicodeEncodeError: # be aggressive on text encoding decoded_line = decoded_line.encode("latin-1", "ignore").decode("latin-1", "ignore") stream_output.write(decoded_line) @@ -100,3 +102,27 @@ class ConanRunner(object): finally: os.chdir(old_dir) return result + + +if getattr(sys, 'frozen', False) and 'LD_LIBRARY_PATH' in os.environ: + + # http://pyinstaller.readthedocs.io/en/stable/runtime-information.html#ld-library-path-libpath-considerations + pyinstaller_bundle_dir = os.environ['LD_LIBRARY_PATH'].replace( + os.environ.get('LD_LIBRARY_PATH_ORIG', ''), '' + ).strip(';:') + + @contextmanager + def pyinstaller_bundle_env_cleaned(): + """Removes the pyinstaller bundle directory from LD_LIBRARY_PATH + + :return: None + """ + ld_library_path = os.environ['LD_LIBRARY_PATH'] + os.environ['LD_LIBRARY_PATH'] = ld_library_path.replace(pyinstaller_bundle_dir, '') + yield + os.environ['LD_LIBRARY_PATH'] = ld_library_path + +else: + @contextmanager + def pyinstaller_bundle_env_cleaned(): + yield diff --git a/conans/client/tools/files.py b/conans/client/tools/files.py index 5d6ddef97..0d42fe368 100644 --- a/conans/client/tools/files.py +++ b/conans/client/tools/files.py @@ -11,6 +11,7 @@ from conans.client.output import ConanOutput from conans.errors import ConanException from conans.util.files import (load, save, _generic_algorithm_sum) from conans.unicode import get_cwd +import six _global_output = None @@ -68,6 +69,11 @@ def unzip(filename, destination=".", keep_permissions=False, pattern=None): filename.endswith(".tbz2") or filename.endswith(".tar.bz2") or filename.endswith(".tar")): return untargz(filename, destination, pattern) + if filename.endswith(".tar.xz") or filename.endswith(".txz"): + if six.PY2: + raise ConanException("XZ format not supported in Python 2. Use Python 3 instead") + return untargz(filename, destination, pattern) + import zipfile full_path = os.path.normpath(os.path.join(get_cwd(), destination)) diff --git a/conans/client/tools/net.py b/conans/client/tools/net.py index 235fc69b5..59293e293 100644 --- a/conans/client/tools/net.py +++ b/conans/client/tools/net.py @@ -9,10 +9,13 @@ from conans.errors import ConanException _global_requester = None -def get(url, md5='', sha1='', sha256='', destination="."): +def get(url, md5='', sha1='', sha256='', destination=".", filename=""): """ high level downloader + unzipper + (optional hash checker) + delete temporary zip """ - filename = os.path.basename(url) + if not filename and ("?" in url or "=" in url): + raise ConanException("Cannot deduce file name form url. Use 'filename' parameter.") + + filename = filename or os.path.basename(url) download(url, filename) if md5: diff --git a/conans/model/conan_file.py b/conans/model/conan_file.py index 455397546..17557672b 100644 --- a/conans/model/conan_file.py +++ b/conans/model/conan_file.py @@ -12,6 +12,8 @@ from conans.model.user_info import DepsUserInfo from conans.paths import RUN_LOG_NAME from conans.tools import environment_append, no_op from conans.client.output import Color +from conans.client.run_environment import RunEnvironment +from conans.client.tools.oss import os_info def create_options(conanfile): @@ -255,15 +257,23 @@ class ConanFile(object): """ define cpp_build_info, flags, etc """ - def run(self, command, output=True, cwd=None, win_bash=False, subsystem=None, msys_mingw=True): - if not win_bash: - retcode = self._runner(command, output, os.path.abspath(RUN_LOG_NAME), cwd) - else: + def run(self, command, output=True, cwd=None, win_bash=False, subsystem=None, msys_mingw=True, + ignore_errors=False, run_environment=False): + def _run(): + if not win_bash: + return self._runner(command, output, os.path.abspath(RUN_LOG_NAME), cwd) # FIXME: run in windows bash is not using output - retcode = tools.run_in_windows_bash(self, bashcmd=command, cwd=cwd, subsystem=subsystem, - msys_mingw=msys_mingw) + return tools.run_in_windows_bash(self, bashcmd=command, cwd=cwd, subsystem=subsystem, + msys_mingw=msys_mingw) + if run_environment: + with tools.environment_append(RunEnvironment(self).vars): + if os_info.is_macos: + command = 'DYLD_LIBRARY_PATH="%s" %s' % (os.environ.get('DYLD_LIBRARY_PATH', ''), command) + retcode = _run() + else: + retcode = _run() - if retcode != 0: + if not ignore_errors and retcode != 0: raise ConanException("Error %d while executing %s" % (retcode, command)) return retcode diff --git a/conans/search/search.py b/conans/search/search.py index 975a97403..2e189bb45 100644 --- a/conans/search/search.py +++ b/conans/search/search.py @@ -61,7 +61,7 @@ def evaluate(prop_name, prop_value, conan_vars_info): """ def compatible_prop(setting_value, prop_value): - return setting_value is None or prop_value == setting_value + return (prop_value == setting_value) or (prop_value == "None" and setting_value is None) info_settings = conan_vars_info.get("settings", []) info_options = conan_vars_info.get("options", []) diff --git a/conans/server/rest/controllers/file_upload_download_controller.py b/conans/server/rest/controllers/file_upload_download_controller.py index b49091a07..fe8ec36ab 100644 --- a/conans/server/rest/controllers/file_upload_download_controller.py +++ b/conans/server/rest/controllers/file_upload_download_controller.py @@ -20,7 +20,12 @@ class FileUploadDownloadController(Controller): token = request.query.get("signature", None) file_path = service.get_file_path(filepath, token) # https://github.com/kennethreitz/requests/issues/1586 - mimetype = "x-gzip" if filepath.endswith(".tgz") else "auto" + if filepath.endswith(".tgz"): + mimetype = "x-gzip" + elif filepath.endswith(".txz"): + mimetype = "x-xz" + else: + mimetype = "auto" return static_file(os.path.basename(file_path), root=os.path.dirname(file_path), mimetype=mimetype)
Using "?" in a tools.get() URL will fail, while using it in a tools.download() will succeed. To help us debug your issue please explain: - [x] I've read the [CONTRIBUTING guide](https://raw.githubusercontent.com/conan-io/conan/develop/.github/CONTRIBUTING.md). - [x] I've specified the Conan version, operating system version and any tool that can be relevant. - [x] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion. Example: ``` from conans import ConanFile, tools class LibraryConan(ConanFile): name = "Library" version = "1.0" license = "" url = "<Package recipe repository url here, for issues about the package>" description = "" settings = "os", "compiler", "build_type", "arch" def source(self): tools.get("http://example.com/?file=1") ``` ``` conan create . Company/beta ERROR: Library/1.0@Company/beta: Error in source() method, line 12 tools.get("http://example.com/?file=1") ConanConnectionError: Download failed, check server, possibly try again [Errno 22] Invalid argument: 'C:\\Users\\User\\.conan\\data\\Library\\1.0\\Company\\beta\\source\\?file=1' ```
conan-io/conan
diff --git a/conans/test/command/remove_test.py b/conans/test/command/remove_test.py index 093fddfb6..5cddca144 100644 --- a/conans/test/command/remove_test.py +++ b/conans/test/command/remove_test.py @@ -15,6 +15,35 @@ from conans.test.utils.test_files import temp_folder class RemoveOutdatedTest(unittest.TestCase): + + def remove_query_test(self): + test_server = TestServer(users={"lasote": "password"}) # exported users and passwords + servers = {"default": test_server} + client = TestClient(servers=servers, users={"default": [("lasote", "password")]}) + conanfile = """from conans import ConanFile +class Test(ConanFile): + settings = "os" + """ + client.save({"conanfile.py": conanfile}) + client.run("create . Test/0.1@lasote/testing -s os=Windows") + client.run("create . Test/0.1@lasote/testing -s os=Linux") + client.save({"conanfile.py": conanfile.replace("settings", "pass #")}) + client.run("create . Test2/0.1@lasote/testing") + client.run("upload * --all --confirm") + for remote in ("", "-r=default"): + client.run("remove Test/0.1@lasote/testing -q=os=Windows -f %s" % remote) + client.run("search Test/0.1@lasote/testing %s" % remote) + self.assertNotIn("os: Windows", client.out) + self.assertIn("os: Linux", client.out) + + client.run("remove Test2/0.1@lasote/testing -q=os=Windows -f %s" % remote) + client.run("search Test2/0.1@lasote/testing %s" % remote) + self.assertIn("Package_ID: 5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9", client.out) + client.run("remove Test2/0.1@lasote/testing -q=os=None -f %s" % remote) + client.run("search Test2/0.1@lasote/testing %s" % remote) + self.assertNotIn("Package_ID: 5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9", client.out) + self.assertIn("There are no packages", client.out) + def remove_outdated_test(self): test_server = TestServer(users={"lasote": "password"}) # exported users and passwords servers = {"default": test_server} diff --git a/conans/test/command/search_test.py b/conans/test/command/search_test.py index e94731ce9..457217c15 100644 --- a/conans/test/command/search_test.py +++ b/conans/test/command/search_test.py @@ -387,8 +387,7 @@ helloTest/1.4.10@fenix/stable""".format(remote) q = 'compiler="gcc" OR compiler.libcxx=libstdc++11' # Should find Visual because of the OR, visual doesn't care about libcxx - self._assert_pkg_q(q, ["LinuxPackageSHA", "PlatformIndependantSHA", - "WindowsPackageSHA"], remote) + self._assert_pkg_q(q, ["LinuxPackageSHA", "PlatformIndependantSHA"], remote) q = '(compiler="gcc" AND compiler.libcxx=libstdc++11) OR compiler.version=4.5' self._assert_pkg_q(q, ["LinuxPackageSHA"], remote) @@ -407,18 +406,25 @@ helloTest/1.4.10@fenix/stable""".format(remote) self._assert_pkg_q(q, ["PlatformIndependantSHA", "WindowsPackageSHA"], remote) q = '(os="Linux" OR os=Windows)' - self._assert_pkg_q(q, ["PlatformIndependantSHA", "LinuxPackageSHA", - "WindowsPackageSHA"], remote) + self._assert_pkg_q(q, ["LinuxPackageSHA", "WindowsPackageSHA"], remote) + + q = '(os="Linux" OR os=None)' + self._assert_pkg_q(q, ["LinuxPackageSHA", "PlatformIndependantSHA"], remote) + + q = '(os=None)' + self._assert_pkg_q(q, ["PlatformIndependantSHA"], remote) q = '(os="Linux" OR os=Windows) AND use_Qt=True' + self._assert_pkg_q(q, ["WindowsPackageSHA"], remote) + + q = '(os=None OR os=Windows) AND use_Qt=True' self._assert_pkg_q(q, ["PlatformIndependantSHA", "WindowsPackageSHA"], remote) q = '(os="Linux" OR os=Windows) AND use_Qt=True AND nonexistant_option=3' - self._assert_pkg_q(q, ["PlatformIndependantSHA", "WindowsPackageSHA"], remote) + self._assert_pkg_q(q, [], remote) q = '(os="Linux" OR os=Windows) AND use_Qt=True OR nonexistant_option=3' - self._assert_pkg_q(q, ["PlatformIndependantSHA", - "WindowsPackageSHA", "LinuxPackageSHA"], remote) + self._assert_pkg_q(q, ["WindowsPackageSHA", "LinuxPackageSHA"], remote) # test in local test_cases() @@ -474,9 +480,19 @@ helloTest/1.4.10@fenix/stable""".format(remote) self.client.run('search Hello/1.4.10/fenix/testing -q os=Windows') self.assertIn("WindowsPackageSHA", self.client.out) + self.assertNotIn("PlatformIndependantSHA", self.client.out) + self.assertNotIn("LinuxPackageSHA", self.client.out) + + self.client.run('search Hello/1.4.10/fenix/testing -q "os=Windows or os=None"') + self.assertIn("WindowsPackageSHA", self.client.out) self.assertIn("PlatformIndependantSHA", self.client.out) self.assertNotIn("LinuxPackageSHA", self.client.out) + self.client.run('search Hello/1.4.10/fenix/testing -q "os=Windows or os=Linux"') + self.assertIn("WindowsPackageSHA", self.client.out) + self.assertNotIn("PlatformIndependantSHA", self.client.out) + self.assertIn("LinuxPackageSHA", self.client.out) + self.client.run('search Hello/1.4.10/fenix/testing -q "os=Windows AND compiler.version=4.5"') self.assertIn("There are no packages for reference 'Hello/1.4.10@fenix/testing' " "matching the query 'os=Windows AND compiler.version=4.5'", self.client.out) diff --git a/conans/test/command/upload_test.py b/conans/test/command/upload_test.py index 661bf9d8e..193024241 100644 --- a/conans/test/command/upload_test.py +++ b/conans/test/command/upload_test.py @@ -2,9 +2,12 @@ import unittest from conans.tools import environment_append from conans.test.utils.tools import TestClient, TestServer from conans.test.utils.cpp_test_files import cpp_hello_conan_files -from conans.model.ref import ConanFileReference -from conans.util.files import save +from conans.model.ref import ConanFileReference, PackageReference +from conans.util.files import save, is_dirty, gzopen_without_timestamps import os +from mock import mock +from conans.errors import ConanException +from conans.paths import EXPORT_SOURCES_TGZ_NAME, PACKAGE_TGZ_NAME conanfile = """from conans import ConanFile @@ -75,6 +78,62 @@ class UploadTest(unittest.TestCase): self.assertIn("Uploading conan_package.tgz", client.user_io.out) self.assertIn("Uploading conanfile.py", client.user_io.out) + def broken_sources_tgz_test(self): + # https://github.com/conan-io/conan/issues/2854 + client = self._client() + client.save({"conanfile.py": conanfile, + "source.h": "my source"}) + client.run("create . user/testing") + ref = ConanFileReference.loads("Hello0/1.2.1@user/testing") + + def gzopen_patched(name, mode="r", fileobj=None, compresslevel=None, **kwargs): + raise ConanException("Error gzopen %s" % name) + with mock.patch('conans.client.remote_manager.gzopen_without_timestamps', new=gzopen_patched): + error = client.run("upload * --confirm", ignore_error=True) + self.assertTrue(error) + self.assertIn("ERROR: Error gzopen conan_sources.tgz", client.out) + + export_folder = client.client_cache.export(ref) + tgz = os.path.join(export_folder, EXPORT_SOURCES_TGZ_NAME) + self.assertTrue(os.path.exists(tgz)) + self.assertTrue(is_dirty(tgz)) + + client.run("upload * --confirm") + self.assertIn("WARN: Hello0/1.2.1@user/testing: Removing conan_sources.tgz, marked as dirty", + client.out) + self.assertTrue(os.path.exists(tgz)) + self.assertFalse(is_dirty(tgz)) + + def broken_package_tgz_test(self): + # https://github.com/conan-io/conan/issues/2854 + client = self._client() + client.save({"conanfile.py": conanfile, + "source.h": "my source"}) + client.run("create . user/testing") + package_ref = PackageReference.loads("Hello0/1.2.1@user/testing:" + "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9") + + def gzopen_patched(name, mode="r", fileobj=None, compresslevel=None, **kwargs): + if name == PACKAGE_TGZ_NAME: + raise ConanException("Error gzopen %s" % name) + return gzopen_without_timestamps(name, mode, fileobj, compresslevel, **kwargs) + with mock.patch('conans.client.remote_manager.gzopen_without_timestamps', new=gzopen_patched): + error = client.run("upload * --confirm --all", ignore_error=True) + self.assertTrue(error) + self.assertIn("ERROR: Error gzopen conan_package.tgz", client.out) + + export_folder = client.client_cache.package(package_ref) + tgz = os.path.join(export_folder, PACKAGE_TGZ_NAME) + self.assertTrue(os.path.exists(tgz)) + self.assertTrue(is_dirty(tgz)) + + client.run("upload * --confirm --all") + self.assertIn("WARN: Hello0/1.2.1@user/testing:5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9: " + "Removing conan_package.tgz, marked as dirty", + client.out) + self.assertTrue(os.path.exists(tgz)) + self.assertFalse(is_dirty(tgz)) + def corrupt_upload_test(self): client = self._client() diff --git a/conans/test/functional/runner_test.py b/conans/test/functional/runner_test.py index f0dc4fda8..d00f9eb71 100644 --- a/conans/test/functional/runner_test.py +++ b/conans/test/functional/runner_test.py @@ -2,7 +2,6 @@ import os import six import unittest -from io import StringIO from conans.client.runner import ConanRunner from conans.test.utils.tools import TestClient @@ -19,6 +18,18 @@ class RunnerTest(unittest.TestCase): client.run("build .") return client + def ignore_error_test(self): + conanfile = """from conans import ConanFile +class Pkg(ConanFile): + def source(self): + ret = self.run("not_a_command", ignore_errors=True) + self.output.info("RETCODE %s" % (ret!=0)) +""" + client = TestClient() + client.save({"conanfile.py": conanfile}) + client.run("source .") + self.assertIn("RETCODE True", client.out) + def basic_test(self): conanfile = ''' from conans import ConanFile diff --git a/conans/test/generators/visual_studio_test.py b/conans/test/generators/visual_studio_test.py index 0f43200ec..fce6ead8c 100644 --- a/conans/test/generators/visual_studio_test.py +++ b/conans/test/generators/visual_studio_test.py @@ -7,6 +7,10 @@ from conans.model.settings import Settings from conans.model.conan_file import ConanFile from conans.model.build_info import CppInfo from conans.model.ref import ConanFileReference +from conans.test.utils.test_files import temp_folder +from conans.util.files import save +import os +from conans import tools class VisualStudioGeneratorTest(unittest.TestCase): @@ -27,3 +31,32 @@ class VisualStudioGeneratorTest(unittest.TestCase): self.assertIn('<PropertyGroup Label="Conan-RootDirs">', content) self.assertIn("<Conan-MyPkg-Root>dummy_root_folder1</Conan-MyPkg-Root>", content) self.assertIn("<Conan-My-Fancy-Pkg_2-Root>dummy_root_folder2</Conan-My-Fancy-Pkg_2-Root>", content) + + def user_profile_test(self): + conanfile = ConanFile(None, None, Settings({}), None) + ref = ConanFileReference.loads("MyPkg/0.1@user/testing") + tmp_folder = temp_folder() + pkg1 = os.path.join(tmp_folder, "pkg1") + cpp_info = CppInfo(pkg1) + cpp_info.includedirs = ["include"] + save(os.path.join(pkg1, "include/file.h"), "") + conanfile.deps_cpp_info.update(cpp_info, ref.name) + ref = ConanFileReference.loads("My.Fancy-Pkg_2/0.1@user/testing") + pkg2 = os.path.join(tmp_folder, "pkg2") + cpp_info = CppInfo(pkg2) + cpp_info.includedirs = ["include"] + save(os.path.join(pkg2, "include/file.h"), "") + conanfile.deps_cpp_info.update(cpp_info, ref.name) + generator = VisualStudioGenerator(conanfile) + + with tools.environment_append({"USERPROFILE": tmp_folder}): + content = generator.content + xml.etree.ElementTree.fromstring(content) + self.assertIn("<AdditionalIncludeDirectories>$(USERPROFILE)/pkg1/include;" + "$(USERPROFILE)/pkg2/include;", content) + + with tools.environment_append({"USERPROFILE": tmp_folder.upper()}): + content = generator.content + xml.etree.ElementTree.fromstring(content) + self.assertIn("<AdditionalIncludeDirectories>$(USERPROFILE)/pkg1/include;" + "$(USERPROFILE)/pkg2/include;", content) diff --git a/conans/test/integration/run_envronment_test.py b/conans/test/integration/run_envronment_test.py index 48a3638b9..efd78257b 100644 --- a/conans/test/integration/run_envronment_test.py +++ b/conans/test/integration/run_envronment_test.py @@ -34,3 +34,68 @@ class HelloConan(ConanFile): client.save({"conanfile.py": reuse}, clean_first=True) client.run("install . --build missing") client.run("build .") + self.assertIn("Hello Hello0", client.out) + + def test_shared_run_environment(self): + client = TestClient() + cmake = """set(CMAKE_CXX_COMPILER_WORKS 1) +set(CMAKE_CXX_ABI_COMPILED 1) +project(MyHello CXX) +cmake_minimum_required(VERSION 2.8.12) + +add_library(hello SHARED hello.cpp) +add_executable(say_hello main.cpp) +target_link_libraries(say_hello hello)""" + hello_h = """#ifdef WIN32 + #define HELLO_EXPORT __declspec(dllexport) +#else + #define HELLO_EXPORT +#endif + +HELLO_EXPORT void hello(); +""" + hello_cpp = r"""#include "hello.h" +#include <iostream> +void hello(){ + std::cout<<"Hello Tool!\n"; +} +""" + main = """#include "hello.h" + int main(){ + hello(); + } + """ + conanfile = """from conans import ConanFile, CMake +class Pkg(ConanFile): + exports_sources = "*" + def build(self): + cmake = CMake(self) + cmake.configure() + cmake.build() + + def package(self): + self.copy("*say_hello.exe", dst="bin", keep_path=False) + self.copy("*say_hello", dst="bin", keep_path=False) + self.copy(pattern="*.dll", dst="bin", keep_path=False) + self.copy(pattern="*.dylib", dst="lib", keep_path=False) + self.copy(pattern="*.so", dst="lib", keep_path=False) +""" + client.save({"conanfile.py": conanfile, + "CMakeLists.txt": cmake, + "main.cpp": main, + "hello.cpp": hello_cpp, + "hello.h": hello_h}) + client.run("create . Pkg/0.1@user/testing") + + reuse = '''from conans import ConanFile +class HelloConan(ConanFile): + requires = "Pkg/0.1@user/testing" + + def build(self): + self.run("say_hello", run_environment=True) +''' + + client.save({"conanfile.py": reuse}, clean_first=True) + client.run("install .") + client.run("build .") + self.assertIn("Hello Tool!", client.out) diff --git a/conans/test/util/tools_test.py b/conans/test/util/tools_test.py index 557095f54..6927347c6 100644 --- a/conans/test/util/tools_test.py +++ b/conans/test/util/tools_test.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- - +from bottle import static_file, request import mock import os import platform @@ -25,7 +25,8 @@ from conans.model.settings import Settings from conans.test.utils.runner import TestRunner from conans.test.utils.test_files import temp_folder -from conans.test.utils.tools import TestClient, TestBufferConanOutput, create_local_git_repo +from conans.test.utils.tools import TestClient, TestBufferConanOutput, create_local_git_repo, \ + StoppableThreadBottle from conans.tools import which from conans.tools import OSInfo, SystemPackageTool, replace_in_file, AptTool, ChocolateyTool,\ @@ -33,6 +34,8 @@ from conans.tools import OSInfo, SystemPackageTool, replace_in_file, AptTool, Ch from conans.util.files import save, load, md5 import requests +from nose.plugins.attrib import attr + class SystemPackageToolTest(unittest.TestCase): def setUp(self): @@ -993,6 +996,51 @@ ProgramFiles(x86)=C:\Program Files (x86) else: self.assertEqual(str, type(result)) + @attr('slow') + def get_filename_download_test(self): + # Create a tar file to be downloaded from server + with tools.chdir(tools.mkdir_tmp()): + import tarfile + tar_file = tarfile.open("sample.tar.gz", "w:gz") + tools.mkdir("test_folder") + tar_file.add(os.path.abspath("test_folder"), "test_folder") + tar_file.close() + file_path = os.path.abspath("sample.tar.gz") + assert(os.path.exists(file_path)) + + # Instance stoppable thread server and add endpoints + thread = StoppableThreadBottle() + + @thread.server.get("/this_is_not_the_file_name") + def get_file(): + return static_file(os.path.basename(file_path), root=os.path.dirname(file_path)) + + @thread.server.get("/") + def get_file2(): + self.assertEquals(request.query["file"], "1") + return static_file(os.path.basename(file_path), root=os.path.dirname(file_path)) + + thread.run_server() + + # Test: File name cannot be deduced from '?file=1' + with self.assertRaisesRegexp(ConanException, + "Cannot deduce file name form url. Use 'filename' parameter."): + tools.get("http://localhost:8266/?file=1") + + # Test: Works with filename parameter instead of '?file=1' + with tools.chdir(tools.mkdir_tmp()): + tools.get("http://localhost:8266/?file=1", filename="sample.tar.gz") + self.assertTrue(os.path.exists("test_folder")) + + # Test: Use a different endpoint but still not the filename one + with tools.chdir(tools.mkdir_tmp()): + from zipfile import BadZipfile + with self.assertRaises(BadZipfile): + tools.get("http://localhost:8266/this_is_not_the_file_name") + tools.get("http://localhost:8266/this_is_not_the_file_name", filename="sample.tar.gz") + self.assertTrue(os.path.exists("test_folder")) + thread.stop() + class GitToolTest(unittest.TestCase): @@ -1059,10 +1107,10 @@ class GitToolTest(unittest.TestCase): def _create_paths(): tmp = temp_folder() submodule_path = os.path.join( - tmp, + tmp, os.path.basename(os.path.normpath(submodule))) subsubmodule_path = os.path.join( - submodule_path, + submodule_path, os.path.basename(os.path.normpath(subsubmodule))) return tmp, submodule_path, subsubmodule_path @@ -1079,7 +1127,7 @@ class GitToolTest(unittest.TestCase): with self.assertRaisesRegexp(ConanException, "Invalid 'submodule' attribute value in the 'scm'."): git.clone(path, submodule="invalid") - # Check shallow + # Check shallow tmp, submodule_path, subsubmodule_path = _create_paths() git = Git(tmp) git.clone(path, submodule="shallow") diff --git a/conans/test/util/xz_test.py b/conans/test/util/xz_test.py new file mode 100644 index 000000000..262549736 --- /dev/null +++ b/conans/test/util/xz_test.py @@ -0,0 +1,88 @@ +import os +from unittest import TestCase +import six +import unittest +import tarfile + +from conans.test.utils.test_files import temp_folder +from conans.tools import unzip, save +from conans.util.files import load, save_files +from conans.errors import ConanException +from conans.test.utils.tools import TestClient, TestServer +from conans.model.ref import ConanFileReference, PackageReference + + +class XZTest(TestCase): + def test_error_xz(self): + server = TestServer() + ref = ConanFileReference.loads("Pkg/0.1@user/channel") + export = server.paths.export(ref) + save_files(export, {"conanfile.py": "#", + "conanmanifest.txt": "#", + "conan_export.txz": "#"}) + client = TestClient(servers={"default": server}, + users={"default": [("lasote", "mypass")]}) + error = client.run("install Pkg/0.1@user/channel", ignore_error=True) + self.assertTrue(error) + self.assertIn("ERROR: This Conan version is not prepared to handle " + "'conan_export.txz' file format", client.out) + + def test_error_sources_xz(self): + server = TestServer() + ref = ConanFileReference.loads("Pkg/0.1@user/channel") + client = TestClient(servers={"default": server}, + users={"default": [("lasote", "mypass")]}) + export = server.paths.export(ref) + conanfile = """from conans import ConanFile +class Pkg(ConanFile): + exports_sources = "*" +""" + save_files(export, {"conanfile.py": conanfile, + "conanmanifest.txt": "1", + "conan_sources.txz": "#"}) + error = client.run("install Pkg/0.1@user/channel --build", ignore_error=True) + self.assertTrue(error) + self.assertIn("ERROR: This Conan version is not prepared to handle " + "'conan_sources.txz' file format", client.out) + + def test_error_package_xz(self): + server = TestServer() + ref = ConanFileReference.loads("Pkg/0.1@user/channel") + client = TestClient(servers={"default": server}, + users={"default": [("lasote", "mypass")]}) + export = server.paths.export(ref) + conanfile = """from conans import ConanFile +class Pkg(ConanFile): + exports_sources = "*" +""" + save_files(export, {"conanfile.py": conanfile, + "conanmanifest.txt": "1"}) + pkg_ref = PackageReference(ref, "5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9") + package = server.paths.package(pkg_ref) + save_files(package, {"conaninfo.txt": "#", + "conanmanifest.txt": "1", + "conan_package.txz": "#"}) + error = client.run("install Pkg/0.1@user/channel", ignore_error=True) + self.assertTrue(error) + self.assertIn("ERROR: This Conan version is not prepared to handle " + "'conan_package.txz' file format", client.out) + + @unittest.skipUnless(six.PY3, "only Py3") + def test(self): + tmp_dir = temp_folder() + file_path = os.path.join(tmp_dir, "a_file.txt") + save(file_path, "my content!") + txz = os.path.join(tmp_dir, "sample.tar.xz") + with tarfile.open(txz, "w:xz") as tar: + tar.add(file_path, "a_file.txt") + + dest_folder = temp_folder() + unzip(txz, dest_folder) + content = load(os.path.join(dest_folder, "a_file.txt")) + self.assertEqual(content, "my content!") + + @unittest.skipUnless(six.PY2, "only Py2") + def test_error_python2(self): + with self.assertRaisesRegexp(ConanException, "XZ format not supported in Python 2"): + dest_folder = temp_folder() + unzip("somefile.tar.xz", dest_folder) diff --git a/conans/test/utils/tools.py b/conans/test/utils/tools.py index 824cbb68e..ee5ff714b 100644 --- a/conans/test/utils/tools.py +++ b/conans/test/utils/tools.py @@ -2,13 +2,16 @@ import os import shlex import shutil import sys +import threading import uuid from collections import Counter from contextlib import contextmanager from io import StringIO +import bottle import requests import six +import time from mock import Mock from six.moves.urllib.parse import urlsplit, urlunsplit from webtest.app import TestApp @@ -507,3 +510,24 @@ class TestClient(object): save_files(path, files) if not files: mkdir(self.current_folder) + + +class StoppableThreadBottle(threading.Thread): + """ + Real server to test download endpoints + """ + server = None + + def __init__(self, host="127.0.0.1", port=8266): + self.server = bottle.Bottle() + super(StoppableThreadBottle, self).__init__(target=self.server.run, kwargs={"host": host, + "port": port}) + self.daemon = True + self._stop = threading.Event() + + def stop(self): + self._stop.set() + + def run_server(self): + self.start() + time.sleep(1)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 9 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "nose-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.6.6 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@c3baafb780b6e5498f8bd460426901d9d5ab10e1#egg=conan cov-core==1.15.0 coverage==4.2 deprecation==2.0.7 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 node-semver==0.2.0 nose==1.3.7 nose-cov==1.6 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 Pygments==2.14.0 PyJWT==1.7.1 pylint==1.8.4 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.12 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==1.6.6 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - cov-core==1.15.0 - coverage==4.2 - deprecation==2.0.7 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - node-semver==0.2.0 - nose==1.3.7 - nose-cov==1.6 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==1.8.4 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.12 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/util/xz_test.py::XZTest::test" ]
[ "conans/test/integration/run_envronment_test.py::RunEnvironmentTest::test_run_environment", "conans/test/integration/run_envronment_test.py::RunEnvironmentTest::test_shared_run_environment", "conans/test/util/tools_test.py::ToolsTest::test_get_env_in_conanfile", "conans/test/util/tools_test.py::ToolsTest::test_global_tools_overrided", "conans/test/util/tools_test.py::GitToolTest::test_clone_submodule_git", "conans/test/util/xz_test.py::XZTest::test_error_package_xz", "conans/test/util/xz_test.py::XZTest::test_error_sources_xz", "conans/test/util/xz_test.py::XZTest::test_error_xz" ]
[ "conans/test/functional/runner_test.py::RunnerTest::test_write_to_stringio", "conans/test/util/tools_test.py::ReplaceInFileTest::test_replace_in_file", "conans/test/util/tools_test.py::ToolsTest::test_environment_nested", "conans/test/util/tools_test.py::GitToolTest::test_clone_existing_folder_git", "conans/test/util/tools_test.py::GitToolTest::test_clone_existing_folder_without_branch", "conans/test/util/tools_test.py::GitToolTest::test_clone_git", "conans/test/util/tools_test.py::GitToolTest::test_credentials", "conans/test/util/tools_test.py::GitToolTest::test_verify_ssl" ]
[]
MIT License
2,757
3,974
[ ".ci/jenkins/conf.py", "conans/client/generators/visualstudio.py", "conans/client/remote_manager.py", "conans/client/runner.py", "conans/client/tools/files.py", "conans/client/tools/net.py", "conans/model/conan_file.py", "conans/search/search.py", "conans/server/rest/controllers/file_upload_download_controller.py" ]
mesonbuild__meson-3863
09ad29ec560f2a05108694d909de30b5e3e58357
2018-07-10 11:37:25
4ff7b65f9be936ef406aa839958c1db991ba8272
nirbheek: Another thing that would be a Very Nice Thing that ensures that stuff like this doesn't break the Intel compiler in the future is to find a way to add the latest version of ICC to the Docker instance that we use for running [Linux tests on the CI](https://github.com/mesonbuild/meson/blob/master/.travis.yml). Then we can run the tests against it in the same way that we run clang tests. asartori86: > find a way to add the latest version of ICC to the Docker instance don't you have to pay to have the intel compiler? nirbheek: > don't you have to pay for intel compiler? I believe you can get a free version for open source use: https://software.intel.com/en-us/qualify-for-free-software/opensourcecontributor I remember getting it for FOSS use 1-2 years ago when I was implementing it for Meson, but I don't remember how.
diff --git a/mesonbuild/compilers/c.py b/mesonbuild/compilers/c.py index b62155b7b..af3e2c4a1 100644 --- a/mesonbuild/compilers/c.py +++ b/mesonbuild/compilers/c.py @@ -866,12 +866,29 @@ class CCompiler(Compiler): return patterns @staticmethod - def _get_trials_from_pattern(pattern, directory, libname): + def _sort_shlibs_openbsd(libs): + filtered = [] + for lib in libs: + # Validate file as a shared library of type libfoo.so.X.Y + ret = lib.rsplit('.so.', maxsplit=1) + if len(ret) != 2: + continue + try: + float(ret[1]) + except ValueError: + continue + filtered.append(lib) + float_cmp = lambda x: float(x.rsplit('.so.', maxsplit=1)[1]) + return sorted(filtered, key=float_cmp, reverse=True) + + @classmethod + def _get_trials_from_pattern(cls, pattern, directory, libname): f = os.path.join(directory, pattern.format(libname)) + # Globbing for OpenBSD if '*' in pattern: # NOTE: globbing matches directories and broken symlinks # so we have to do an isfile test on it later - return glob.glob(f) + return cls._sort_shlibs_openbsd(glob.glob(f)) return [f] @staticmethod diff --git a/mesonbuild/compilers/compilers.py b/mesonbuild/compilers/compilers.py index 21aab1163..25835a32d 100644 --- a/mesonbuild/compilers/compilers.py +++ b/mesonbuild/compilers/compilers.py @@ -1561,6 +1561,9 @@ class IntelCompiler: else: return ['-openmp'] + def get_link_whole_for(self, args): + return GnuCompiler.get_link_whole_for(self, args) + class ArmCompiler: # Functionality that is common to all ARM family compilers.
intel compiler doesn't implement link_whole Hi, I got an error when including PETSc as external dependency. Here is my `meson.build` ``` project('xxx', 'cpp', default_options : ['cpp_std=c++11']) pdep = dependency('PETSc') ``` this is what I get when I run meson ```The Meson build system Version: 0.47.0 Source dir: /some/path/ Build dir: /some/path/build Build type: native build Project name: xxx Project version: undefined Native C++ compiler: icpc (intel 17.0.4 "icpc (ICC) 17.0.4 20170411") Build machine cpu family: x86_64 Build machine cpu: x86_64 Found pkg-config: /usr/bin/pkg-config (0.27.1) meson.build:5:0: ERROR: Language C++ does not support linking whole archives. A full log can be found at /some/path/build/meson-logs/meson-log.txt ``` and the log is ``` Build started at 2018-07-10T11:48:00.454242 Main binary: /bin/python3 Python system: Linux The Meson build system Version: 0.47.0 Source dir: /some/path Build dir: /some/path/build Build type: native build Project name: xxx Project version: undefined Sanity testing C++ compiler: icpc Is cross compiler: False. Sanity check compiler command line: icpc /some/path/build/meson-private/sanitycheckcpp.cc -o /some/path/build/meson-private/sanitycheckcpp.exe Sanity check compile stdout: ----- Sanity check compile stderr: ----- Running test binary command: /some/path/build/meson-private/sanitycheckcpp.exe Native C++ compiler: icpc (intel 17.0.4 "icpc (ICC) 17.0.4 20170411") Build machine cpu family: x86_64 Build machine cpu: x86_64 Found pkg-config: /usr/bin/pkg-config (0.27.1) Determining dependency 'PETSc' with pkg-config executable '/usr/bin/pkg-config' Called `/usr/bin/pkg-config --modversion PETSc` -> 0 3.9.2 Called `/usr/bin/pkg-config --cflags PETSc` -> 0 -I/...../petsc-3.9.2/arch-linux-c-dbg-g-real-avx-2-512-int64/include Called `/usr/bin/pkg-config PETSc --libs` -> 0 -L/...../petsc-3.9.2/arch-linux-c-dbg-g-real-avx-2-512-int64/lib -lpetsc Called `/usr/bin/pkg-config PETSc --libs` -> 0 -L/......./petsc-3.9.2/arch-linux-c-dbg-g-real-avx-2-512-int64/lib -lpetsc meson.build:5:0: ERROR: Language C++ does not support linking whole archives. ``` however, if I issue from the command line ``` icpc $(pkg-config --cflags --libs PETSc) meson-private/sanitycheckcpp.cc ``` it compiles and links.. What happens inside the call to `dependency`? Why I get that error and how can I solve it? thanks
mesonbuild/meson
diff --git a/run_unittests.py b/run_unittests.py index df4603e3a..f4e95a302 100755 --- a/run_unittests.py +++ b/run_unittests.py @@ -522,12 +522,28 @@ class InternalTests(unittest.TestCase): self.assertEqual(p, shr) p = cc.get_library_naming(env, 'static') self.assertEqual(p, stc) - p = cc.get_library_naming(env, 'default') - self.assertEqual(p, shr + stc) - p = cc.get_library_naming(env, 'shared-static') - self.assertEqual(p, shr + stc) p = cc.get_library_naming(env, 'static-shared') self.assertEqual(p, stc + shr) + p = cc.get_library_naming(env, 'shared-static') + self.assertEqual(p, shr + stc) + p = cc.get_library_naming(env, 'default') + self.assertEqual(p, shr + stc) + # Test find library by mocking up openbsd + if platform != 'openbsd': + return + with tempfile.TemporaryDirectory() as tmpdir: + with open(os.path.join(tmpdir, 'libfoo.so.6.0'), 'w') as f: + f.write('') + with open(os.path.join(tmpdir, 'libfoo.so.5.0'), 'w') as f: + f.write('') + with open(os.path.join(tmpdir, 'libfoo.so.54.0'), 'w') as f: + f.write('') + with open(os.path.join(tmpdir, 'libfoo.so.66a.0b'), 'w') as f: + f.write('') + with open(os.path.join(tmpdir, 'libfoo.so.70.0.so.1'), 'w') as f: + f.write('') + found = cc.find_library_real('foo', env, [tmpdir], '', 'default') + self.assertEqual(os.path.basename(found[0]), 'libfoo.so.54.0') def test_find_library_patterns(self): '''
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
0.47
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/mesonbuild/meson.git@09ad29ec560f2a05108694d909de30b5e3e58357#egg=meson packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: meson channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/meson
[ "run_unittests.py::InternalTests::test_find_library_patterns" ]
[ "run_unittests.py::AllPlatformTests::test_absolute_prefix_libdir", "run_unittests.py::AllPlatformTests::test_all_forbidden_targets_tested", "run_unittests.py::AllPlatformTests::test_always_prefer_c_compiler_for_asm", "run_unittests.py::AllPlatformTests::test_array_option_bad_change", "run_unittests.py::AllPlatformTests::test_array_option_change", "run_unittests.py::AllPlatformTests::test_array_option_empty_equivalents", "run_unittests.py::AllPlatformTests::test_build_by_default", "run_unittests.py::AllPlatformTests::test_check_module_linking", "run_unittests.py::AllPlatformTests::test_command_line", "run_unittests.py::AllPlatformTests::test_compiler_detection", "run_unittests.py::AllPlatformTests::test_compiler_options_documented", "run_unittests.py::AllPlatformTests::test_compiler_run_command", "run_unittests.py::AllPlatformTests::test_configure_file_warnings", "run_unittests.py::AllPlatformTests::test_conflicting_d_dash_option", "run_unittests.py::AllPlatformTests::test_cpu_families_documented", "run_unittests.py::AllPlatformTests::test_cross_file_system_paths", "run_unittests.py::AllPlatformTests::test_custom_target_changes_cause_rebuild", "run_unittests.py::AllPlatformTests::test_custom_target_exe_data_deterministic", "run_unittests.py::AllPlatformTests::test_dash_d_dedup", "run_unittests.py::AllPlatformTests::test_default_options_prefix", "run_unittests.py::AllPlatformTests::test_default_options_prefix_dependent_defaults", "run_unittests.py::AllPlatformTests::test_dirs", "run_unittests.py::AllPlatformTests::test_dist_git", "run_unittests.py::AllPlatformTests::test_dist_hg", "run_unittests.py::AllPlatformTests::test_feature_check_usage_subprojects", "run_unittests.py::AllPlatformTests::test_flock", "run_unittests.py::AllPlatformTests::test_forcefallback", "run_unittests.py::AllPlatformTests::test_free_stringarray_setting", "run_unittests.py::AllPlatformTests::test_guessed_linker_dependencies", "run_unittests.py::AllPlatformTests::test_identical_target_name_in_subdir_flat_layout", "run_unittests.py::AllPlatformTests::test_identical_target_name_in_subproject_flat_layout", "run_unittests.py::AllPlatformTests::test_install_introspection", "run_unittests.py::AllPlatformTests::test_internal_include_order", "run_unittests.py::AllPlatformTests::test_libdir_must_be_inside_prefix", "run_unittests.py::AllPlatformTests::test_markdown_files_in_sitemap", "run_unittests.py::AllPlatformTests::test_ndebug_if_release_disabled", "run_unittests.py::AllPlatformTests::test_ndebug_if_release_enabled", "run_unittests.py::AllPlatformTests::test_permitted_method_kwargs", "run_unittests.py::AllPlatformTests::test_pkgconfig_gen_escaping", "run_unittests.py::AllPlatformTests::test_pkgconfig_static", "run_unittests.py::AllPlatformTests::test_prebuilt_object", "run_unittests.py::AllPlatformTests::test_prebuilt_shared_lib", "run_unittests.py::AllPlatformTests::test_prebuilt_static_lib", "run_unittests.py::AllPlatformTests::test_prefix_dependent_defaults", "run_unittests.py::AllPlatformTests::test_preprocessor_checks_CPPFLAGS", "run_unittests.py::AllPlatformTests::test_rpath_uses_ORIGIN", "run_unittests.py::AllPlatformTests::test_run_target_files_path", "run_unittests.py::AllPlatformTests::test_same_d_option_twice", "run_unittests.py::AllPlatformTests::test_same_d_option_twice_configure", "run_unittests.py::AllPlatformTests::test_same_dash_option_twice", "run_unittests.py::AllPlatformTests::test_same_dash_option_twice_configure", "run_unittests.py::AllPlatformTests::test_same_project_d_option_twice", "run_unittests.py::AllPlatformTests::test_same_project_d_option_twice_configure", "run_unittests.py::AllPlatformTests::test_source_changes_cause_rebuild", "run_unittests.py::AllPlatformTests::test_static_compile_order", "run_unittests.py::AllPlatformTests::test_static_library_lto", "run_unittests.py::AllPlatformTests::test_static_library_overwrite", "run_unittests.py::AllPlatformTests::test_subproject_promotion", "run_unittests.py::AllPlatformTests::test_suite_selection", "run_unittests.py::AllPlatformTests::test_templates", "run_unittests.py::AllPlatformTests::test_testsetup_selection", "run_unittests.py::AllPlatformTests::test_testsetups", "run_unittests.py::AllPlatformTests::test_uninstall", "run_unittests.py::AllPlatformTests::test_warning_location", "run_unittests.py::FailureTests::test_apple_frameworks_dependency", "run_unittests.py::FailureTests::test_boost_BOOST_ROOT_dependency", "run_unittests.py::FailureTests::test_boost_notfound_dependency", "run_unittests.py::FailureTests::test_dependency", "run_unittests.py::FailureTests::test_dependency_invalid_method", "run_unittests.py::FailureTests::test_dict_forbids_duplicate_keys", "run_unittests.py::FailureTests::test_dict_forbids_integer_key", "run_unittests.py::FailureTests::test_dict_requires_key_value_pairs", "run_unittests.py::FailureTests::test_exception_exit_status", "run_unittests.py::FailureTests::test_gnustep_notfound_dependency", "run_unittests.py::FailureTests::test_llvm_dependency", "run_unittests.py::FailureTests::test_objc_cpp_detection", "run_unittests.py::FailureTests::test_sdl2_notfound_dependency", "run_unittests.py::FailureTests::test_subproject_variables", "run_unittests.py::FailureTests::test_using_recent_feature", "run_unittests.py::FailureTests::test_using_too_recent_feature", "run_unittests.py::FailureTests::test_using_too_recent_feature_dependency", "run_unittests.py::FailureTests::test_wx_dependency", "run_unittests.py::FailureTests::test_wx_notfound_dependency", "run_unittests.py::WindowsTests::test_find_program", "run_unittests.py::WindowsTests::test_ignore_libs", "run_unittests.py::WindowsTests::test_rc_depends_files", "run_unittests.py::LinuxlikeTests::test_apple_bitcode", "run_unittests.py::LinuxlikeTests::test_apple_bitcode_modules", "run_unittests.py::LinuxlikeTests::test_basic_soname", "run_unittests.py::LinuxlikeTests::test_build_rpath", "run_unittests.py::LinuxlikeTests::test_compiler_c_stds", "run_unittests.py::LinuxlikeTests::test_compiler_check_flags_order", "run_unittests.py::LinuxlikeTests::test_compiler_cpp_stds", "run_unittests.py::LinuxlikeTests::test_coverage", "run_unittests.py::LinuxlikeTests::test_cpp_std_override", "run_unittests.py::LinuxlikeTests::test_cross_find_program", "run_unittests.py::LinuxlikeTests::test_custom_soname", "run_unittests.py::LinuxlikeTests::test_install_umask", "run_unittests.py::LinuxlikeTests::test_installed_modes", "run_unittests.py::LinuxlikeTests::test_installed_modes_extended", "run_unittests.py::LinuxlikeTests::test_installed_soname", "run_unittests.py::LinuxlikeTests::test_introspect_dependencies", "run_unittests.py::LinuxlikeTests::test_old_gnome_module_codepaths", "run_unittests.py::LinuxlikeTests::test_order_of_l_arguments", "run_unittests.py::LinuxlikeTests::test_pch_with_address_sanitizer", "run_unittests.py::LinuxlikeTests::test_pic", "run_unittests.py::LinuxlikeTests::test_pkg_unfound", "run_unittests.py::LinuxlikeTests::test_pkgconfig_formatting", "run_unittests.py::LinuxlikeTests::test_pkgconfig_gen", "run_unittests.py::LinuxlikeTests::test_pkgconfig_gen_deps", "run_unittests.py::LinuxlikeTests::test_pkgconfig_internal_libraries", "run_unittests.py::LinuxlikeTests::test_pkgconfig_usage", "run_unittests.py::LinuxlikeTests::test_qt5dependency_pkgconfig_detection", "run_unittests.py::LinuxlikeTests::test_qt5dependency_qmake_detection", "run_unittests.py::LinuxlikeTests::test_reconfigure", "run_unittests.py::LinuxlikeTests::test_run_installed", "run_unittests.py::LinuxlikeTests::test_soname", "run_unittests.py::LinuxlikeTests::test_unity_subproj", "run_unittests.py::LinuxlikeTests::test_usage_external_library", "run_unittests.py::LinuxlikeTests::test_vala_c_warnings", "run_unittests.py::LinuxlikeTests::test_vala_generated_source_buildir_inside_source_tree", "run_unittests.py::LinuxArmCrossCompileTests::test_cflags_cross_environment_pollution", "run_unittests.py::LinuxArmCrossCompileTests::test_cross_file_overrides_always_args", "run_unittests.py::PythonTests::test_versions", "run_unittests.py::RewriterTests::test_basic", "run_unittests.py::RewriterTests::test_subdir" ]
[ "run_unittests.py::InternalTests::test_compiler_args_class", "run_unittests.py::InternalTests::test_extract_as_list", "run_unittests.py::InternalTests::test_listify", "run_unittests.py::InternalTests::test_mode_symbolic_to_bits", "run_unittests.py::InternalTests::test_needs_exe_wrapper_override", "run_unittests.py::InternalTests::test_pkgconfig_module", "run_unittests.py::InternalTests::test_snippets", "run_unittests.py::InternalTests::test_string_templates_substitution", "run_unittests.py::InternalTests::test_version_number" ]
[]
Apache License 2.0
2,758
514
[ "mesonbuild/compilers/c.py", "mesonbuild/compilers/compilers.py" ]
valohai__valohai-cli-33
fbdad62d3e4177586622e18a53c30fe4f081416a
2018-07-11 15:20:44
b909441d803e87ff45f51d34e40f3aed396bd1a8
codecov[bot]: # [Codecov](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=h1) Report > Merging [#33](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=desc) into [master](https://codecov.io/gh/valohai/valohai-cli/commit/b909441d803e87ff45f51d34e40f3aed396bd1a8?src=pr&el=desc) will **increase** coverage by `0.09%`. > The diff coverage is `91.8%`. [![Impacted file tree graph](https://codecov.io/gh/valohai/valohai-cli/pull/33/graphs/tree.svg?src=pr&token=xqgKRx94XH&width=650&height=150)](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #33 +/- ## ========================================== + Coverage 89.39% 89.49% +0.09% ========================================== Files 79 81 +2 Lines 2056 2113 +57 Branches 262 271 +9 ========================================== + Hits 1838 1891 +53 - Misses 131 133 +2 - Partials 87 89 +2 ``` | [Impacted Files](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [valohai\_cli/utils/cli\_utils.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvdXRpbHMvY2xpX3V0aWxzLnB5) | `70.58% <ø> (ø)` | | | [valohai\_cli/utils/\_\_init\_\_.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvdXRpbHMvX19pbml0X18ucHk=) | `81.31% <ø> (ø)` | | | [valohai\_cli/commands/execution/run.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvY29tbWFuZHMvZXhlY3V0aW9uL3J1bi5weQ==) | `81.51% <100%> (+2.87%)` | :arrow_up: | | [valohai\_cli/commands/project/link.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvY29tbWFuZHMvcHJvamVjdC9saW5rLnB5) | `91.48% <100%> (ø)` | :arrow_up: | | [valohai\_cli/yaml\_wizard.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkveWFtbF93aXphcmQucHk=) | `95.23% <100%> (ø)` | :arrow_up: | | [tests/commands/execution/test\_run.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dGVzdHMvY29tbWFuZHMvZXhlY3V0aW9uL3Rlc3RfcnVuLnB5) | `100% <100%> (ø)` | :arrow_up: | | [valohai\_cli/git.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvZ2l0LnB5) | `88.23% <50%> (+0.73%)` | :arrow_up: | | [valohai\_cli/utils/levenshtein.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvdXRpbHMvbGV2ZW5zaHRlaW4ucHk=) | `80% <80%> (ø)` | | | [valohai\_cli/utils/friendly\_option\_parser.py](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree#diff-dmFsb2hhaV9jbGkvdXRpbHMvZnJpZW5kbHlfb3B0aW9uX3BhcnNlci5weQ==) | `90% <90%> (ø)` | | | ... and [1 more](https://codecov.io/gh/valohai/valohai-cli/pull/33/diff?src=pr&el=tree-more) | | ------ [Continue to review full report at Codecov](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=footer). Last update [b909441...8a10837](https://codecov.io/gh/valohai/valohai-cli/pull/33?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
diff --git a/valohai_cli/commands/execution/run.py b/valohai_cli/commands/execution/run.py index d266ee9..83527ec 100644 --- a/valohai_cli/commands/execution/run.py +++ b/valohai_cli/commands/execution/run.py @@ -1,3 +1,5 @@ +import re + import click from click.exceptions import BadParameter from click.globals import get_current_context @@ -9,10 +11,29 @@ import valohai_cli.git as git # this import style required for tests from valohai_cli.adhoc import create_adhoc_commit from valohai_cli.api import request from valohai_cli.ctx import get_project -from valohai_cli.messages import success, warn, error +from valohai_cli.utils.friendly_option_parser import FriendlyOptionParser +from valohai_cli.messages import success, warn from valohai_cli.utils import humanize_identifier, match_prefix +def sanitize_name(name): + return re.sub(r'[_ ]', '-', name) + + +def generate_sanitized_options(name): + seen = set() + for choice in ( + '--%s' % name, + '--%s' % sanitize_name(name), + ('--%s' % sanitize_name(name)).lower(), + ): + if ' ' in choice: + continue + if choice not in seen: + seen.add(choice) + yield choice + + class RunCommand(click.Command): """ A dynamically-generated subcommand that has Click options for parameters and inputs. @@ -47,7 +68,7 @@ class RunCommand(click.Command): self.image = image self.watch = bool(watch) super(RunCommand, self).__init__( - name=step.name.lower().replace(' ', '-'), + name=sanitize_name(step.name.lower()), callback=self.execute, add_help_option=True, ) @@ -65,9 +86,7 @@ class RunCommand(click.Command): """ assert isinstance(parameter, Parameter) option = click.Option( - param_decls=[ - '--%s' % parameter.name.replace('_', '-'), - ], + param_decls=list(generate_sanitized_options(parameter.name)), required=(parameter.default is None and not parameter.optional), default=parameter.default, help=parameter.description, @@ -85,9 +104,7 @@ class RunCommand(click.Command): """ assert isinstance(input, Input) option = click.Option( - param_decls=[ - '--%s' % input.name.replace('_', '-'), - ], + param_decls=list(generate_sanitized_options(input.name)), required=(input.default is None and not input.optional), default=input.default, metavar='URL', @@ -154,6 +171,14 @@ class RunCommand(click.Command): return commit + def make_parser(self, ctx): + parser = super(RunCommand, self).make_parser(ctx) + # This is somewhat naughty, but allows us to easily hook into here. + # Besides, FriendlyOptionParser does inherit from OptionParser anyway, + # and just overrides that one piece of behavior... + parser.__class__ = FriendlyOptionParser + return parser + @click.command(context_settings=dict(ignore_unknown_options=True), add_help_option=False) @click.argument('step') diff --git a/valohai_cli/commands/project/link.py b/valohai_cli/commands/project/link.py index 430c986..f699516 100644 --- a/valohai_cli/commands/project/link.py +++ b/valohai_cli/commands/project/link.py @@ -1,7 +1,7 @@ import click from valohai_cli.api import request -from valohai_cli.cli_utils import prompt_from_list +from valohai_cli.utils.cli_utils import prompt_from_list from valohai_cli.commands.project.create import create_project from valohai_cli.consts import yes_option from valohai_cli.ctx import get_project, set_project_link diff --git a/valohai_cli/git.py b/valohai_cli/git.py index 47e4664..95c7776 100644 --- a/valohai_cli/git.py +++ b/valohai_cli/git.py @@ -1,3 +1,4 @@ +import os import subprocess from valohai_cli.exceptions import NoGitRepo @@ -10,9 +11,10 @@ def check_git_output(args, directory): cwd=directory, shell=False, stderr=subprocess.STDOUT, + env=dict(os.environ, LC_ALL='C'), ) except subprocess.CalledProcessError as cpe: - if cpe.returncode == 128 and 'Not a git repository' in cpe.output.decode(): + if cpe.returncode == 128 and 'not a git repository' in cpe.output.decode().lower(): raise NoGitRepo(directory) raise diff --git a/valohai_cli/utils.py b/valohai_cli/utils/__init__.py similarity index 100% rename from valohai_cli/utils.py rename to valohai_cli/utils/__init__.py diff --git a/valohai_cli/cli_utils.py b/valohai_cli/utils/cli_utils.py similarity index 100% rename from valohai_cli/cli_utils.py rename to valohai_cli/utils/cli_utils.py diff --git a/valohai_cli/utils/friendly_option_parser.py b/valohai_cli/utils/friendly_option_parser.py new file mode 100644 index 0000000..0c8c134 --- /dev/null +++ b/valohai_cli/utils/friendly_option_parser.py @@ -0,0 +1,26 @@ +from click import OptionParser, NoSuchOption + +from .levenshtein import levenshtein + + +class FriendlyOptionParser(OptionParser): + """ + A friendlier version of OptionParser that uses Levenshtein distances to figure out + if the user has just misspelled an option name. + """ + def _match_long_opt(self, opt, explicit_value, state): + try: + return super(FriendlyOptionParser, self)._match_long_opt(opt, explicit_value, state) + except NoSuchOption as nse: + if not nse.possibilities: + # No possibilities were guessed, so attempt some deeper magic + nse.possibilities = [ + word + for word + in self._long_opt + if levenshtein( + word.lower().lstrip('-'), + nse.option_name.lower().lstrip('-'), + ) <= 4 + ] + raise diff --git a/valohai_cli/utils/levenshtein.py b/valohai_cli/utils/levenshtein.py new file mode 100644 index 0000000..940b974 --- /dev/null +++ b/valohai_cli/utils/levenshtein.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +# From http://hetland.org/coding/python/levenshtein.py, which is in the public domain. + + +def levenshtein(a, b): + "Calculates the Levenshtein distance between a and b." + n, m = len(a), len(b) + if n > m: + # Make sure n <= m, to use O(min(n,m)) space + a, b = b, a + n, m = m, n + + current = range(n + 1) + for i in range(1, m + 1): + previous, current = current, [i] + [0] * n + for j in range(1, n + 1): + add, delete = previous[j] + 1, current[j - 1] + 1 + change = previous[j - 1] + if a[j - 1] != b[i - 1]: + change = change + 1 + current[j] = min(add, delete, change) + + return current[n] diff --git a/valohai_cli/yaml_wizard.py b/valohai_cli/yaml_wizard.py index b18d36b..a00fdf3 100644 --- a/valohai_cli/yaml_wizard.py +++ b/valohai_cli/yaml_wizard.py @@ -5,7 +5,7 @@ import click import requests import yaml -from valohai_cli.cli_utils import prompt_from_list +from valohai_cli.utils.cli_utils import prompt_from_list from valohai_cli.messages import error, success, warn from valohai_cli.utils import find_scripts
Step parameters with spaces don't work Passing step parameters with spaces does't work, it does use such default parameters fine though. Maybe we should require a separate `id` attribute in params for this? Or should we just slugify the name? Or enforce more strict naming for parameters? Example below. =========== ``` (valohai-cli) bog:darknet-example ruksi$ vh exec run --step="Generate text" --'Textual Seed'=1 Usage: vh execution run [OPTIONS] [ARGS]... Error: no such option: --Textual Seed ```
valohai/valohai-cli
diff --git a/tests/commands/execution/test_run.py b/tests/commands/execution/test_run.py index 2b90142..fc78001 100644 --- a/tests/commands/execution/test_run.py +++ b/tests/commands/execution/test_run.py @@ -117,3 +117,35 @@ def test_run_no_git(runner, logged_in_and_linked): with RunAPIMock(project_id, None, {}): output = runner.invoke(run, args, catch_exceptions=False).output assert 'is not a Git repository' in output + + +def test_param_input_sanitization(runner, logged_in_and_linked): + with open(get_project().get_config_filename(), 'w') as yaml_fp: + yaml_fp.write(''' +- step: + name: Train model + image: busybox + command: "false" + inputs: + - name: Ridiculously Complex Input_Name + default: http://example.com/ + parameters: + - name: Parameter With Highly Convoluted Name + pass-as: --simple={v} + type: integer + default: 1 +''') + output = runner.invoke(run, ['train', '--help'], catch_exceptions=False).output + assert '--Parameter-With-Highly-Convoluted-Name' in output + assert '--parameter-with-highly-convoluted-name' in output + assert '--Ridiculously-Complex-Input-Name' in output + assert '--ridiculously-complex-input-name' in output + + +def test_typo_check(runner, logged_in_and_linked): + with open(get_project().get_config_filename(), 'w') as yaml_fp: + yaml_fp.write(CONFIG_YAML) + args = ['train', '--max-setps=80'] # Oopsy! + output = runner.invoke(run, args, catch_exceptions=False).output + assert '(Possible options:' in output + assert '--max-steps' in output
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 4 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "requests-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5.2", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 distlib==0.3.9 filelock==3.4.1 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonschema==3.2.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 PyYAML==6.0.1 requests==2.27.1 requests-mock==1.12.1 requests-toolbelt==1.0.0 six==1.17.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 -e git+https://github.com/valohai/valohai-cli.git@fbdad62d3e4177586622e18a53c30fe4f081416a#egg=valohai_cli valohai-yaml==0.25.2 virtualenv==20.17.1 zipp==3.6.0
name: valohai-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonschema==3.2.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - pyyaml==6.0.1 - requests==2.27.1 - requests-mock==1.12.1 - requests-toolbelt==1.0.0 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - valohai-yaml==0.25.2 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/valohai-cli
[ "tests/commands/execution/test_run.py::test_run_no_git", "tests/commands/execution/test_run.py::test_param_input_sanitization", "tests/commands/execution/test_run.py::test_typo_check" ]
[ "tests/commands/execution/test_run.py::test_param_type_validation" ]
[ "tests/commands/execution/test_run.py::test_run_requires_step", "tests/commands/execution/test_run.py::test_run[regular-False-False-False]", "tests/commands/execution/test_run.py::test_run[regular-False-False-True]", "tests/commands/execution/test_run.py::test_run[regular-False-True-False]", "tests/commands/execution/test_run.py::test_run[regular-False-True-True]", "tests/commands/execution/test_run.py::test_run[regular-True-False-False]", "tests/commands/execution/test_run.py::test_run[regular-True-False-True]", "tests/commands/execution/test_run.py::test_run[regular-True-True-False]", "tests/commands/execution/test_run.py::test_run[regular-True-True-True]", "tests/commands/execution/test_run.py::test_run[adhoc-False-False-False]", "tests/commands/execution/test_run.py::test_run[adhoc-False-False-True]", "tests/commands/execution/test_run.py::test_run[adhoc-False-True-False]", "tests/commands/execution/test_run.py::test_run[adhoc-False-True-True]", "tests/commands/execution/test_run.py::test_run[adhoc-True-False-False]", "tests/commands/execution/test_run.py::test_run[adhoc-True-False-True]", "tests/commands/execution/test_run.py::test_run[adhoc-True-True-False]", "tests/commands/execution/test_run.py::test_run[adhoc-True-True-True]" ]
[]
MIT License
2,762
2,033
[ "valohai_cli/commands/execution/run.py", "valohai_cli/commands/project/link.py", "valohai_cli/git.py", "valohai_cli/yaml_wizard.py" ]
dwavesystems__dimod-219
54303f184427d1b3a2741cfb7ea1b1263f68a361
2018-07-11 18:33:24
8ebfffa42319aa4850cfc5a1c99a8711eac44722
diff --git a/dimod/response.py b/dimod/response.py index 1378ed70..e2b30309 100644 --- a/dimod/response.py +++ b/dimod/response.py @@ -230,7 +230,7 @@ class Response(Iterable, Sized): True """ - return all(future.done() for future in self._futures) + return all(future.done() for future in self._futures.get('futures', tuple())) ############################################################################################## # Construction and updates @@ -559,7 +559,7 @@ class Response(Iterable, Sized): response = cls.empty(vartype) # now dump all of the remaining information into the _futures - response._futures = {'futures': futures, + response._futures = {'futures': list(futures), 'samples_key': samples_key, 'data_vector_keys': data_vector_keys, 'info_keys': info_keys,
Response futures appear to be strings? ``` from dwave.system.samplers import DWaveSampler sampler = DWaveSampler(profile='BAY4') h = {} J = {(0, 4): -1} response = sampler.sample_ising(h, J, num_reads=10) print response.done() ``` yields ``` AttributeError: 'str' object has no attribute 'done' ``` If I print `response._futures` right after creating the response, I get ``` {'ignore_extra_keys': True, 'samples_key': 'samples', 'futures': (<dwave.cloud.computation.Future object at 0x7f31793d8110>,), 'data_vector_keys': {'energies': 'energy', 'num_occurrences': 'num_occurrences'}, 'active_variables': [0, 4], 'variable_labels': [0, 4], 'info_keys': {'timing': 'timing'}} ``` Is it possible `response._futures` is temporarily overwritten somewhere? Apparently yes, `response._futures` can hold something else than futures: at https://github.com/dwavesystems/dimod/blob/master/dimod/response.py#L561, it gets populated with a bunch of stuff, including non-futures. So `response._futures` can be different things at different stages of the response ... :-1:
dwavesystems/dimod
diff --git a/tests/test_response.py b/tests/test_response.py index bd18948e..c3c0ddf3 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -301,6 +301,8 @@ class TestResponse(unittest.TestCase): response = dimod.Response.from_futures(_futures(), vartype=dimod.SPIN, num_variables=3) + self.assertTrue(response.done()) + matrix = response.samples_matrix npt.assert_equal(matrix, np.matrix([[-1, -1, 1], [-1, -1, 1]]))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 decorator==5.1.1 -e git+https://github.com/dwavesystems/dimod.git@54303f184427d1b3a2741cfb7ea1b1263f68a361#egg=dimod docutils==0.18.1 enum34==1.1.6 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 jsonschema==2.6.0 MarkupSafe==2.0.1 mock==2.0.0 networkx==2.0 numpy==1.11.3 packaging==21.3 pandas==0.22.0 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 six==1.11.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: dimod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - docutils==0.18.1 - enum34==1.1.6 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - jsonschema==2.6.0 - markupsafe==2.0.1 - mock==2.0.0 - networkx==2.0 - numpy==1.11.3 - packaging==21.3 - pandas==0.22.0 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - six==1.11.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/dimod
[ "tests/test_response.py::TestResponse::test_from_futures" ]
[]
[ "tests/test_response.py::TestResponse::test__iter__", "tests/test_response.py::TestResponse::test_change_vartype_copy", "tests/test_response.py::TestResponse::test_change_vartype_inplace", "tests/test_response.py::TestResponse::test_data_docstrings", "tests/test_response.py::TestResponse::test_data_vectors_are_arrays", "tests/test_response.py::TestResponse::test_data_vectors_copy", "tests/test_response.py::TestResponse::test_data_vectors_not_array_like", "tests/test_response.py::TestResponse::test_data_vectors_wrong_length", "tests/test_response.py::TestResponse::test_empty", "tests/test_response.py::TestResponse::test_from_dicts", "tests/test_response.py::TestResponse::test_from_dicts_unlike_labels", "tests/test_response.py::TestResponse::test_from_dicts_unsortable_labels", "tests/test_response.py::TestResponse::test_from_futures_column_subset", "tests/test_response.py::TestResponse::test_from_futures_extra_keys", "tests/test_response.py::TestResponse::test_from_futures_typical", "tests/test_response.py::TestResponse::test_from_matrix", "tests/test_response.py::TestResponse::test_from_pandas", "tests/test_response.py::TestResponse::test_infer_vartype", "tests/test_response.py::TestResponse::test_instantiation", "tests/test_response.py::TestResponse::test_instantiation_without_energy", "tests/test_response.py::TestResponse::test_partial_relabel", "tests/test_response.py::TestResponse::test_partial_relabel_inplace", "tests/test_response.py::TestResponse::test_relabel_copy", "tests/test_response.py::TestResponse::test_relabel_docstring", "tests/test_response.py::TestResponse::test_samples_num_limited", "tests/test_response.py::TestResponse::test_update", "tests/test_response.py::TestResponse::test_update_energy" ]
[]
Apache License 2.0
2,764
234
[ "dimod/response.py" ]
dwavesystems__dimod-220
54303f184427d1b3a2741cfb7ea1b1263f68a361
2018-07-11 18:39:01
8ebfffa42319aa4850cfc5a1c99a8711eac44722
diff --git a/dimod/response.py b/dimod/response.py index 1378ed70..89891418 100644 --- a/dimod/response.py +++ b/dimod/response.py @@ -230,7 +230,7 @@ class Response(Iterable, Sized): True """ - return all(future.done() for future in self._futures) + return all(future.done() for future in self._futures.get('futures', tuple())) ############################################################################################## # Construction and updates @@ -421,7 +421,7 @@ class Response(Iterable, Sized): import pandas as pd variable_labels = list(samples_df.columns) - samples_matrix = samples_df.as_matrix(columns=variable_labels) + samples_matrix = np.matrix(samples_df.values) if isinstance(data_vectors, pd.DataFrame): raise NotImplementedError("support for DataFrame data_vectors is forthcoming") @@ -559,7 +559,7 @@ class Response(Iterable, Sized): response = cls.empty(vartype) # now dump all of the remaining information into the _futures - response._futures = {'futures': futures, + response._futures = {'futures': list(futures), 'samples_key': samples_key, 'data_vector_keys': data_vector_keys, 'info_keys': info_keys,
numpy FutureWarning FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead. samples_matrix = samples_df.as_matrix(columns=variable_labels)
dwavesystems/dimod
diff --git a/tests/test_response.py b/tests/test_response.py index bd18948e..c3c0ddf3 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -301,6 +301,8 @@ class TestResponse(unittest.TestCase): response = dimod.Response.from_futures(_futures(), vartype=dimod.SPIN, num_variables=3) + self.assertTrue(response.done()) + matrix = response.samples_matrix npt.assert_equal(matrix, np.matrix([[-1, -1, 1], [-1, -1, 1]]))
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 decorator==5.1.1 -e git+https://github.com/dwavesystems/dimod.git@54303f184427d1b3a2741cfb7ea1b1263f68a361#egg=dimod docutils==0.18.1 enum34==1.1.6 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 jsonschema==2.6.0 MarkupSafe==2.0.1 mock==2.0.0 networkx==2.0 numpy==1.11.3 packaging==21.3 pandas==0.22.0 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 six==1.11.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: dimod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - docutils==0.18.1 - enum34==1.1.6 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - jsonschema==2.6.0 - markupsafe==2.0.1 - mock==2.0.0 - networkx==2.0 - numpy==1.11.3 - packaging==21.3 - pandas==0.22.0 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - six==1.11.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/dimod
[ "tests/test_response.py::TestResponse::test_from_futures" ]
[]
[ "tests/test_response.py::TestResponse::test__iter__", "tests/test_response.py::TestResponse::test_change_vartype_copy", "tests/test_response.py::TestResponse::test_change_vartype_inplace", "tests/test_response.py::TestResponse::test_data_docstrings", "tests/test_response.py::TestResponse::test_data_vectors_are_arrays", "tests/test_response.py::TestResponse::test_data_vectors_copy", "tests/test_response.py::TestResponse::test_data_vectors_not_array_like", "tests/test_response.py::TestResponse::test_data_vectors_wrong_length", "tests/test_response.py::TestResponse::test_empty", "tests/test_response.py::TestResponse::test_from_dicts", "tests/test_response.py::TestResponse::test_from_dicts_unlike_labels", "tests/test_response.py::TestResponse::test_from_dicts_unsortable_labels", "tests/test_response.py::TestResponse::test_from_futures_column_subset", "tests/test_response.py::TestResponse::test_from_futures_extra_keys", "tests/test_response.py::TestResponse::test_from_futures_typical", "tests/test_response.py::TestResponse::test_from_matrix", "tests/test_response.py::TestResponse::test_from_pandas", "tests/test_response.py::TestResponse::test_infer_vartype", "tests/test_response.py::TestResponse::test_instantiation", "tests/test_response.py::TestResponse::test_instantiation_without_energy", "tests/test_response.py::TestResponse::test_partial_relabel", "tests/test_response.py::TestResponse::test_partial_relabel_inplace", "tests/test_response.py::TestResponse::test_relabel_copy", "tests/test_response.py::TestResponse::test_relabel_docstring", "tests/test_response.py::TestResponse::test_samples_num_limited", "tests/test_response.py::TestResponse::test_update", "tests/test_response.py::TestResponse::test_update_energy" ]
[]
Apache License 2.0
2,765
317
[ "dimod/response.py" ]
wright-group__WrightTools-665
32e4571ed7acb3c1b7588d5857785d9d91d3bd18
2018-07-12 21:12:08
6e0c301b1f703527709a2669bbde785255254239
pep8speaks: Hello @darienmorrow! Thanks for submitting the PR. - In the file [`WrightTools/kit/_calculate.py`](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py), following are the PEP8 issues : > [Line 21:67](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L21): [W291](https://duckduckgo.com/?q=pep8%20W291) trailing whitespace > [Line 24:1](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L24): [W293](https://duckduckgo.com/?q=pep8%20W293) blank line contains whitespace > [Line 44:61](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L44): [W291](https://duckduckgo.com/?q=pep8%20W291) trailing whitespace > [Line 45:73](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L45): [W291](https://duckduckgo.com/?q=pep8%20W291) trailing whitespace > [Line 51:1](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L51): [W293](https://duckduckgo.com/?q=pep8%20W293) blank line contains whitespace > [Line 56:40](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L56): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 60:34](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L60): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 61:17](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L61): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 62:22](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L62): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 64:58](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L64): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 65:30](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L65): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 66:30](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L66): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 67:25](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L67): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 69:78](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L69): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 70:24](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L70): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 71:27](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L71): [E261](https://duckduckgo.com/?q=pep8%20E261) at least two spaces before inline comment > [Line 76:1](https://github.com/wright-group/WrightTools/blob/4e15e503274465ef90aaa870da00ab2f112e4de1/WrightTools/kit/_calculate.py#L76): [W293](https://duckduckgo.com/?q=pep8%20W293) blank line contains whitespace ksunden: we may wish to look at `unyt` to simplify the computation here, perhaps. I'm considering replacing the custom code in the `units` package with that library, which has some potential positive side effects ksunden: Also, the pep8 warning still mentioned above are all in the docstring (which is why `black` didn't catch it) I believe `autopep8` will catch that if you don't feel like tracking those down manually ksunden: https://github.com/ambv/black/issues/318 (`black` will NOT handle this case, as there exist cases [perhaps poorly reasoned, but still] where doing so will affect correctness of the program, and `black` commits to not making any such changes) darienmorrow: @ksunden The reason I am not checking the value is because that requires me to be 100% sure about the correct value of the calculation. I am waiting for someone to check my math before I do that. darienmorrow: @ksunden The reason I do not check for the value in my test is because checking for the value requires me to be absolutely sure about the result of my calculation. I was hoping for someone to check my math before I specify values. darienmorrow: @ksunden I now check the value in the test. ksunden: Im holding off rereviewing until the math itself is approved, I would like to check thebither two outputs as well in the test, please.
diff --git a/WrightTools/data/_data.py b/WrightTools/data/_data.py index a48cf49..1124658 100644 --- a/WrightTools/data/_data.py +++ b/WrightTools/data/_data.py @@ -625,7 +625,7 @@ class Data(Group): New data object with the downscaled channels and axes """ if name is None: - name = self.natural_name + '_downscaled' + name = self.natural_name + "_downscaled" if parent is None: newdata = Data(name=name) else: @@ -633,13 +633,13 @@ class Data(Group): for channel in self.channels: name = channel.natural_name - newdata.create_channel(name=name, - values=downscale_local_mean(channel[:], tup), - units=channel.units) + newdata.create_channel( + name=name, values=downscale_local_mean(channel[:], tup), units=channel.units + ) args = [] for i, axis in enumerate(self.axes): if len(axis.variables) > 1: - raise NotImplementedError('downscale only works with simple axes currently') + raise NotImplementedError("downscale only works with simple axes currently") variable = axis.variables[0] name = variable.natural_name args.append(name) diff --git a/WrightTools/kit/_calculate.py b/WrightTools/kit/_calculate.py index 3af381c..16ef7d2 100644 --- a/WrightTools/kit/_calculate.py +++ b/WrightTools/kit/_calculate.py @@ -1,7 +1,7 @@ """Calculate.""" -# --- import -------------------------------------------------------------------------------------- +# --- import ------------------------------------------------------------- import numpy as np @@ -9,13 +9,78 @@ import numpy as np from .. import units as wt_units -# --- define -------------------------------------------------------------------------------------- +# --- define ------------------------------------------------------------- -__all__ = ["mono_resolution", "nm_width", "symmetric_sqrt"] +__all__ = ["fluence", "mono_resolution", "nm_width", "symmetric_sqrt"] -# --- functions ----------------------------------------------------------------------------------- +# --- functions ---------------------------------------------------------- + + +def fluence( + power_mW, + color, + beam_radius, + reprate_Hz, + pulse_width, + color_units="wn", + beam_radius_units="mm", + pulse_width_units="fs_t", + area_type="even", +): + """Calculate the fluence of a beam. + + Parameters + ---------- + power_mW : number + Time integrated power of beam. + color : number + Color of beam in units. + beam_radius : number + Radius of beam in units. + reprate_Hz : number + Laser repetition rate in inverse seconds (Hz). + pulse_width : number + Pulsewidth of laser in units + color_units : string (optional) + Valid wt.units color unit identifier. Default is wn. + beam_radius_units : string (optional) + Valid wt.units distance unit identifier. Default is mm. + pulse_width_units : number + Valid wt.units time unit identifier. Default is fs. + area_type : string (optional) + Type of calculation to accomplish for Gaussian area. + Currently nothing other than the default of even is implemented. + + Returns + ------- + tuple + Fluence in uj/cm2, photons/cm2, and peak intensity in GW/cm2 + + """ + # calculate beam area + if area_type == "even": + radius_cm = wt_units.converter(beam_radius, beam_radius_units, "cm") + area_cm2 = np.pi * radius_cm ** 2 # cm^2 + else: + raise NotImplementedError + # calculate fluence in uj/cm^2 + ujcm2 = power_mW / reprate_Hz # mJ + ujcm2 *= 1e3 # uJ + ujcm2 /= area_cm2 # uJ/cm^2 + # calculate fluence in photons/cm^2 + energy = wt_units.converter(color, color_units, "eV") # eV + photonscm2 = ujcm2 * 1e-6 # J/cm2 + photonscm2 /= 1.60218e-19 # eV/cm2 + photonscm2 /= energy # photons/cm2 + # calculate peak intensity in GW/cm^2 + pulse_width_s = wt_units.converter(pulse_width, pulse_width_units, "s_t") # seconds + GWcm2 = ujcm2 / 1e6 # J/cm2 + GWcm2 /= pulse_width_s # W/cm2 + GWcm2 /= 1e9 + # finish + return ujcm2, photonscm2, GWcm2 def mono_resolution(grooves_per_mm, slit_width, focal_length, output_color, output_units="wn"):
Fluence calculation I oftentimes find myself needing to calculate a fluence from a power reading. I then go through ten minutes of unit conversions to do the calculation. I think we should make a function in `kit._calculate.py` that does this calculation. For instance: ``` def fluence(power_mW, reprate_Hz, photon_energy_eV, beam_radius_mm): return uj/cm2, photons/cm2 ``` Any thoughts?
wright-group/WrightTools
diff --git a/tests/kit/fluence.py b/tests/kit/fluence.py new file mode 100644 index 0000000..5355d64 --- /dev/null +++ b/tests/kit/fluence.py @@ -0,0 +1,20 @@ +"""Test fluence.""" + + +# --- import ------------------------------------------------------------- + + +import numpy as np + +import WrightTools as wt + + +# --- test --------------------------------------------------------------- + + +def test_0(): + out = wt.kit.fluence(1, 2, .1, 1000, 1, "eV", "cm", "ps_t") + checks = (31.83098, 99336493460095.2, 0.03183098) + assert np.isclose(checks[0], out[0], rtol=1e-3) + assert np.isclose(checks[1], out[1], rtol=1e-3) + assert np.isclose(checks[2], out[2], rtol=1e-3)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
3.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y libfreetype6-dev libopenblas-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
black==25.1.0 cfgv==3.4.0 click==8.1.8 contourpy==1.3.0 coverage==7.8.0 cycler==0.12.1 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 fonttools==4.56.0 h5py==3.13.0 identify==2.6.9 imageio==2.37.0 importlib_resources==6.5.2 iniconfig==2.1.0 kiwisolver==1.4.7 lazy_loader==0.4 matplotlib==3.9.4 mypy-extensions==1.0.0 networkx==3.2.1 nodeenv==1.9.1 numexpr==2.10.2 numpy==2.0.2 packaging==24.2 pathspec==0.12.1 pillow==11.1.0 platformdirs==4.3.7 pluggy==1.5.0 pre_commit==4.2.0 pydocstyle==6.3.0 pyparsing==3.2.3 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 scikit-image==0.24.0 scipy==1.13.1 six==1.17.0 snowballstemmer==2.2.0 swebench_matterhorn @ file:///swebench_matterhorn tidy_headers==1.0.4 tifffile==2024.8.30 tomli==2.2.1 typing_extensions==4.13.0 virtualenv==20.29.3 -e git+https://github.com/wright-group/WrightTools.git@32e4571ed7acb3c1b7588d5857785d9d91d3bd18#egg=WrightTools zipp==3.21.0
name: WrightTools channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - black==25.1.0 - cfgv==3.4.0 - click==8.1.8 - contourpy==1.3.0 - coverage==7.8.0 - cycler==0.12.1 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - fonttools==4.56.0 - h5py==3.13.0 - identify==2.6.9 - imageio==2.37.0 - importlib-resources==6.5.2 - iniconfig==2.1.0 - kiwisolver==1.4.7 - lazy-loader==0.4 - matplotlib==3.9.4 - mypy-extensions==1.0.0 - networkx==3.2.1 - nodeenv==1.9.1 - numexpr==2.10.2 - numpy==2.0.2 - packaging==24.2 - pathspec==0.12.1 - pillow==11.1.0 - platformdirs==4.3.7 - pluggy==1.5.0 - pre-commit==4.2.0 - pydocstyle==6.3.0 - pyparsing==3.2.3 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - scikit-image==0.24.0 - scipy==1.13.1 - six==1.17.0 - snowballstemmer==2.2.0 - swebench-matterhorn==0.0.0 - tidy-headers==1.0.4 - tifffile==2024.8.30 - tomli==2.2.1 - typing-extensions==4.13.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/WrightTools
[ "tests/kit/fluence.py::test_0" ]
[]
[]
[]
MIT License
2,770
1,157
[ "WrightTools/data/_data.py", "WrightTools/kit/_calculate.py" ]
fennekki__cdparacord-32
bcc53aad7774868d42e36cddc42da72abdf990c2
2018-07-14 09:40:21
ce0444604ac0d87ec586fd94b6c62096b10c3657
diff --git a/cdparacord/config.py b/cdparacord/config.py index 962327b..c7e52e3 100644 --- a/cdparacord/config.py +++ b/cdparacord/config.py @@ -30,13 +30,11 @@ class Config: __default_config = { # Config for the encoder 'encoder': { - 'lame': { - 'parameters': [ - '-V2', - '${one_file}', - '${out_file}' - ] - } + 'lame': [ + '-V2', + '${one_file}', + '${out_file}' + ] }, # Tasks follow the format of encoder # post_rip are run after an individual file has been ripped to a diff --git a/cdparacord/dependency.py b/cdparacord/dependency.py index 9f47b51..b2f165e 100644 --- a/cdparacord/dependency.py +++ b/cdparacord/dependency.py @@ -27,7 +27,7 @@ class Dependency: # dir. I don't think anyone wants that but they... might... return name - for path in os.environ["PATH"].split(os.pathsep): + for path in os.environ['PATH'].split(os.pathsep): path = path.strip('"') binname = os.path.join(path, name) if os.path.isfile(binname) and os.access(binname, os.X_OK): @@ -35,18 +35,53 @@ class Dependency: # If we haven't returned, the executable was not found raise DependencyError( - "Executable {} not found or not executable".format(name)) + 'Executable {} not found or not executable'.format(name)) + + def _verify_action_params(self, action): + """Confirm certain things about action configuration.""" + if len(action) > 1: + multiple_actions = ', '.join(action.keys()) + raise DependencyError( + 'Tried to configure multiple actions in one dict: {}' + .format(multiple_actions)) + + if len(action) < 1: + raise DependencyError( + 'Configuration opened an action dict but it had no keys') + + action_key = list(action.keys())[0] + action_params = action[action_key] + + if type(action_params) is not list: + raise DependencyError( + '{} configuration has type {} (list expected)' + .format(action_key, type(action_params).__name__)) + + for item in action_params: + if type(item) is not str: + raise DependencyError( + 'Found {} parameter {} with type {} (str expected)' + .format(action_key, item, type(item).__name__)) def _discover(self): """Discover dependencies and ensure they exist.""" - # Find the executables + # Find the executables, and verify parameters for post-actions + # and encoder self._encoder = self._find_executable( list(self._config.get('encoder').keys())[0]) + + self._verify_action_params(self._config.get('encoder')) + self._editor = self._find_executable(self._config.get('editor')) self._cdparanoia = self._find_executable( self._config.get('cdparanoia')) + for post_action in ('post_rip', 'post_encode', 'post_finished'): + for action in self._config.get(post_action): + self._find_executable(list(action.keys())[0]) + self._verify_action_params(action) + # Ensure discid is importable try: import discid @@ -54,7 +89,7 @@ class Dependency: # it would be ridiculous as it only depends on documented # behaviour and only raises a further exception. except OSError as e: # pragma: no cover - raise DependencyError("Could not find libdiscid") from e + raise DependencyError('Could not find libdiscid') from e @property def encoder(self):
Could not find "parameters". <!-- Describe your issue and what you'd like to be done about it quickly. If you intend to implement the solution yourself, you don't need to file a bug before a pull request. Note that the maintainer will only take note of issues added to the "continuous backlog" project. Click "Projects -> continous backlog" on the right hand side of the issue box and correctly tag your issue as "bug", "enhancement" or "question" depending on its purpose. This way it'll be visible in the work queue. --> Under some quite unknown circumstances, with at least one specific album (lnTlccHq6F8XNcvNFafPUyaw1mA-), a fresh git clone fails to encode on the first track and crashes. The script correctly rips track 1 and when it starts to encode there's an issue. After the rip... Prints: ``` Could not find "parameters". Can't init infile 'parameters' ``` And then raises: ``` File "cdparacord/rip.py", line 104, in _encode_track raise RipError('Failed to encode track {}'.format(track.filename)) ```
fennekki/cdparacord
diff --git a/tests/test_config.py b/tests/test_config.py index 0bc761c..1a85588 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -185,4 +185,40 @@ def test_update_config_unknown_keys(mock_temp_home, capsys): c.update({'invalid_key': True}, quiet_ignore=False) out, err = capsys.readouterr() - assert err == "Warning: Unknown configuration key invalid_key\n" + assert err == 'Warning: Unknown configuration key invalid_key\n' + +def test_ensure_default_encoder_keys_are_strings(mock_temp_home): + """Test default encoder configuration.""" + from cdparacord import config + + c = config.Config() + + assert len(c.get('encoder')) == 1 + + for encoder in c.get('encoder'): + encoder_params = c.get('encoder')[encoder] + # If it's not a list something's wrong + assert type(encoder_params) is list + + for item in encoder_params: + # And the params should be strings + assert type(item) is str + +def test_ensure_default_postaction_keys_are_strings(mock_temp_home): + """Test default encoder configuration.""" + from cdparacord import config + + c = config.Config() + + for post_action in ('post_rip', 'post_encode', 'post_finished'): + for action in c.get(post_action): + assert len(action) == 1 + + for action_key in action: + action_params = action[action_key] + # If it's not a list something's wrong + assert type(action_params) is list + + for item in action_params: + # And the params should be strings + assert type(item) is str diff --git a/tests/test_dependency.py b/tests/test_dependency.py index 96c0519..e7e92df 100644 --- a/tests/test_dependency.py +++ b/tests/test_dependency.py @@ -9,45 +9,57 @@ from cdparacord.dependency import Dependency, DependencyError @pytest.fixture -def mock_external_binary(): +def mock_config_external(): + """Mock the Config class such that it returns self.param. + + In addition, querying for encoder results in a dict that contains + an empty list in the key self.param. + """ + class MockConfig: + def __init__(self, param): + self.param = param + self.encoder = {self.param: []} + self.post = [{self.param: []}] + + def get(self, name): + # Maybe we should write a fake config file but there are + # Huge issues with mocking the config module... + if name == 'encoder': + return self.encoder + if name in ('post_rip', 'post_encode', 'post_finished'): + return self.post + return self.param + return MockConfig + + [email protected] +def mock_external_encoder(mock_config_external): """Mock an external dependency binary. - + Create a file, set it to be executable and return it as an - ostensible external binary. + ostensible external binary via configuration. """ with NamedTemporaryFile(prefix='cdparacord-unittest-') as f: os.chmod(f.name, stat.S_IXUSR) - yield f.name + conf = mock_config_external(f.name) + yield conf [email protected] -def mock_config_external(): - """Mock the Config class such that it always returns given name.""" - def get_config(mockbin): - class MockConfig: - def get(self, name): - # Maybe we should write a fake config file but there are - # Huge issues with mocking the config module... - if name == 'encoder': - return {mockbin: []} - return mockbin - return MockConfig() - return get_config - - -def test_find_valid_absolute_dependencies(mock_external_binary, mock_config_external): + +def test_find_valid_absolute_dependencies(mock_external_encoder): """Finds fake dependencies that exist by absolute path.""" - - Dependency(mock_config_external(mock_external_binary)) + Dependency(mock_external_encoder) -def test_find_valid_dependencies_in_path(mock_external_binary, mock_config_external, monkeypatch): +def test_find_valid_dependencies_in_path(mock_external_encoder, monkeypatch): """Finds fake dependencies that exist in $PATH.""" - dirname, basename = os.path.split(mock_external_binary) + dirname, basename = os.path.split(mock_external_encoder.param) # Set PATH to only contain the directory our things are in monkeypatch.setenv("PATH", dirname) - Dependency(mock_config_external(basename)) + conf = mock_external_encoder + conf.param = basename + Dependency(conf) def test_fail_to_find_dependencies(mock_config_external): @@ -55,28 +67,59 @@ def test_fail_to_find_dependencies(mock_config_external): # This file should not be executable by default so the finding # should fail with pytest.raises(DependencyError): - Dependency(mock_config_external(f.name)) + conf = mock_config_external(f.name) + Dependency(conf) -def test_get_encoder(mock_config_external, mock_external_binary): +def test_get_encoder(mock_external_encoder): """Get the 'encoder' property.""" - deps = Dependency(mock_config_external(mock_external_binary)) + deps = Dependency(mock_external_encoder) # It's an absolute path so the value should be the same - assert deps.encoder == mock_external_binary + assert deps.encoder == mock_external_encoder.param -def test_get_editor(mock_config_external, mock_external_binary): +def test_get_editor(mock_external_encoder): """Get the 'editor' property.""" - deps = Dependency(mock_config_external(mock_external_binary)) + deps = Dependency(mock_external_encoder) # It's an absolute path so the value should be the same - assert deps.editor == mock_external_binary + assert deps.editor == mock_external_encoder.param -def test_get_cdparanoia(mock_config_external, mock_external_binary): +def test_get_cdparanoia(mock_external_encoder): """Get the 'cdparanoia' property.""" - deps = Dependency(mock_config_external(mock_external_binary)) + deps = Dependency(mock_external_encoder) # It's an absolute path so the value should be the same - assert deps.cdparanoia == mock_external_binary + assert deps.cdparanoia == mock_external_encoder.param + +def test_verify_action_params(mock_external_encoder): + """Ensure encoder and post-action parameter verification works.""" + + conf = mock_external_encoder + deps = Dependency(conf) + + # Dict can only have one key + invalid_input = {'a': [], 'b': []} + with pytest.raises(DependencyError): + deps._verify_action_params(invalid_input) + + # Dict mustn't be empty + invalid_input = {} + with pytest.raises(DependencyError): + deps._verify_action_params(invalid_input) + + # Type of encoder param container should be list + invalid_input = {conf.param: {'ah', 'beh'}} + with pytest.raises(DependencyError): + deps._verify_action_params(invalid_input) + + # Type of encoder param items should be str + invalid_input = {conf.param: [1]} + with pytest.raises(DependencyError): + deps._verify_action_params(invalid_input) + + # Test valid + deps._verify_action_params({'valid': ['totally', 'valid']}) +
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "Pipfile", "pip_packages": [ "pytest", "coverage", "tox", "vulture" ], "pre_install": [ "apt-get update", "apt-get install -y libdiscid0" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 -e git+https://github.com/fennekki/cdparacord.git@bcc53aad7774868d42e36cddc42da72abdf990c2#egg=cdparacord certifi==2021.5.30 click==8.0.4 coverage==6.2 discid==1.2.0 distlib==0.3.9 filelock==3.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 musicbrainzngs==0.7.1 mutagen==1.45.1 packaging==21.3 pipfile==0.0.2 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 virtualenv==20.17.1 vulture==2.8 zipp==3.6.0
name: cdparacord channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - pipfile=0.0.2=py_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - click==8.0.4 - coverage==6.2 - discid==1.2.0 - distlib==0.3.9 - filelock==3.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - musicbrainzngs==0.7.1 - mutagen==1.45.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - virtualenv==20.17.1 - vulture==2.8 - zipp==3.6.0 prefix: /opt/conda/envs/cdparacord
[ "tests/test_config.py::test_ensure_default_encoder_keys_are_strings", "tests/test_dependency.py::test_verify_action_params" ]
[ "tests/test_config.py::test_fail_to_create_config_dir", "tests/test_config.py::test_fail_to_open_config_file" ]
[ "tests/test_config.py::test_create_config", "tests/test_config.py::test_get_encoder", "tests/test_config.py::test_fail_to_get_variable", "tests/test_config.py::test_read_config_file", "tests/test_config.py::test_read_invalid_config", "tests/test_config.py::test_update_config_no_unknown_keys", "tests/test_config.py::test_update_config_unknown_keys", "tests/test_config.py::test_ensure_default_postaction_keys_are_strings", "tests/test_dependency.py::test_find_valid_absolute_dependencies", "tests/test_dependency.py::test_find_valid_dependencies_in_path", "tests/test_dependency.py::test_fail_to_find_dependencies", "tests/test_dependency.py::test_get_encoder", "tests/test_dependency.py::test_get_editor", "tests/test_dependency.py::test_get_cdparanoia" ]
[]
BSD 2-Clause "Simplified" License
2,777
937
[ "cdparacord/config.py", "cdparacord/dependency.py" ]
oauthlib__oauthlib-564
371029906aa6ccc9943120e096a7bbdd0ef6945d
2018-07-19 16:47:27
e9c6f01bc6f89e6b90f2c9b61e6a9878d5612147
diff --git a/oauthlib/common.py b/oauthlib/common.py index f25656f..c1180e6 100644 --- a/oauthlib/common.py +++ b/oauthlib/common.py @@ -114,7 +114,7 @@ def decode_params_utf8(params): return decoded -urlencoded = set(always_safe) | set('=&;:%+~,*@!()/?') +urlencoded = set(always_safe) | set('=&;:%+~,*@!()/?\'$') def urldecode(query):
ValueError when query string contains "'" Similar to Issue #404, `oauthlib.common.urldecode` raises a ValueError if the provided query string contains a "'" character. ``` ValueError: Error trying to decode a non urlencoded string. Found invalid characters: set([u"'"]) in the string: 'url=Schr%C3%B6dinger's%20cat'. Please ensure the request/response body is x-www-form-urlencoded. ``` Per [RFC 3986 section 3.4]( https://tools.ietf.org/html/rfc3986#section-3.4), query strings should be allowed to include the characters defined as `pchar` which in turn allows for characters defined as `sub-delims`. This includes the "'" character.
oauthlib/oauthlib
diff --git a/tests/test_common.py b/tests/test_common.py index b0ea20d..fb4bd5b 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -39,6 +39,8 @@ class EncodingTest(TestCase): self.assertItemsEqual(urldecode('foo=bar@spam'), [('foo', 'bar@spam')]) self.assertItemsEqual(urldecode('foo=bar/baz'), [('foo', 'bar/baz')]) self.assertItemsEqual(urldecode('foo=bar?baz'), [('foo', 'bar?baz')]) + self.assertItemsEqual(urldecode('foo=bar\'s'), [('foo', 'bar\'s')]) + self.assertItemsEqual(urldecode('foo=$'), [('foo', '$')]) self.assertRaises(ValueError, urldecode, 'foo bar') self.assertRaises(ValueError, urldecode, '%R') self.assertRaises(ValueError, urldecode, '%RA')
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 blinker==1.4 certifi==2021.5.30 cffi==1.15.1 coverage==6.2 cryptography==40.0.2 importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 -e git+https://github.com/oauthlib/oauthlib.git@371029906aa6ccc9943120e096a7bbdd0ef6945d#egg=oauthlib packaging==21.3 pluggy==1.0.0 py==1.11.0 pycparser==2.21 PyJWT==1.6.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: oauthlib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - blinker==1.4 - cffi==1.15.1 - coverage==6.2 - cryptography==40.0.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pyjwt==1.6.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/oauthlib
[ "tests/test_common.py::EncodingTest::test_urldecode" ]
[]
[ "tests/test_common.py::ParameterTest::test_add_params_to_uri", "tests/test_common.py::ParameterTest::test_extract_invalid", "tests/test_common.py::ParameterTest::test_extract_non_formencoded_string", "tests/test_common.py::ParameterTest::test_extract_params_blank_string", "tests/test_common.py::ParameterTest::test_extract_params_dict", "tests/test_common.py::ParameterTest::test_extract_params_empty_list", "tests/test_common.py::ParameterTest::test_extract_params_formencoded", "tests/test_common.py::ParameterTest::test_extract_params_twotuple", "tests/test_common.py::GeneratorTest::test_generate_client_id", "tests/test_common.py::GeneratorTest::test_generate_nonce", "tests/test_common.py::GeneratorTest::test_generate_timestamp", "tests/test_common.py::GeneratorTest::test_generate_token", "tests/test_common.py::RequestTest::test_dict_body", "tests/test_common.py::RequestTest::test_empty_dict_body", "tests/test_common.py::RequestTest::test_empty_list_body", "tests/test_common.py::RequestTest::test_empty_string_body", "tests/test_common.py::RequestTest::test_getattr_existing_attribute", "tests/test_common.py::RequestTest::test_getattr_raise_attribute_error", "tests/test_common.py::RequestTest::test_getattr_return_default", "tests/test_common.py::RequestTest::test_list_body", "tests/test_common.py::RequestTest::test_non_formencoded_string_body", "tests/test_common.py::RequestTest::test_non_unicode_params", "tests/test_common.py::RequestTest::test_none_body", "tests/test_common.py::RequestTest::test_param_free_sequence_body", "tests/test_common.py::RequestTest::test_password_body", "tests/test_common.py::RequestTest::test_sanitizing_authorization_header", "tests/test_common.py::RequestTest::test_token_body", "tests/test_common.py::CaseInsensitiveDictTest::test_basic", "tests/test_common.py::CaseInsensitiveDictTest::test_update" ]
[]
BSD 3-Clause "New" or "Revised" License
2,793
128
[ "oauthlib/common.py" ]
pennmem__cmlreaders-129
828f57fa7cae9033917802ef646c1ad334790ed3
2018-07-19 17:03:02
177d8508b999957ec1492ecaa7775179ad875454
diff --git a/cmlreaders/cmlreader.py b/cmlreaders/cmlreader.py index 6ae4bfd..7d35bc4 100644 --- a/cmlreaders/cmlreader.py +++ b/cmlreaders/cmlreader.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import List, Optional import numpy as np import pandas as pd @@ -233,3 +233,47 @@ class CMLReader(object): }) return self.load('eeg', **kwargs) + + @classmethod + def load_events(cls, subjects: Optional[List[str]] = None, + experiments: Optional[List[str]] = None, + rootdir: Optional[str] = None) -> pd.DataFrame: + """Load events from multiple sessions. + + Parameters + ---------- + subjects + List of subjects. + experiments + List of experiments to include. + rootdir + Path to root data directory. + + """ + if subjects is None and experiments is None: + raise ValueError( + "Please specify at least one subject or experiment." + ) + + rootdir = get_root_dir(rootdir) + df = get_data_index("all", rootdir=rootdir) + + if subjects is None: + subjects = df["subject"].unique() + + if experiments is None: + experiments = df["experiment"].unique() + + events = [] + + for subject in subjects: + for experiment in experiments: + mask = (df["subject"] == subject) & (df["experiment"] == experiment) + sessions = df[mask]["session"].unique() + + for session in sessions: + reader = CMLReader(subject, experiment, session, + rootdir=rootdir) + events.append(reader.load("events")) + + return pd.concat(events)
Multi-session event reading A common use case when working with events is to load multiple sessions at a time. Right now, this is not as easy as it should be. ```python all_events = [] for session in sessions_completed: sess_events = cml.CMLReader(subject="R1409D", experiment="FR6", session=session, localization=0, montage=0, rootdir=rhino_root).load('task_events') all_events.append(sess_events) all_sessions_df = pd.concat(all_events) ``` The proposed API is to have a special method associated with cml_reader to allow loading multiple sessions of events. The other option is to allow additional kwargs in .load(), but then it becomes extremely difficult to document that function since it would take different parameters depending on the data type being loaded. Instead, we want to mimic the behavior of load_eeg and have it be a separate method associated with the class. Single sessions of events can be loaded using either reader.load() after having specified a session when creating the reader, or by using reader.load_events(sessions=[1]). At a minimum, the following cases should be handled: - Given a single experiment, load all completed sessions - Given a single experiment, load a specific subset of sessions ```python reader = CMLReader(subject="R1409D", experiment="FR6") # Load all sessions all_fr6_events = reader.load_events() # Load specific sessions subset_fr5_events = reader.load_events(sessions=[0, 1]) ``` - Given multiple experiments, load all completed sessions from each experiment - Given a reader with no experiment specified, raise an error if load_events is called ```python reader = CMLReader(subject="R1409D") # Invalid Request all_events = reader.load_events() # Load sessions across experiments all_record_only_events = reader.load_events(experiments=['catFR1', 'FR1']) ``` Depending on if it is important enough of a use case, it could also handle the following cases: - Given multiple experiments and a specific session, load that session number of each experiment, i.e. the first session of FR1 and catFR1 for a particular subject - Given multiple experiments and a specific set of sessions, load those specific sessions for each experiment given, raising an error if any of the requested session/experiment combinations are not available ```python reader = CMLReader(subject="R1409D") # Multi-experiment, single session multi_exp_single_sess = reader.load_events(experiments=['catFR1', 'FR1'], sessions=[0]) # Multi-experiment, multi-session multi_exp_multi_sess = reader.load_events(experiments=['catFR1', 'FR1'], sessions=[0, 1]) ```
pennmem/cmlreaders
diff --git a/cmlreaders/test/test_cmlreader.py b/cmlreaders/test/test_cmlreader.py index f222842..614fb8e 100644 --- a/cmlreaders/test/test_cmlreader.py +++ b/cmlreaders/test/test_cmlreader.py @@ -200,3 +200,25 @@ class TestLoadMontage: with pytest.raises(exc.MissingDataError): reader.load(kind, read_categories=True) + + [email protected] [email protected] +class TestLoadAggregate: + @pytest.mark.parametrize("subjects,experiments,unique_sessions", [ + (None, None, None), + (["R1111M", "R1260D"], ["FR1"], 5), + (["R1111M"], None, 22), + (["R1111M"], ["PS2"], 6), + (None, ["FR2"], 79), + ]) + def test_load_events(self, subjects, experiments, unique_sessions, + rhino_root): + if subjects is experiments is None: + with pytest.raises(ValueError): + CMLReader.load_events(subjects, experiments, rootdir=rhino_root) + return + + events = CMLReader.load_events(subjects, experiments, rootdir=rhino_root) + size = len(events.groupby(["subject", "experiment", "session"]).size()) + assert size == unique_sessions
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@828f57fa7cae9033917802ef646c1ad334790ed3#egg=cmlreaders codecov==2.1.13 coverage==6.2 cycler==0.11.0 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[None-None-None]" ]
[ "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[voxel_coordinates-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_excluded_leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[jacksheet-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[good_leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_coordinates-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[prior_stim_results-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[target_selection_table-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_categories-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[session_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[pairs-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[contacts-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[localization-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[baseline_classifier-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[used_classifier-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[all_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[all_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[task_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[task_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[baseline_classifier.zip]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[used_classifier.zip]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[baseline_classifier]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[used_classifier]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_ps4_events[R1354E-PS4_FR-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_ps2_events", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[True-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[True-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[False-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[False-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_missing[contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_missing[pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects1-experiments1-5]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects2-None-22]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects3-experiments3-6]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[None-experiments4-79]" ]
[ "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-catFR1-0-0-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-catFR1-None-0-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-PAL1-None-2-2]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-PAL3-2-2-2]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-TH1-0-0-0]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-TH1-None-0-0]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[LTP093-ltpFR2-0-None-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[voxel_coordinates-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_excluded_leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[jacksheet-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[good_leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_coordinates-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[prior_stim_results-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[target_selection_table-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_categories-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[session_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[pairs-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[contacts-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[localization-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[baseline_classifier-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[used_classifier-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[voxel_coordinates.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[classifier_excluded_leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[jacksheet.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[good_leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[electrode_coordinates.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[prior_stim_results.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[target_selection_table.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[pairs.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[contacts.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[localization.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[all_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[math_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[task_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[voxel_coordinates]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[classifier_excluded_leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[jacksheet]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[good_leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[electrode_coordinates]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[prior_stim_results]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[target_selection_table]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[pairs]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[contacts]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[localization]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[all_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[math_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[task_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_unimplemented", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[True-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[True-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[False-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[False-pairs]" ]
[]
null
2,794
429
[ "cmlreaders/cmlreader.py" ]
pre-commit__pre-commit-803
f2da2c435c1123c4edc4ca9701c245cc25b0a50d
2018-07-20 01:49:48
cf691e85c89dbe16dce7e0a729649b2e19d4d9ad
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py index b1549d4..dbf5641 100644 --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -256,7 +256,7 @@ def run(runner, store, args, environ=os.environ): for _, hook in repo.hooks: if ( (not args.hook or hook['id'] == args.hook) and - not hook['stages'] or args.hook_stage in hook['stages'] + (not hook['stages'] or args.hook_stage in hook['stages']) ): repo_hooks.append((repo, hook))
`stages: [commit]` hooks will run with `pre-commit run otherhookid` minor logic bug, good new-contributor ticket Easy to reproduce on pre-commit itself: ```diff diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a146bd2..7bb382d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,6 +3,7 @@ repos: rev: v1.2.3 hooks: - id: trailing-whitespace + stages: [commit] - id: end-of-file-fixer - id: autopep8-wrapper - id: check-docstring-first ``` ```console $ pre-commit run end-of-file-fixer --all-files Trim Trailing Whitespace.................................................Passed Fix End of Files.........................................................Passed ``` (it should have only run `end-of-file-fixer` but also run `trailing-whitespace` due to a logic error).
pre-commit/pre-commit
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py index 70a6b6e..e6258d3 100644 --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -762,3 +762,34 @@ def test_include_exclude_does_search_instead_of_match(some_filenames): def test_include_exclude_exclude_removes_files(some_filenames): ret = _filter_by_include_exclude(some_filenames, '', r'\.py$') assert ret == ['.pre-commit-hooks.yaml'] + + +def test_args_hook_only(cap_out, store, repo_with_passing_hook): + config = OrderedDict(( + ('repo', 'local'), + ( + 'hooks', ( + OrderedDict(( + ('id', 'flake8'), + ('name', 'flake8'), + ('entry', "'{}' -m flake8".format(sys.executable)), + ('language', 'system'), + ('stages', ['commit']), + )), OrderedDict(( + ('id', 'do_not_commit'), + ('name', 'Block if "DO NOT COMMIT" is found'), + ('entry', 'DO NOT COMMIT'), + ('language', 'pygrep'), + )), + ), + ), + )) + add_config_to_repo(repo_with_passing_hook, config) + stage_a_file() + ret, printed = _do_run( + cap_out, + store, + repo_with_passing_hook, + run_opts(hook='do_not_commit'), + ) + assert b'flake8' not in printed
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "pytest", "pytest-env" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 cfgv==3.3.1 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 identify==2.4.4 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 mccabe==0.7.0 mock==5.2.0 nodeenv==1.6.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/pre-commit/pre-commit.git@f2da2c435c1123c4edc4ca9701c245cc25b0a50d#egg=pre_commit py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing==3.1.4 pytest==7.0.1 pytest-env==0.6.2 PyYAML==6.0.1 six==1.17.0 toml==0.10.2 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.17.1 zipp==3.6.0
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aspy-yaml==1.3.0 - attrs==22.2.0 - cached-property==1.5.2 - cfgv==3.3.1 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - identify==2.4.4 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mccabe==0.7.0 - mock==5.2.0 - nodeenv==1.6.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-env==0.6.2 - pyyaml==6.0.1 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit
[ "tests/commands/run_test.py::test_args_hook_only" ]
[]
[ "tests/commands/run_test.py::test_run_all_hooks_failing", "tests/commands/run_test.py::test_arbitrary_bytes_hook", "tests/commands/run_test.py::test_hook_that_modifies_but_returns_zero", "tests/commands/run_test.py::test_types_hook_repository", "tests/commands/run_test.py::test_exclude_types_hook_repository", "tests/commands/run_test.py::test_global_exclude", "tests/commands/run_test.py::test_show_diff_on_failure", "tests/commands/run_test.py::test_run[options0-outputs0-0-True]", "tests/commands/run_test.py::test_run[options1-outputs1-0-True]", "tests/commands/run_test.py::test_run[options2-outputs2-0-True]", "tests/commands/run_test.py::test_run[options3-outputs3-1-True]", "tests/commands/run_test.py::test_run[options4-outputs4-0-True]", "tests/commands/run_test.py::test_run[options5-outputs5-0-True]", "tests/commands/run_test.py::test_run[options6-outputs6-0-False]", "tests/commands/run_test.py::test_run_output_logfile", "tests/commands/run_test.py::test_always_run", "tests/commands/run_test.py::test_always_run_alt_config", "tests/commands/run_test.py::test_hook_verbose_enabled", "tests/commands/run_test.py::test_origin_source_error_msg_error[master-]", "tests/commands/run_test.py::test_origin_source_error_msg_error[-master]", "tests/commands/run_test.py::test_origin_source_both_ok", "tests/commands/run_test.py::test_has_unmerged_paths", "tests/commands/run_test.py::test_merge_conflict", "tests/commands/run_test.py::test_merge_conflict_modified", "tests/commands/run_test.py::test_merge_conflict_resolved", "tests/commands/run_test.py::test_compute_cols[hooks0-True-80]", "tests/commands/run_test.py::test_compute_cols[hooks1-False-81]", "tests/commands/run_test.py::test_compute_cols[hooks2-True-85]", "tests/commands/run_test.py::test_compute_cols[hooks3-False-82]", "tests/commands/run_test.py::test_get_skips[environ0-expected_output0]", "tests/commands/run_test.py::test_get_skips[environ1-expected_output1]", "tests/commands/run_test.py::test_get_skips[environ2-expected_output2]", "tests/commands/run_test.py::test_get_skips[environ3-expected_output3]", "tests/commands/run_test.py::test_get_skips[environ4-expected_output4]", "tests/commands/run_test.py::test_get_skips[environ5-expected_output5]", "tests/commands/run_test.py::test_get_skips[environ6-expected_output6]", "tests/commands/run_test.py::test_skip_hook", "tests/commands/run_test.py::test_hook_id_not_in_non_verbose_output", "tests/commands/run_test.py::test_hook_id_in_verbose_output", "tests/commands/run_test.py::test_multiple_hooks_same_id", "tests/commands/run_test.py::test_non_ascii_hook_id", "tests/commands/run_test.py::test_stdout_write_bug_py26", "tests/commands/run_test.py::test_lots_of_files", "tests/commands/run_test.py::test_stages", "tests/commands/run_test.py::test_commit_msg_hook", "tests/commands/run_test.py::test_local_hook_passes", "tests/commands/run_test.py::test_local_hook_fails", "tests/commands/run_test.py::test_pcre_deprecation_warning", "tests/commands/run_test.py::test_meta_hook_passes", "tests/commands/run_test.py::test_error_with_unstaged_config", "tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts0]", "tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts1]", "tests/commands/run_test.py::test_files_running_subdir", "tests/commands/run_test.py::test_pass_filenames[True-hook_args0-foo.py]", "tests/commands/run_test.py::test_pass_filenames[False-hook_args1-]", "tests/commands/run_test.py::test_pass_filenames[True-hook_args2-some", "tests/commands/run_test.py::test_pass_filenames[False-hook_args3-some", "tests/commands/run_test.py::test_fail_fast", "tests/commands/run_test.py::test_include_exclude_base_case", "tests/commands/run_test.py::test_matches_broken_symlink", "tests/commands/run_test.py::test_include_exclude_total_match", "tests/commands/run_test.py::test_include_exclude_does_search_instead_of_match", "tests/commands/run_test.py::test_include_exclude_exclude_removes_files" ]
[]
MIT License
2,796
167
[ "pre_commit/commands/run.py" ]
PlasmaPy__PlasmaPy-517
0a5eb2eb13d06b2cc9b758a82bcf888197c105af
2018-07-20 03:28:18
24113f1659d809930288374f6b1f95dc573aff47
diff --git a/plasmapy/atomic/particle_class.py b/plasmapy/atomic/particle_class.py index b7e7ed5c..1a73b294 100644 --- a/plasmapy/atomic/particle_class.py +++ b/plasmapy/atomic/particle_class.py @@ -113,9 +113,10 @@ class Particle: Parameters ---------- - argument : `str` or `int` - A string representing a particle, element, isotope, or ion; or - an integer representing the atomic number of an element. + argument : `str`, `int`, or `~plasmapy.atomic.Particle` + A string representing a particle, element, isotope, or ion; an + integer representing the atomic number of an element; or a + `Particle` instance. mass_numb : `int`, optional The mass number of an isotope or nuclide. @@ -238,6 +239,25 @@ class Particle: >>> ~positron Particle("e-") + A `~plasmapy.atomic.Particle` instance may be used as the first + argument to `~plasmapy.atomic.Particle`. + + >>> iron = Particle('Fe') + >>> iron == Particle(iron) + True + >>> Particle(iron, mass_numb=56, Z=6) + Particle("Fe-56 6+") + + If the previously constructed `~plasmapy.atomic.Particle` instance + represents an element, then the `Z` and `mass_numb` arguments may be + used to specify an ion or isotope. + + >>> iron = Particle('Fe') + >>> Particle(iron, Z=1) + Particle("Fe 1+") + >>> Particle(iron, mass_numb=56) + Particle("Fe-56") + The `~plasmapy.atomic.particle_class.Particle.categories` attribute and `~plasmapy.atomic.particle_class.Particle.is_category` method may be used to find and test particle membership in categories. @@ -257,14 +277,22 @@ class Particle: def __init__(self, argument: Union[str, int], mass_numb: int = None, Z: int = None): """ - Initialize a `~plasmapy.atomic.Particle` object and set private + Instantiate a `~plasmapy.atomic.Particle` object and set private attributes. """ - if not isinstance(argument, (int, str)): + if not isinstance(argument, (int, np.integer, str, Particle)): raise TypeError( "The first positional argument when creating a Particle " - "object must be either an integer or string.") + "object must be either an integer, string, or another" + "Particle object.") + + # If argument is a Particle instance, then we will construct a + # new Particle instance for the same Particle (essentially a + # copy). + + if isinstance(argument, Particle): + argument = argument.particle if mass_numb is not None and not isinstance(mass_numb, int): raise TypeError("mass_numb is not an integer")
Have Particle class return corresponding Particle instance for Particle arguments I've run into a bunch of situations where I have some objects that are either `Particle` class instances or `str`/`int` representations of particles, and I want to make sure that they are all `Particle` class instances. I have usually written code like this: ```Python >>> orig_particles = ['H', Particle('He')] >>> particles = [ particle if isinstance(particle, Particle) else Particle(particle) for particle in orig_particles ] ``` This code is rather obfuscating since it checks on whether or not `particle` is a `Particle` class instance. It would be simpler to have `Particle` return the corresponding `Particle` instance which would allow code like this: ```Python >>> particles = [Particle(particle) for particle in particles] ``` @StanczakDominik suggested that this be a copy of the `Particle` instance rather than returning self, which is like how `numpy.array` behaves. A good test would be to check that `Particle(something) == Particle(Particle(something))`, e.g., something like: ```Python from plasmapy.atomic import Particle def test_particle_of_particle(particle_representation): particle = Particle(particle_representation) particle_of_particle = Particle(particle) assert particle == particle_of_particle assert particle is not particle_of_particle # to make sure it is a copy rather than self ``` Thanks! -Nick
PlasmaPy/PlasmaPy
diff --git a/plasmapy/atomic/tests/test_particle_class.py b/plasmapy/atomic/tests/test_particle_class.py index 9d3308e0..1cb727c4 100644 --- a/plasmapy/atomic/tests/test_particle_class.py +++ b/plasmapy/atomic/tests/test_particle_class.py @@ -377,6 +377,17 @@ 'is_category("boson", exclude="boson")': AtomicError, 'is_category(any_of="boson", exclude="boson")': AtomicError, }), + + (Particle('C'), {}, + {'particle': 'C', + }), + + (Particle('C'), {'Z': 3, 'mass_numb': 14}, + {'particle': 'C-14 3+', + 'element': 'C', + 'isotope': 'C-14', + 'ionic_symbol': 'C-14 3+', + }), ] @@ -478,6 +489,8 @@ def test_Particle_equivalent_cases(equivalent_particles): ('Fe', {}, '.spin', MissingAtomicDataError), ('nu_e', {}, '.mass', MissingAtomicDataError), ('Og', {}, '.standard_atomic_weight', MissingAtomicDataError), + (Particle('C-14'), {'mass_numb': 13}, "", InvalidParticleError), + (Particle('Au 1+'), {'Z': 2}, "", InvalidParticleError), ([], {}, "", TypeError), ] @@ -707,3 +720,25 @@ def test_antiparticle_attribute_and_operator(self, particle, opposite): (f"{repr(particle)}.antiparticle returned " f"{particle.antiparticle}, whereas ~{repr(particle)} " f"returned {~particle}.") + + [email protected]('arg', ['e-', 'D+', 'Fe 25+', 'H-', 'mu+']) +def test_particleing_a_particle(arg): + """ + Test that Particle(arg) is equal to Particle(Particle(arg)), but is + not the same object in memory. + """ + particle = Particle(arg) + + assert particle == Particle(particle), ( + f"Particle({repr(arg)}) does not equal " + f"Particle(Particle({repr(arg)}).") + + assert particle == Particle(Particle(Particle(particle))), ( + f"Particle({repr(arg)}) does not equal " + f"Particle(Particle(Particle({repr(arg)})).") + + assert particle is not Particle(particle), ( + f"Particle({repr(arg)}) is the same object in memory as " + f"Particle(Particle({repr(arg)})), when it is intended to " + f"create a new object in memory (e.g., a copy).")
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 astropy", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asteval==1.0.6 astropy @ file:///croot/astropy_1697468907928/work colorama==0.4.6 contourpy==1.3.0 cycler==0.12.1 Cython==3.0.12 dill==0.3.9 exceptiongroup==1.2.2 fonttools==4.56.0 h5py==3.13.0 importlib_resources==6.5.2 iniconfig==2.1.0 kiwisolver==1.4.7 lmfit==1.3.3 matplotlib==3.9.4 mpmath==1.3.0 numpy @ file:///croot/numpy_and_numpy_base_1708638617955/work/dist/numpy-1.26.4-cp39-cp39-linux_x86_64.whl#sha256=b69ac3eb7538c5a224df429dc49031914fb977825ee007f2c77a13f7aa6cd769 packaging @ file:///croot/packaging_1734472117206/work pillow==11.1.0 -e git+https://github.com/PlasmaPy/PlasmaPy.git@0a5eb2eb13d06b2cc9b758a82bcf888197c105af#egg=plasmapy pluggy==1.5.0 pyerfa @ file:///croot/pyerfa_1738082786199/work pyparsing==3.2.3 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML @ file:///croot/pyyaml_1728657952215/work roman==5.0 scipy==1.13.1 six==1.17.0 tomli==2.2.1 uncertainties==3.2.2 zipp==3.21.0
name: PlasmaPy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - astropy=5.3.4=py39ha9d4c09_0 - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - numpy=1.26.4=py39heeff2f4_0 - numpy-base=1.26.4=py39h8a23956_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pyerfa=2.0.1.5=py39h5eee18b_0 - python=3.9.21=he870216_1 - pyyaml=6.0.2=py39h5eee18b_0 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - zlib=1.2.13=h5eee18b_1 - pip: - asteval==1.0.6 - colorama==0.4.6 - contourpy==1.3.0 - cycler==0.12.1 - cython==3.0.12 - dill==0.3.9 - exceptiongroup==1.2.2 - fonttools==4.56.0 - h5py==3.13.0 - importlib-resources==6.5.2 - iniconfig==2.1.0 - kiwisolver==1.4.7 - lmfit==1.3.3 - matplotlib==3.9.4 - mpmath==1.3.0 - pillow==11.1.0 - pluggy==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - roman==5.0 - scipy==1.13.1 - six==1.17.0 - tomli==2.2.1 - uncertainties==3.2.2 - zipp==3.21.0 prefix: /opt/conda/envs/PlasmaPy
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Particle(\"C\")-kwargs16-expected_dict16]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Particle(\"C\")-kwargs17-expected_dict17]", "plasmapy/atomic/tests/test_particle_class.py::test_particleing_a_particle[e-]", "plasmapy/atomic/tests/test_particle_class.py::test_particleing_a_particle[D+]", "plasmapy/atomic/tests/test_particle_class.py::test_particleing_a_particle[Fe", "plasmapy/atomic/tests/test_particle_class.py::test_particleing_a_particle[H-]", "plasmapy/atomic/tests/test_particle_class.py::test_particleing_a_particle[mu+]" ]
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Li-kwargs12-expected_dict12]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[a-kwargs0--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[d+-kwargs1--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[H-kwargs2--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-818-kwargs3--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-12-kwargs4--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-kwargs5--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Au-kwargs6--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs7--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs8-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[alpha-kwargs9-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Fe-56-kwargs10-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[e--kwargs11-.standard_atomic_weight-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[tau--kwargs12-.element_name-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[tau+-kwargs13-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[neutron-kwargs14-.atomic_number-InvalidElementError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[H-kwargs15-.mass_number-InvalidIsotopeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[neutron-kwargs16-.mass_number-InvalidIsotopeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[He-kwargs17-.charge-ChargeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[He-kwargs18-.integer_charge-ChargeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Fe-kwargs19-.spin-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[nu_e-kwargs20-.mass-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Og-kwargs21-.standard_atomic_weight-MissingAtomicDataError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Particle(\"C-14\")-kwargs22--InvalidParticleError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[Particle(\"Au", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_errors[arg24-kwargs24--TypeError]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[H-----kwargs0--AtomicWarning]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[alpha-kwargs1--AtomicWarning]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_warnings[alpha-kwargs2--AtomicWarning]" ]
[ "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[neutron-kwargs0-expected_dict0]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[p+-kwargs1-expected_dict1]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[p--kwargs2-expected_dict2]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[e--kwargs3-expected_dict3]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[e+-kwargs4-expected_dict4]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H-kwargs5-expected_dict5]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[H-1", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[D+-kwargs8-expected_dict8]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[tritium-kwargs9-expected_dict9]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Fe-kwargs10-expected_dict10]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[alpha-kwargs11-expected_dict11]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[Cn-276-kwargs13-expected_dict13]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[muon-kwargs14-expected_dict14]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_class[nu_tau-kwargs15-expected_dict15]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles0]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles1]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles2]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles3]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles4]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles5]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles6]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles7]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles8]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles9]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_equivalent_cases[equivalent_particles10]", "plasmapy/atomic/tests/test_particle_class.py::test_Particle_cmp", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[n-neutron]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[p+-proton]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[H-1-p+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[H-1", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[D-D+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[T-T+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[He-4-alpha]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_class_mass_nuclide_mass[Fe-56-Fe-56", "plasmapy/atomic/tests/test_particle_class.py::test_particle_half_life_string", "plasmapy/atomic/tests/test_particle_class.py::test_particle_is_electron[Particle(\"e-\")-True]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_is_electron[Particle(\"p+\")-False]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_bool_error", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[p+-p-]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[n-antineutron]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[e--e+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[mu--mu+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[tau--tau+]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_e-anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_mu-anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::test_particle_inversion[nu_tau-anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[p+-p-]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[n-antineutron]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[e--e+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[mu--mu+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[tau--tau+]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_e-anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_mu-anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::test_antiparticle_inversion[nu_tau-anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::test_unary_operator_for_elements", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_inverted_inversion[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_opposite_charge[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_equal_mass[nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[mu+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[mu-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[n]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[tau-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[p-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[antineutron]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[e-]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[p+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[tau+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[e+]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_tau]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_e]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[anti_nu_mu]", "plasmapy/atomic/tests/test_particle_class.py::Test_antiparticle_properties_inversion::test_antiparticle_attribute_and_operator[nu_mu]" ]
[]
BSD 3-Clause "New" or "Revised" License
2,798
754
[ "plasmapy/atomic/particle_class.py" ]
jonathanj__eliottree-68
983999c822a83258d4f3bc3086925649bcf672f2
2018-07-21 19:01:29
86b5043c1c308624ae29de82606e96d5a65f76f4
diff --git a/eliottree/_cli.py b/eliottree/_cli.py index 0325c73..f10389e 100644 --- a/eliottree/_cli.py +++ b/eliottree/_cli.py @@ -77,12 +77,14 @@ def display_tasks(tasks, color, ignored_fields, field_limit, human_readable): the task trees to stdout. """ write = text_writer(sys.stdout).write + write_err = text_writer(sys.stderr).write if color == 'auto': colorize = sys.stdout.isatty() else: colorize = color == 'always' render_tasks( write=write, + write_err=write_err, tasks=tasks, ignored_fields=set(ignored_fields) or None, field_limit=field_limit, diff --git a/eliottree/_render.py b/eliottree/_render.py index 59ee982..c8fc3b9 100644 --- a/eliottree/_render.py +++ b/eliottree/_render.py @@ -1,13 +1,17 @@ +import sys +import traceback from functools import partial from eliot._action import WrittenAction from eliot._message import WrittenMessage from eliot._parse import Task +from six import text_type from termcolor import colored -from toolz import compose, identity +from toolz import compose, excepts, identity from tree_format import format_tree from eliottree import format +from eliottree._util import eliot_ns, format_namespace, is_namespace RIGHT_DOUBLE_ARROW = u'\u21d2' @@ -33,6 +37,7 @@ class COLORS(object): success = Color('green') failure = Color('red') prop = Color('blue') + error = Color('red', ['bold']) def __init__(self, colored): self.colored = colored @@ -52,7 +57,7 @@ def _default_value_formatter(human_readable, field_limit, encoding='utf-8'): fields = {} if human_readable: fields = { - u'timestamp': format.timestamp(), + eliot_ns(u'timestamp'): format.timestamp(), } return compose( # We want tree-format to handle newlines. @@ -126,6 +131,8 @@ def format_node(format_value, colors, node): value = u'' else: value = format_value(value, key) + if is_namespace(key): + key = format_namespace(key) return u'{}: {}'.format( colors.prop(format.escape_control_characters(key)), value) @@ -138,13 +145,17 @@ def message_fields(message, ignored_fields): """ def _items(): try: - yield u'timestamp', message.timestamp + yield eliot_ns('timestamp'), message.timestamp except KeyError: pass for key, value in message.contents.items(): if key not in ignored_fields: yield key, value - return sorted(_items()) if message else [] + + def _sortkey(x): + k = x[0] + return format_namespace(k) if is_namespace(k) else k + return sorted(_items(), key=_sortkey) if message else [] def get_children(ignored_fields, node): @@ -176,8 +187,20 @@ def get_children(ignored_fields, node): return [] +def track_exceptions(f, caught, default=None): + """ + Decorate ``f`` with a function that traps exceptions and appends them to + ``caught``, returning ``default`` in their place. + """ + def _catch(_): + caught.append(sys.exc_info()) + return default + return excepts(Exception, f, _catch) + + def render_tasks(write, tasks, field_limit=0, ignored_fields=None, - human_readable=False, colorize=False): + human_readable=False, colorize=False, write_err=None, + format_node=format_node, format_value=None): """ Render Eliot tasks as an ASCII tree. @@ -193,18 +216,44 @@ def render_tasks(write, tasks, field_limit=0, ignored_fields=None, most Eliot metadata. :param bool human_readable: Render field values as human-readable? :param bool colorize: Colorized the output? + :type write_err: Callable[[`text_type`], None] + :param write_err: Callable used to write errors. + :param format_node: See `format_node`. + :type format_value: Callable[[Any], `text_type`] + :param format_value: Callable to format a value. """ if ignored_fields is None: ignored_fields = DEFAULT_IGNORED_KEYS - _format_node = partial( - format_node, - _default_value_formatter(human_readable=human_readable, - field_limit=field_limit), - COLORS(colored if colorize else _no_color)) + colors = COLORS(colored if colorize else _no_color) + caught_exceptions = [] + if format_value is None: + format_value = _default_value_formatter( + human_readable=human_readable, + field_limit=field_limit) + _format_value = track_exceptions( + format_value, + caught_exceptions, + u'<value formatting exception>') + _format_node = track_exceptions( + partial(format_node, _format_value, colors), + caught_exceptions, + u'<node formatting exception>') _get_children = partial(get_children, ignored_fields) for task in tasks: write(format_tree(task, _format_node, _get_children)) write(u'\n') + if write_err and caught_exceptions: + write_err( + colors.error( + u'Exceptions ({}) occurred during processing:\n'.format( + len(caught_exceptions)))) + for exc in caught_exceptions: + for line in traceback.format_exception(*exc): + if not isinstance(line, text_type): + line = line.decode('utf-8') + write_err(line) + write_err(u'\n') + __all__ = ['render_tasks'] diff --git a/eliottree/_util.py b/eliottree/_util.py new file mode 100644 index 0000000..3ef7008 --- /dev/null +++ b/eliottree/_util.py @@ -0,0 +1,36 @@ +from collections import namedtuple + + +namespace = namedtuple('namespace', ['prefix', 'name']) + + +def namespaced(prefix): + """ + Create a function that creates new names in the ``prefix`` namespace. + + :rtype: Callable[[unicode], `namespace`] + """ + return lambda name: namespace(prefix, name) + + +def format_namespace(ns): + """ + Format a `namespace`. + + :rtype: unicode + """ + if not is_namespace(ns): + raise TypeError('Expected namespace', ns) + return u'{}/{}'.format(ns.prefix, ns.name) + + +def is_namespace(x): + """ + Is this a `namespace` instance? + + :rtype: bool + """ + return isinstance(x, namespace) + + +eliot_ns = namespaced(u'eliot') diff --git a/eliottree/render.py b/eliottree/render.py index 58d2992..e12f3aa 100644 --- a/eliottree/render.py +++ b/eliottree/render.py @@ -7,6 +7,7 @@ from tree_format import format_tree from eliottree._render import ( COLORS, DEFAULT_IGNORED_KEYS, _default_value_formatter, _no_color) +from eliottree._util import is_namespace, eliot_ns from eliottree.format import escape_control_characters @@ -81,7 +82,10 @@ def get_name_factory(colors): if isinstance(task, text_type): return escape_control_characters(task) elif isinstance(task, tuple): - name = escape_control_characters(task[0]) + key = task[0] + if is_namespace(key): + key = key.name + name = escape_control_characters(key) if isinstance(task[1], dict): return name elif isinstance(task[1], text_type): @@ -129,6 +133,8 @@ def get_children_factory(ignored_task_keys, format_value): def items_children(items): for key, value in sorted(items): if key not in ignored_task_keys: + if key == u'timestamp': + key = eliot_ns(key) if isinstance(value, dict): yield key, value else: @@ -150,7 +156,10 @@ def get_children_factory(ignored_task_keys, format_value): return else: for child in items_children(task.task.items()): - yield child + if child[0] == u'timestamp': + yield eliot_ns(child[0]), child[1] + else: + yield child for child in task.children(): yield child return get_children diff --git a/setup.py b/setup.py index e47a7ef..85950e5 100644 --- a/setup.py +++ b/setup.py @@ -30,7 +30,7 @@ setup( "six>=1.9.0", "jmespath>=0.7.1", "iso8601>=0.1.10", - "tree-format>=0.1.2", + "tree-format>=0.1.1", "termcolor>=1.1.0", "toolz>=0.8.2", "eliot>=0.12.0",
Handle exceptions during formatting more gracefully Sometimes timestamps are missing / None for example: ``` File "/home/mithrandi/code/eliottree/eliottree/format.py", line 47, in _format_timestamp_value result = datetime.utcfromtimestamp(float(value)).isoformat(' ') TypeError: float() argument must be a string or a number ``` `--raw` will work around this but then you get no formatting for _anything_.
jonathanj/eliottree
diff --git a/eliottree/test/test_cli.py b/eliottree/test/test_cli.py index 0d7d9bd..1612f1b 100644 --- a/eliottree/test/test_cli.py +++ b/eliottree/test/test_cli.py @@ -13,9 +13,9 @@ from eliottree.test.tasks import message_task, missing_uuid_task rendered_message_task = ( u'cdeb220d-7605-4d5f-8341-1a170222e308\n' u'\u2514\u2500\u2500 twisted:log/1\n' + u' \u251c\u2500\u2500 eliot/timestamp: 2015-03-03 04:25:00\n' u' \u251c\u2500\u2500 error: False\n' - u' \u251c\u2500\u2500 message: Main loop terminated.\n' - u' \u2514\u2500\u2500 timestamp: 2015-03-03 04:25:00\n\n' + u' \u2514\u2500\u2500 message: Main loop terminated.\n\n' ).encode('utf-8') diff --git a/eliottree/test/test_render.py b/eliottree/test/test_render.py index 3946f7b..0d612d7 100644 --- a/eliottree/test/test_render.py +++ b/eliottree/test/test_render.py @@ -4,13 +4,15 @@ from termcolor import colored from testtools import ExpectedException, TestCase from testtools.matchers import AfterPreprocessing as After from testtools.matchers import ( - Contains, EndsWith, Equals, HasLength, IsDeprecated, StartsWith) + Contains, EndsWith, Equals, HasLength, IsDeprecated, MatchesAll, + MatchesListwise, StartsWith) from eliottree import ( Tree, render_task_nodes, render_tasks, tasks_from_iterable) from eliottree._render import ( COLORS, RIGHT_DOUBLE_ARROW, _default_value_formatter, _no_color, format_node, get_children, message_fields, message_name) +from eliottree._util import eliot_ns from eliottree.render import get_name_factory from eliottree.test.matchers import ExactlyEquals from eliottree.test.tasks import ( @@ -72,7 +74,7 @@ class DefaultValueFormatterTests(TestCase): def test_timestamp_field(self): """ - Format ``timestamp`` fields as human-readable if the feature was + Format Eliot ``timestamp`` fields as human-readable if the feature was requested. """ format_value = _default_value_formatter( @@ -80,12 +82,26 @@ class DefaultValueFormatterTests(TestCase): # datetime(2015, 6, 6, 22, 57, 12) now = 1433631432 self.assertThat( - format_value(now, u'timestamp'), + format_value(now, eliot_ns(u'timestamp')), ExactlyEquals(u'2015-06-06 22:57:12')) self.assertThat( - format_value(str(now), u'timestamp'), + format_value(str(now), eliot_ns(u'timestamp')), ExactlyEquals(u'2015-06-06 22:57:12')) + def test_not_eliot_timestamp_field(self): + """ + Do not format user fields named ``timestamp``. + """ + format_value = _default_value_formatter( + human_readable=True, field_limit=0) + now = 1433631432 + self.assertThat( + format_value(now, u'timestamp'), + ExactlyEquals(text_type(now))) + self.assertThat( + format_value(text_type(now), u'timestamp'), + ExactlyEquals(text_type(now))) + def test_timestamp_field_not_human(self): """ Do not format ``timestamp`` fields as human-readable if the feature was @@ -668,8 +684,9 @@ class MessageFieldsTests(TestCase): message = WrittenMessage.from_dict({u'a': 1, u'timestamp': 12345678}) self.assertThat( message_fields(message, set()), - Equals([(u'a', 1), - (u'timestamp', 12345678)])) + Equals([ + (u'a', 1), + (eliot_ns(u'timestamp'), 12345678)])) def test_ignored_fields(self): """ @@ -711,7 +728,7 @@ class GetChildrenTests(TestCase): Equals([ (u'action_status', start_message.contents.action_status), (u'action_type', start_message.contents.action_type), - (u'timestamp', start_message.timestamp)])) + (eliot_ns(u'timestamp'), start_message.timestamp)])) def test_written_action_start(self): """ @@ -726,7 +743,7 @@ class GetChildrenTests(TestCase): Equals([ (u'action_status', start_message.contents.action_status), (u'action_type', start_message.contents.action_type), - (u'timestamp', start_message.timestamp)])) + (eliot_ns(u'timestamp'), start_message.timestamp)])) def test_written_action_children(self): """ @@ -822,10 +839,47 @@ class RenderTasksTests(TestCase): """ def render_tasks(self, iterable, **kw): fd = StringIO() + err = StringIO(u'') tasks = tasks_from_iterable(iterable) - render_tasks(write=fd.write, tasks=tasks, **kw) + render_tasks(write=fd.write, write_err=err.write, tasks=tasks, **kw) + if err.tell(): + return fd.getvalue(), err.getvalue() return fd.getvalue() + def test_format_node_failures(self): + """ + Catch exceptions when formatting nodes and display a message without + interrupting the processing of tasks. List all caught exceptions to + stderr. + """ + def bad_format_node(*a, **kw): + raise ValueError('Nope') + self.assertThat( + self.render_tasks([message_task], + format_node=bad_format_node), + MatchesListwise([ + Contains(u'<node formatting exception>'), + MatchesAll( + Contains(u'Traceback (most recent call last):'), + Contains(u'ValueError: Nope'))])) + + def test_format_value_failures(self): + """ + Catch exceptions when formatting node values and display a message + without interrupting the processing of tasks. List all caught + exceptions to stderr. + """ + def bad_format_value(*a, **kw): + raise ValueError('Nope') + self.assertThat( + self.render_tasks([message_task], + format_value=bad_format_value), + MatchesListwise([ + Contains(u'message: <value formatting exception>'), + MatchesAll( + Contains(u'Traceback (most recent call last):'), + Contains(u'ValueError: Nope'))])) + def test_tasks(self): """ Render two tasks of sequential levels, by default most standard Eliot @@ -836,9 +890,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 timestamp: 1425356800\n' + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' u' \u2514\u2500\u2500 app:action/2 \u21d2 succeeded\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u2514\u2500\u2500 eliot/timestamp: 1425356800\n\n')) def test_tasks_human_readable(self): """ @@ -851,9 +905,11 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 timestamp: 2015-03-03 04:26:40\n' + u' \u251c\u2500\u2500 eliot/timestamp: ' + u'2015-03-03 04:26:40\n' u' \u2514\u2500\u2500 app:action/2 \u21d2 succeeded\n' - u' \u2514\u2500\u2500 timestamp: 2015-03-03 04:26:40\n' + u' \u2514\u2500\u2500 eliot/timestamp: ' + u'2015-03-03 04:26:40\n' u'\n')) def test_multiline_field(self): @@ -871,9 +927,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 message: this is a\u23ce\n' - u' \u2502 many line message\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' + u' \u2514\u2500\u2500 message: this is a\u23ce\n' + u' many line message\n\n')) def test_multiline_field_limit(self): """ @@ -886,8 +942,8 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 message: this is a\u2026\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' + u' \u2514\u2500\u2500 message: this is a\u2026\n\n')) def test_field_limit(self): """ @@ -899,9 +955,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'cdeb220d-7605-4d5f-8341-1a170222e308\n' u'\u2514\u2500\u2500 twisted:log/1\n' + u' \u251c\u2500\u2500 eliot/timestamp: 14253\u2026\n' u' \u251c\u2500\u2500 error: False\n' - u' \u251c\u2500\u2500 message: Main \u2026\n' - u' \u2514\u2500\u2500 timestamp: 14253\u2026\n\n')) + u' \u2514\u2500\u2500 message: Main \u2026\n\n')) def test_ignored_keys(self): """ @@ -914,7 +970,7 @@ class RenderTasksTests(TestCase): u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' u' \u251c\u2500\u2500 action_status: started\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u2514\u2500\u2500 eliot/timestamp: 1425356800\n\n')) def test_task_data(self): """ @@ -925,9 +981,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'cdeb220d-7605-4d5f-8341-1a170222e308\n' u'\u2514\u2500\u2500 twisted:log/1\n' + u' \u251c\u2500\u2500 eliot/timestamp: 1425356700\n' u' \u251c\u2500\u2500 error: False\n' - u' \u251c\u2500\u2500 message: Main loop terminated.\n' - u' \u2514\u2500\u2500 timestamp: 1425356700\n\n')) + u' \u2514\u2500\u2500 message: Main loop terminated.\n\n')) def test_dict_data(self): """ @@ -938,9 +994,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 some_data: \n' - u' \u2502 \u2514\u2500\u2500 a: 42\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' + u' \u2514\u2500\u2500 some_data: \n' + u' \u2514\u2500\u2500 a: 42\n\n')) def test_list_data(self): """ @@ -951,10 +1007,10 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 some_data: \n' - u' \u2502 \u251c\u2500\u2500 0: a\n' - u' \u2502 \u2514\u2500\u2500 1: b\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\n\n')) + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' + u' \u2514\u2500\u2500 some_data: \n' + u' \u251c\u2500\u2500 0: a\n' + u' \u2514\u2500\u2500 1: b\n\n')) def test_nested(self): """ @@ -965,9 +1021,9 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' u'\u2514\u2500\u2500 app:action/1 \u21d2 started\n' - u' \u251c\u2500\u2500 timestamp: 1425356800\n' + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\n' u' \u2514\u2500\u2500 app:action:nest/1/1 \u21d2 started\n' - u' \u2514\u2500\u2500 timestamp: 1425356900\n\n')) + u' \u2514\u2500\u2500 eliot/timestamp: 1425356900\n\n')) def test_janky_message(self): """ @@ -979,10 +1035,10 @@ class RenderTasksTests(TestCase): ExactlyEquals( u'cdeb220d-7605-4d5f-\u241b(08341-1a170222e308\n' u'\u2514\u2500\u2500 M\u241b(0/1\n' + u' \u251c\u2500\u2500 eliot/timestamp: 1425356700\n' u' \u251c\u2500\u2500 er\u241bror: False\n' - u' \u251c\u2500\u2500 mes\u240asage: ' - u'Main loop\u241b(0terminated.\n' - u' \u2514\u2500\u2500 timestamp: 1425356700\n\n')) + u' \u2514\u2500\u2500 mes\u240asage: ' + u'Main loop\u241b(0terminated.\n\n')) def test_janky_action(self): """ @@ -996,8 +1052,9 @@ class RenderTasksTests(TestCase): u'\u2514\u2500\u2500 A\u241b(0/1 \u21d2 started\n' u' \u251c\u2500\u2500 \u241b(0: \n' u' \u2502 \u2514\u2500\u2500 \u241b(0: nope\n' - u' \u251c\u2500\u2500 mes\u240asage: hello\u241b(0world\n' - u' \u2514\u2500\u2500 timestamp: 1425356800\u241b(0\n\n')) + u' \u251c\u2500\u2500 eliot/timestamp: 1425356800\u241b(0\n' + u' \u2514\u2500\u2500 mes\u240asage: hello\u241b(0world\n\n' + )) def test_colorize(self): """ @@ -1013,11 +1070,11 @@ class RenderTasksTests(TestCase): colors.parent(u'app:action'), colors.success(u'started')), u' \u251c\u2500\u2500 {}: {}'.format( - colors.prop(u'timestamp'), u'1425356800'), + colors.prop(u'eliot/timestamp'), u'1425356800'), u' \u2514\u2500\u2500 {}/2 \u21d2 {}'.format( colors.parent(u'app:action'), colors.success(u'succeeded')), u' \u2514\u2500\u2500 {}: {}'.format( - colors.prop('timestamp'), u'1425356800'), + colors.prop('eliot/timestamp'), u'1425356800'), u'\n', ]))) diff --git a/eliottree/test/test_util.py b/eliottree/test/test_util.py new file mode 100644 index 0000000..c75cdde --- /dev/null +++ b/eliottree/test/test_util.py @@ -0,0 +1,64 @@ +from testtools import ExpectedException, TestCase +from testtools.matchers import AfterPreprocessing as After +from testtools.matchers import ( + Equals, Is, MatchesAll, MatchesListwise, MatchesPredicate, + MatchesStructure) + +from eliottree._util import format_namespace, is_namespace, namespaced + + +class NamespaceTests(TestCase): + """ + Tests for `namespaced`, `format_namespace` and `is_namespace`. + """ + def test_namespaced(self): + """ + `namespaced` creates a function that when called produces a namespaced + name. + """ + self.assertThat( + namespaced(u'foo'), + MatchesAll( + MatchesPredicate(callable, '%s is not callable'), + After( + lambda f: f(u'bar'), + MatchesAll( + MatchesListwise([ + Equals(u'foo'), + Equals(u'bar')]), + MatchesStructure( + prefix=Equals(u'foo'), + name=Equals(u'bar')))))) + + def test_format_not_namespace(self): + """ + `format_namespace` raises `TypeError` if its argument is not a + namespaced name. + """ + with ExpectedException(TypeError): + format_namespace(42) + + def test_format_namespace(self): + """ + `format_namespace` creates a text representation of a namespaced name. + """ + self.assertThat( + format_namespace(namespaced(u'foo')(u'bar')), + Equals(u'foo/bar')) + + def test_is_namespace(self): + """ + `is_namespace` returns ``True`` only for namespaced names. + """ + self.assertThat( + is_namespace(42), + Is(False)) + self.assertThat( + is_namespace((u'foo', u'bar')), + Is(False)) + self.assertThat( + is_namespace(namespaced(u'foo')), + Is(False)) + self.assertThat( + is_namespace(namespaced(u'foo')(u'bar')), + Is(True))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 4 }
17.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
boltons==25.0.0 eliot==1.17.5 -e git+https://github.com/jonathanj/eliottree.git@983999c822a83258d4f3bc3086925649bcf672f2#egg=eliot_tree exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work iso8601==2.1.0 jmespath==1.0.1 orjson==3.10.16 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pyrsistent==0.20.0 pytest @ file:///croot/pytest_1738938843180/work six==1.17.0 termcolor==3.0.0 testtools==2.7.2 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work toolz==1.0.0 tree-format==0.1.2 zope.interface==7.2
name: eliottree channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boltons==25.0.0 - eliot==1.17.5 - iso8601==2.1.0 - jmespath==1.0.1 - orjson==3.10.16 - pyrsistent==0.20.0 - six==1.17.0 - termcolor==3.0.0 - testtools==2.7.2 - toolz==1.0.0 - tree-format==0.1.2 - zope-interface==7.2 prefix: /opt/conda/envs/eliottree
[ "eliottree/test/test_cli.py::EndToEndTests::test_eliot_parse_error", "eliottree/test/test_cli.py::EndToEndTests::test_file", "eliottree/test/test_cli.py::EndToEndTests::test_json_parse_error", "eliottree/test/test_cli.py::EndToEndTests::test_stdin", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_anything", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_bytes", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_not_eliot_timestamp_field", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_timestamp_field", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_timestamp_field_not_human", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_unicode", "eliottree/test/test_render.py::DefaultValueFormatterTests::test_unicode_control_characters", "eliottree/test/test_render.py::RenderTaskNodesTests::test_colorize", "eliottree/test/test_render.py::RenderTaskNodesTests::test_deprecated", "eliottree/test/test_render.py::RenderTaskNodesTests::test_dict_data", "eliottree/test/test_render.py::RenderTaskNodesTests::test_field_limit", "eliottree/test/test_render.py::RenderTaskNodesTests::test_ignored_keys", "eliottree/test/test_render.py::RenderTaskNodesTests::test_janky_action", "eliottree/test/test_render.py::RenderTaskNodesTests::test_janky_message", "eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field", "eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field_limit", "eliottree/test/test_render.py::RenderTaskNodesTests::test_nested", "eliottree/test/test_render.py::RenderTaskNodesTests::test_task_data", "eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks", "eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks_human_readable", "eliottree/test/test_render.py::GetNameFactoryTests::test_node", "eliottree/test/test_render.py::GetNameFactoryTests::test_node_failure", "eliottree/test/test_render.py::GetNameFactoryTests::test_node_success", "eliottree/test/test_render.py::GetNameFactoryTests::test_text", "eliottree/test/test_render.py::GetNameFactoryTests::test_tuple_dict", "eliottree/test/test_render.py::GetNameFactoryTests::test_tuple_root", "eliottree/test/test_render.py::GetNameFactoryTests::test_tuple_unicode", "eliottree/test/test_render.py::MessageNameTests::test_action_status", "eliottree/test/test_render.py::MessageNameTests::test_action_status_failed", "eliottree/test/test_render.py::MessageNameTests::test_action_status_success", "eliottree/test/test_render.py::MessageNameTests::test_action_task_level", "eliottree/test/test_render.py::MessageNameTests::test_action_type", "eliottree/test/test_render.py::MessageNameTests::test_message_task_level", "eliottree/test/test_render.py::MessageNameTests::test_message_type", "eliottree/test/test_render.py::MessageNameTests::test_unknown", "eliottree/test/test_render.py::FormatNodeTests::test_other", "eliottree/test/test_render.py::FormatNodeTests::test_task", "eliottree/test/test_render.py::FormatNodeTests::test_tuple_dict", "eliottree/test/test_render.py::FormatNodeTests::test_tuple_list", "eliottree/test/test_render.py::FormatNodeTests::test_tuple_other", "eliottree/test/test_render.py::FormatNodeTests::test_written_action", "eliottree/test/test_render.py::MessageFieldsTests::test_empty", "eliottree/test/test_render.py::MessageFieldsTests::test_fields", "eliottree/test/test_render.py::MessageFieldsTests::test_ignored_fields", "eliottree/test/test_render.py::GetChildrenTests::test_other", "eliottree/test/test_render.py::GetChildrenTests::test_task_action", "eliottree/test/test_render.py::GetChildrenTests::test_tuple_dict", "eliottree/test/test_render.py::GetChildrenTests::test_tuple_list", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_children", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_end", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_ignored_fields", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_no_children", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_no_end", "eliottree/test/test_render.py::GetChildrenTests::test_written_action_start", "eliottree/test/test_render.py::GetChildrenTests::test_written_message", "eliottree/test/test_render.py::RenderTasksTests::test_colorize", "eliottree/test/test_render.py::RenderTasksTests::test_dict_data", "eliottree/test/test_render.py::RenderTasksTests::test_field_limit", "eliottree/test/test_render.py::RenderTasksTests::test_format_node_failures", "eliottree/test/test_render.py::RenderTasksTests::test_format_value_failures", "eliottree/test/test_render.py::RenderTasksTests::test_ignored_keys", "eliottree/test/test_render.py::RenderTasksTests::test_janky_action", "eliottree/test/test_render.py::RenderTasksTests::test_janky_message", "eliottree/test/test_render.py::RenderTasksTests::test_list_data", "eliottree/test/test_render.py::RenderTasksTests::test_multiline_field", "eliottree/test/test_render.py::RenderTasksTests::test_multiline_field_limit", "eliottree/test/test_render.py::RenderTasksTests::test_nested", "eliottree/test/test_render.py::RenderTasksTests::test_task_data", "eliottree/test/test_render.py::RenderTasksTests::test_tasks", "eliottree/test/test_render.py::RenderTasksTests::test_tasks_human_readable", "eliottree/test/test_util.py::NamespaceTests::test_format_namespace", "eliottree/test/test_util.py::NamespaceTests::test_format_not_namespace", "eliottree/test/test_util.py::NamespaceTests::test_is_namespace", "eliottree/test/test_util.py::NamespaceTests::test_namespaced" ]
[]
[]
[]
MIT License
2,807
2,238
[ "eliottree/_cli.py", "eliottree/_render.py", "eliottree/render.py", "setup.py" ]
F5Networks__f5-common-python-1485
fb001e95cc16ddf84ba03c3193582c69cd8ce0df
2018-07-24 22:21:08
a97a2ef2abb9114a2152453671dee0ac2ae70d1f
jasonrahm: @drenout can you change your two append lines to this line instead: `self._meta_data['allowed_commands'].extend(['revoke', 'install'])`
diff --git a/f5/bigip/tm/sys/license.py b/f5/bigip/tm/sys/license.py index df150f9..c38d3d4 100644 --- a/f5/bigip/tm/sys/license.py +++ b/f5/bigip/tm/sys/license.py @@ -41,7 +41,7 @@ class License(UnnamedResource, CommandExecutionMixin): super(License, self).__init__(sys) self._meta_data['required_json_kind'] =\ "tm:sys:license:licensestats" - self._meta_data['allowed_commands'].append('revoke') + self._meta_data['allowed_commands'].extend(['revoke', 'install']) def exec_cmd(self, command, **kwargs): self._is_allowed_command(command)
Add license installation Add license installation command similar to the revoking the license: Code snippet for the revoking the license: ```python mgnt = ManagementRoot(bigip_mgnt, user, pass) mgnt.tm.sys.license.exec_cmd('revoke')` ``` Code snippet for the license installation: ```python mgnt = ManagementRoot(bigip_mgnt, user, pass) mgnt.tm.sys.license.exec_cmd('install', registrationKey=regkey) ```
F5Networks/f5-common-python
diff --git a/f5/bigip/tm/sys/test/unit/test_license.py b/f5/bigip/tm/sys/test/unit/test_license.py index 617edf2..27222bc 100644 --- a/f5/bigip/tm/sys/test/unit/test_license.py +++ b/f5/bigip/tm/sys/test/unit/test_license.py @@ -37,3 +37,17 @@ def test_delete_raises(FakeLicense): with pytest.raises(UnsupportedMethod) as EIO: FakeLicense.delete() assert str(EIO.value) == "License does not support the delete method" + + +def test_exec_install(FakeLicense): + assert "install" in FakeLicense._meta_data['allowed_commands'] + FakeLicense._meta_data['bigip']._meta_data.__getitem__.return_value = "14.0.0" + FakeLicense._exec_cmd = mock.MagicMock() + version_dict = {"13.1.0": 13, "14.0.0": 14} + + def get_version(version): + return version_dict[version] + + License.LooseVersion = mock.MagicMock(side_effect=get_version) + FakeLicense.exec_cmd("install", registrationKey='1234-56789-0') + FakeLicense._exec_cmd.assert_called_with("install", registrationKey='1234-56789-0')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "pytest-bdd", "pytest-benchmark", "pytest-randomly", "responses", "mock", "hypothesis", "freezegun", "trustme", "requests-mock", "requests", "tomlkit" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 coverage==7.8.0 cryptography==44.0.2 exceptiongroup==1.2.2 execnet==2.1.1 f5-icontrol-rest==1.3.13 -e git+https://github.com/F5Networks/f5-common-python.git@fb001e95cc16ddf84ba03c3193582c69cd8ce0df#egg=f5_sdk freezegun==1.5.1 gherkin-official==29.0.0 hypothesis==6.130.6 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 Mako==1.3.9 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 parse==1.20.2 parse_type==0.6.4 pluggy==1.5.0 py-cpuinfo==9.0.0 pycparser==2.22 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-bdd==8.1.0 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-randomly==3.16.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 requests-mock==1.12.1 responses==0.25.7 six==1.17.0 sortedcontainers==2.4.0 tomli==2.2.1 tomlkit==0.13.2 trustme==1.2.1 typing_extensions==4.13.0 urllib3==2.3.0 zipp==3.21.0
name: f5-common-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - coverage==7.8.0 - cryptography==44.0.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - f5-icontrol-rest==1.3.13 - freezegun==1.5.1 - gherkin-official==29.0.0 - hypothesis==6.130.6 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - mako==1.3.9 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - parse==1.20.2 - parse-type==0.6.4 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pycparser==2.22 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-bdd==8.1.0 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-randomly==3.16.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - requests-mock==1.12.1 - responses==0.25.7 - six==1.17.0 - sortedcontainers==2.4.0 - tomli==2.2.1 - tomlkit==0.13.2 - trustme==1.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/f5-common-python
[ "f5/bigip/tm/sys/test/unit/test_license.py::test_exec_install" ]
[]
[ "f5/bigip/tm/sys/test/unit/test_license.py::test_delete_raises", "f5/bigip/tm/sys/test/unit/test_license.py::test_create_raises" ]
[]
Apache License 2.0
2,823
180
[ "f5/bigip/tm/sys/license.py" ]
Azure__WALinuxAgent-1273
066d711c4dd3f5a166a19da1910ee92b35cd3cbb
2018-07-25 01:14:02
6e9b985c1d7d564253a1c344bab01b45093103cd
boumenot: Sync'ed offline. LGTM.
diff --git a/azurelinuxagent/common/utils/processutil.py b/azurelinuxagent/common/utils/processutil.py index fe9dd4a5..9c0eb24b 100644 --- a/azurelinuxagent/common/utils/processutil.py +++ b/azurelinuxagent/common/utils/processutil.py @@ -16,7 +16,7 @@ # # Requires Python 2.6+ and Openssl 1.0+ # - +import multiprocessing import subprocess import sys import os @@ -100,75 +100,57 @@ def _destroy_process(process, signal_to_send=signal.SIGKILL): pass # If the process is already gone, that's fine -def capture_from_process_modern(process, cmd, timeout): - try: - stdout, stderr = process.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - # Just kill the process. The .communicate method will gather stdout/stderr, close those pipes, and reap - # the zombie process. That is, .communicate() does all the other stuff that _destroy_process does. +def capture_from_process_poll(process, cmd, timeout): + """ + If the process forks, we cannot capture anything we block until the process tree completes + """ + retry = timeout + while retry > 0 and process.poll() is None: + time.sleep(1) + retry -= 1 + + # process did not fork, timeout expired + if retry == 0: os.killpg(os.getpgid(process.pid), signal.SIGKILL) stdout, stderr = process.communicate() msg = format_stdout_stderr(sanitize(stdout), sanitize(stderr)) raise ExtensionError("Timeout({0}): {1}\n{2}".format(timeout, cmd, msg)) - except OSError as e: - _destroy_process(process, signal.SIGKILL) - raise ExtensionError("Error while running '{0}': {1}".format(cmd, e.strerror)) - except ValueError: - _destroy_process(process, signal.SIGKILL) - raise ExtensionError("Invalid timeout ({0}) specified for '{1}'".format(timeout, cmd)) - except Exception as e: - _destroy_process(process, signal.SIGKILL) - raise ExtensionError("Exception while running '{0}': {1}".format(cmd, e)) - return stdout, stderr + # process completed or forked + return_code = process.wait() + if return_code != 0: + raise ExtensionError("Non-zero exit code: {0}, {1}".format(return_code, cmd)) + stderr = b'' + stdout = b'cannot collect stdout' -def capture_from_process_pre_33(process, cmd, timeout): - """ - Can't use process.communicate(timeout=), so do it the hard way. - """ - watcher_process_exited = 0 - watcher_process_timed_out = 1 - - def kill_on_timeout(pid, watcher_timeout): - """ - Check for the continued existence of pid once per second. If pid no longer exists, exit with code 0. - If timeout (in seconds) elapses, kill pid and exit with code 1. - """ - for iteration in range(watcher_timeout): - time.sleep(1) - try: - os.kill(pid, 0) - except OSError as ex: - if ESRCH == ex.errno: # Process no longer exists - exit(watcher_process_exited) - os.killpg(os.getpgid(pid), signal.SIGKILL) - exit(watcher_process_timed_out) - - watcher = Process(target=kill_on_timeout, args=(process.pid, timeout)) - watcher.start() + # attempt non-blocking process communication to capture output + def proc_comm(_process, _return): + try: + _stdout, _stderr = _process.communicate() + _return[0] = _stdout + _return[1] = _stderr + except Exception: + pass try: - # Now, block "forever" waiting on process. If the timeout-limited Event wait in the watcher pops, - # it will kill the process and Popen.communicate() will return - stdout, stderr = process.communicate() - except OSError as e: - _destroy_process(process, signal.SIGKILL) - raise ExtensionError("Error while running '{0}': {1}".format(cmd, e.strerror)) - except Exception as e: - _destroy_process(process, signal.SIGKILL) - raise ExtensionError("Exception while running '{0}': {1}".format(cmd, e)) + mgr = multiprocessing.Manager() + ret_dict = mgr.dict() - timeout_happened = False - watcher.join(1) - if watcher.is_alive(): - watcher.terminate() - else: - timeout_happened = (watcher.exitcode == watcher_process_timed_out) + cproc = Process(target=proc_comm, args=(process, ret_dict)) + cproc.start() - if timeout_happened: - msg = format_stdout_stderr(sanitize(stdout), sanitize(stderr)) - raise ExtensionError("Timeout({0}): {1}\n{2}".format(timeout, cmd, msg)) + # allow 1s to capture output + cproc.join(1) + + if cproc.is_alive(): + cproc.terminate() + + stdout = ret_dict[0] + stderr = ret_dict[1] + + except Exception: + pass return stdout, stderr @@ -204,10 +186,7 @@ def capture_from_process_raw(process, cmd, timeout): _destroy_process(process, signal.SIGKILL) raise ExtensionError("Subprocess was not root of its own process group") - if sys.version_info < (3, 3): - stdout, stderr = capture_from_process_pre_33(process, cmd, timeout) - else: - stdout, stderr = capture_from_process_modern(process, cmd, timeout) + stdout, stderr = capture_from_process_poll(process, cmd, timeout) return stdout, stderr diff --git a/azurelinuxagent/common/version.py b/azurelinuxagent/common/version.py index 650eaf0f..4d10b024 100644 --- a/azurelinuxagent/common/version.py +++ b/azurelinuxagent/common/version.py @@ -113,7 +113,7 @@ def get_distro(): AGENT_NAME = "WALinuxAgent" AGENT_LONG_NAME = "Azure Linux Agent" -AGENT_VERSION = '2.2.29' +AGENT_VERSION = '2.2.30' AGENT_LONG_VERSION = "{0}-{1}".format(AGENT_NAME, AGENT_VERSION) AGENT_DESCRIPTION = """ The Azure Linux Agent supports the provisioning and running of Linux diff --git a/azurelinuxagent/ga/exthandlers.py b/azurelinuxagent/ga/exthandlers.py index 21cc2ef2..f46447ab 100644 --- a/azurelinuxagent/ga/exthandlers.py +++ b/azurelinuxagent/ga/exthandlers.py @@ -1002,12 +1002,12 @@ class ExtHandlerInstance(object): CGroups.add_to_extension_cgroup(self.ext_handler.name) process = subprocess.Popen(full_path, - shell=True, - cwd=base_dir, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - env=os.environ, - preexec_fn=pre_exec_function) + shell=True, + cwd=base_dir, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=os.environ, + preexec_fn=pre_exec_function) except OSError as e: raise ExtensionError("Failed to launch '{0}': {1}".format(full_path, e.strerror)) @@ -1016,7 +1016,9 @@ class ExtHandlerInstance(object): msg = capture_from_process(process, cmd, timeout) ret = process.poll() - if ret is None or ret != 0: + if ret is None: + raise ExtensionError("Process {0} was not terminated: {1}\n{2}".format(process.pid, cmd, msg)) + if ret != 0: raise ExtensionError("Non-zero exit code: {0}, {1}\n{2}".format(ret, cmd, msg)) duration = elapsed_milliseconds(begin_utc)
Agent Prematurely Terminates Long Running Extensions A user opened an issue against [Azure/custom-script-extension-linux #139](https://github.com/Azure/custom-script-extension-linux/issues/139) about the extension prematurely timing out. I have verified this issue against 2.2.29. ```sh az vm extension set -g my-resource-group --vm-name vm1 --publisher Microsoft.Azure.Extensions --name CustomScript --version 2.0 --settings "{ \"commandToExecute\": \"sleep 360; ls\" }" ``` The agent will kill the process after five minutes, which is different from previous behavior. The logs for the agent claim that it moved the extension PID into a cGroup, but the PID it referenced in the logs is the PID *agent ext-handler process* not the extension.
Azure/WALinuxAgent
diff --git a/tests/ga/test_update.py b/tests/ga/test_update.py index a3aa7ae9..af5dcbba 100644 --- a/tests/ga/test_update.py +++ b/tests/ga/test_update.py @@ -1000,8 +1000,8 @@ class TestUpdate(UpdateTestCase): self.assertTrue(2 < len(self.update_handler.agents)) # Purge every other agent - kept_agents = self.update_handler.agents[1::2] - purged_agents = self.update_handler.agents[::2] + kept_agents = self.update_handler.agents[::2] + purged_agents = self.update_handler.agents[1::2] # Reload and assert only the kept agents remain on disk self.update_handler.agents = kept_agents diff --git a/tests/utils/test_process_util.py b/tests/utils/test_process_util.py index 85abdb5a..a950e556 100644 --- a/tests/utils/test_process_util.py +++ b/tests/utils/test_process_util.py @@ -14,12 +14,12 @@ # # Requires Python 2.6+ and Openssl 1.0+ # - +import datetime import subprocess from azurelinuxagent.common.exception import ExtensionError from azurelinuxagent.common.utils.processutil \ - import format_stdout_stderr, capture_from_process, capture_from_process_raw + import format_stdout_stderr, capture_from_process from tests.tools import * import sys @@ -121,7 +121,14 @@ class TestProcessUtils(AgentTestCase): actual = capture_from_process(process, cmd) self.assertEqual(expected, actual) - def test_process_timeout(self): + def test_process_timeout_non_forked(self): + """ + non-forked process runs for 20 seconds, timeout is 10 seconds + we expect: + - test to run in just over 10 seconds + - exception should be thrown + - output should be collected + """ cmd = "{0} -t 20".format(process_target) process = subprocess.Popen(cmd, shell=True, @@ -130,19 +137,93 @@ class TestProcessUtils(AgentTestCase): env=os.environ, preexec_fn=os.setsid) - if sys.version_info < (2, 7): - self.assertRaises(ExtensionError, capture_from_process_raw, process, cmd, 10) - else: - with self.assertRaises(ExtensionError) as ee: - capture_from_process_raw(process, cmd, 10) + try: + capture_from_process(process, 'sleep 20', 10) + self.fail('Timeout exception was expected') + except ExtensionError as e: + body = str(e) + self.assertTrue('Timeout(10)' in body) + self.assertTrue('Iteration 9' in body) + self.assertFalse('Iteration 11' in body) + except Exception as gen_ex: + self.fail('Unexpected exception: {0}'.format(gen_ex)) - body = str(ee.exception) - if sys.version_info >= (3, 2): - self.assertNotRegex(body, "Iteration 12") - self.assertRegex(body, "Iteration 8") - else: - self.assertNotRegexpMatches(body, "Iteration 12") - self.assertRegexpMatches(body, "Iteration 8") + def test_process_timeout_forked(self): + """ + forked process runs for 20 seconds, timeout is 10 seconds + we expect: + - test to run in less than 3 seconds + - no exception should be thrown + - no output is collected + """ + cmd = "{0} -t 20 &".format(process_target) + process = subprocess.Popen(cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=os.environ, + preexec_fn=os.setsid) + + start = datetime.datetime.utcnow() + try: + cap = capture_from_process(process, 'sleep 20 &', 10) + except Exception as e: + self.fail('No exception should be thrown for a long running process which forks: {0}'.format(e)) + duration = datetime.datetime.utcnow() - start + + self.assertTrue(duration < datetime.timedelta(seconds=3)) + self.assertEqual('[stdout]\ncannot collect stdout\n\n[stderr]\n', cap) + + def test_process_behaved_non_forked(self): + """ + non-forked process runs for 10 seconds, timeout is 20 seconds + we expect: + - test to run in just over 10 seconds + - no exception should be thrown + - output should be collected + """ + cmd = "{0} -t 10".format(process_target) + process = subprocess.Popen(cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=os.environ, + preexec_fn=os.setsid) + + try: + body = capture_from_process(process, 'sleep 10', 20) + except Exception as gen_ex: + self.fail('Unexpected exception: {0}'.format(gen_ex)) + + self.assertFalse('Timeout' in body) + self.assertTrue('Iteration 9' in body) + self.assertTrue('Iteration 10' in body) + + def test_process_behaved_forked(self): + """ + forked process runs for 10 seconds, timeout is 20 seconds + we expect: + - test to run in under 3 seconds + - no exception should be thrown + - output is not collected + """ + cmd = "{0} -t 10 &".format(process_target) + process = subprocess.Popen(cmd, + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=os.environ, + preexec_fn=os.setsid) + + start = datetime.datetime.utcnow() + try: + body = capture_from_process(process, 'sleep 10 &', 20) + except Exception as e: + self.fail('No exception should be thrown for a well behaved process which forks: {0}'.format(e)) + duration = datetime.datetime.utcnow() - start + + self.assertTrue(duration < datetime.timedelta(seconds=3)) + self.assertEqual('[stdout]\ncannot collect stdout\n\n[stderr]\n', body) def test_process_bad_pgid(self): """
{ "commit_name": "merge_commit", "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, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work -e git+https://github.com/Azure/WALinuxAgent.git@066d711c4dd3f5a166a19da1910ee92b35cd3cbb#egg=WALinuxAgent zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: WALinuxAgent channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - nose==1.3.7 prefix: /opt/conda/envs/WALinuxAgent
[ "tests/ga/test_update.py::TestUpdate::test_purge_agents", "tests/utils/test_process_util.py::TestProcessUtils::test_process_behaved_forked", "tests/utils/test_process_util.py::TestProcessUtils::test_process_timeout_forked" ]
[]
[ "tests/ga/test_update.py::TestGuestAgentError::test_clear", "tests/ga/test_update.py::TestGuestAgentError::test_creation", "tests/ga/test_update.py::TestGuestAgentError::test_mark_failure", "tests/ga/test_update.py::TestGuestAgentError::test_mark_failure_permanent", "tests/ga/test_update.py::TestGuestAgentError::test_save", "tests/ga/test_update.py::TestGuestAgentError::test_str", "tests/ga/test_update.py::TestGuestAgent::test_clear_error", "tests/ga/test_update.py::TestGuestAgent::test_creation", "tests/ga/test_update.py::TestGuestAgent::test_download", "tests/ga/test_update.py::TestGuestAgent::test_download_fail", "tests/ga/test_update.py::TestGuestAgent::test_download_fallback", "tests/ga/test_update.py::TestGuestAgent::test_ensure_download_skips_blacklisted", "tests/ga/test_update.py::TestGuestAgent::test_ensure_downloaded", "tests/ga/test_update.py::TestGuestAgent::test_ensure_downloaded_download_fails", "tests/ga/test_update.py::TestGuestAgent::test_ensure_downloaded_load_manifest_fails", "tests/ga/test_update.py::TestGuestAgent::test_ensure_downloaded_unpack_fails", "tests/ga/test_update.py::TestGuestAgent::test_ioerror_not_blacklisted", "tests/ga/test_update.py::TestGuestAgent::test_is_available", "tests/ga/test_update.py::TestGuestAgent::test_is_blacklisted", "tests/ga/test_update.py::TestGuestAgent::test_is_downloaded", "tests/ga/test_update.py::TestGuestAgent::test_load_error", "tests/ga/test_update.py::TestGuestAgent::test_load_manifest", "tests/ga/test_update.py::TestGuestAgent::test_load_manifest_is_empty", "tests/ga/test_update.py::TestGuestAgent::test_load_manifest_is_malformed", "tests/ga/test_update.py::TestGuestAgent::test_load_manifest_missing", "tests/ga/test_update.py::TestGuestAgent::test_mark_failure", "tests/ga/test_update.py::TestGuestAgent::test_resource_gone_error_not_blacklisted", "tests/ga/test_update.py::TestGuestAgent::test_unpack", "tests/ga/test_update.py::TestGuestAgent::test_unpack_fail", "tests/ga/test_update.py::TestUpdate::test_creation", "tests/ga/test_update.py::TestUpdate::test_emit_restart_event_emits_event_if_not_clean_start", "tests/ga/test_update.py::TestUpdate::test_ensure_no_orphans", "tests/ga/test_update.py::TestUpdate::test_ensure_no_orphans_ignores_exceptions", "tests/ga/test_update.py::TestUpdate::test_ensure_no_orphans_kills_after_interval", "tests/ga/test_update.py::TestUpdate::test_ensure_no_orphans_skips_if_no_orphans", "tests/ga/test_update.py::TestUpdate::test_ensure_partition_assigned", "tests/ga/test_update.py::TestUpdate::test_ensure_readonly_leaves_unmodified", "tests/ga/test_update.py::TestUpdate::test_ensure_readonly_sets_readonly", "tests/ga/test_update.py::TestUpdate::test_evaluate_agent_health_ignores_installed_agent", "tests/ga/test_update.py::TestUpdate::test_evaluate_agent_health_raises_exception_for_restarting_agent", "tests/ga/test_update.py::TestUpdate::test_evaluate_agent_health_resets_with_new_agent", "tests/ga/test_update.py::TestUpdate::test_evaluate_agent_health_will_not_raise_exception_for_long_restarts", "tests/ga/test_update.py::TestUpdate::test_evaluate_agent_health_will_not_raise_exception_too_few_restarts", "tests/ga/test_update.py::TestUpdate::test_filter_blacklisted_agents", "tests/ga/test_update.py::TestUpdate::test_find_agents", "tests/ga/test_update.py::TestUpdate::test_find_agents_does_reload", "tests/ga/test_update.py::TestUpdate::test_find_agents_sorts", "tests/ga/test_update.py::TestUpdate::test_get_host_plugin_returns_host_for_wireserver", "tests/ga/test_update.py::TestUpdate::test_get_host_plugin_returns_none_otherwise", "tests/ga/test_update.py::TestUpdate::test_get_latest_agent", "tests/ga/test_update.py::TestUpdate::test_get_latest_agent_excluded", "tests/ga/test_update.py::TestUpdate::test_get_latest_agent_no_updates", "tests/ga/test_update.py::TestUpdate::test_get_latest_agent_skip_updates", "tests/ga/test_update.py::TestUpdate::test_get_latest_agent_skips_unavailable", "tests/ga/test_update.py::TestUpdate::test_get_pid_files", "tests/ga/test_update.py::TestUpdate::test_get_pid_files_returns_previous", "tests/ga/test_update.py::TestUpdate::test_is_clean_start_returns_false_for_exceptions", "tests/ga/test_update.py::TestUpdate::test_is_clean_start_returns_false_when_sentinel_exists", "tests/ga/test_update.py::TestUpdate::test_is_clean_start_returns_true_when_no_sentinel", "tests/ga/test_update.py::TestUpdate::test_is_orphaned_returns_false_if_parent_exists", "tests/ga/test_update.py::TestUpdate::test_is_orphaned_returns_true_if_parent_does_not_exist", "tests/ga/test_update.py::TestUpdate::test_is_orphaned_returns_true_if_parent_is_init", "tests/ga/test_update.py::TestUpdate::test_is_version_available", "tests/ga/test_update.py::TestUpdate::test_is_version_available_accepts_current", "tests/ga/test_update.py::TestUpdate::test_is_version_available_rejects", "tests/ga/test_update.py::TestUpdate::test_is_version_available_rejects_by_default", "tests/ga/test_update.py::TestUpdate::test_package_filter_for_agent_manifest", "tests/ga/test_update.py::TestUpdate::test_run", "tests/ga/test_update.py::TestUpdate::test_run_clears_sentinel_on_successful_exit", "tests/ga/test_update.py::TestUpdate::test_run_emits_restart_event", "tests/ga/test_update.py::TestUpdate::test_run_keeps_running", "tests/ga/test_update.py::TestUpdate::test_run_latest", "tests/ga/test_update.py::TestUpdate::test_run_latest_captures_signals", "tests/ga/test_update.py::TestUpdate::test_run_latest_creates_only_one_signal_handler", "tests/ga/test_update.py::TestUpdate::test_run_latest_defaults_to_current", "tests/ga/test_update.py::TestUpdate::test_run_latest_exception_blacklists", "tests/ga/test_update.py::TestUpdate::test_run_latest_exception_does_not_blacklist_if_terminating", "tests/ga/test_update.py::TestUpdate::test_run_latest_forwards_output", "tests/ga/test_update.py::TestUpdate::test_run_latest_nonzero_code_marks_failures", "tests/ga/test_update.py::TestUpdate::test_run_latest_passes_child_args", "tests/ga/test_update.py::TestUpdate::test_run_latest_polling_stops_at_failure", "tests/ga/test_update.py::TestUpdate::test_run_latest_polling_stops_at_success", "tests/ga/test_update.py::TestUpdate::test_run_latest_polls_and_waits_for_success", "tests/ga/test_update.py::TestUpdate::test_run_latest_polls_frequently_if_installed_is_latest", "tests/ga/test_update.py::TestUpdate::test_run_latest_polls_moderately_if_installed_not_latest", "tests/ga/test_update.py::TestUpdate::test_run_leaves_sentinel_on_unsuccessful_exit", "tests/ga/test_update.py::TestUpdate::test_run_stops_if_orphaned", "tests/ga/test_update.py::TestUpdate::test_run_stops_if_update_available", "tests/ga/test_update.py::TestUpdate::test_set_agents_sets_agents", "tests/ga/test_update.py::TestUpdate::test_set_agents_sorts_agents", "tests/ga/test_update.py::TestUpdate::test_set_sentinel", "tests/ga/test_update.py::TestUpdate::test_set_sentinel_writes_current_agent", "tests/ga/test_update.py::TestUpdate::test_shutdown", "tests/ga/test_update.py::TestUpdate::test_shutdown_ignores_exceptions", "tests/ga/test_update.py::TestUpdate::test_shutdown_ignores_missing_sentinel_file", "tests/ga/test_update.py::TestUpdate::test_update_available_returns_true_if_current_gets_blacklisted", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_handles_missing_family", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_includes_old_agents", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_purges_old_agents", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_returns_true_on_first_use", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_skips_if_too_frequent", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_skips_if_when_no_new_versions", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_skips_when_no_versions", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_skips_when_updates_are_disabled", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_sorts", "tests/ga/test_update.py::TestUpdate::test_upgrade_available_will_refresh_goal_state", "tests/ga/test_update.py::TestUpdate::test_write_pid_file", "tests/ga/test_update.py::TestUpdate::test_write_pid_file_ignores_exceptions", "tests/ga/test_update.py::MonitorThreadTest::test_check_if_env_thread_is_alive", "tests/ga/test_update.py::MonitorThreadTest::test_check_if_monitor_thread_is_alive", "tests/ga/test_update.py::MonitorThreadTest::test_restart_env_thread", "tests/ga/test_update.py::MonitorThreadTest::test_restart_env_thread_if_not_alive", "tests/ga/test_update.py::MonitorThreadTest::test_restart_monitor_thread", "tests/ga/test_update.py::MonitorThreadTest::test_restart_monitor_thread_if_not_alive", "tests/ga/test_update.py::MonitorThreadTest::test_start_threads", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr00", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr01", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr02", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr03", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr04", "tests/utils/test_process_util.py::TestProcessUtils::test_format_stdout_stderr05", "tests/utils/test_process_util.py::TestProcessUtils::test_process_bad_pgid", "tests/utils/test_process_util.py::TestProcessUtils::test_process_behaved_non_forked", "tests/utils/test_process_util.py::TestProcessUtils::test_process_stdout_stderr", "tests/utils/test_process_util.py::TestProcessUtils::test_process_timeout_non_forked" ]
[]
Apache License 2.0
2,824
1,915
[ "azurelinuxagent/common/utils/processutil.py", "azurelinuxagent/common/version.py", "azurelinuxagent/ga/exthandlers.py" ]
joke2k__faker-790
29dff0a0f2a31edac21a18cfa50b5bc9206304b2
2018-07-31 14:58:53
29dff0a0f2a31edac21a18cfa50b5bc9206304b2
diff --git a/faker/providers/address/en_CA/__init__.py b/faker/providers/address/en_CA/__init__.py index 4d8963ed..7e7e989a 100644 --- a/faker/providers/address/en_CA/__init__.py +++ b/faker/providers/address/en_CA/__init__.py @@ -316,7 +316,7 @@ class Provider(AddressProvider): """ return self.random_element(self.postal_code_letters) - def postalcode(self): + def postcode(self): """ Replaces all question mark ('?') occurrences with a random letter from postal_code_formats then passes result to @@ -326,3 +326,6 @@ class Provider(AddressProvider): lambda x: self.postal_code_letter(), self.random_element(self.postal_code_formats)) return self.numerify(temp) + + def postalcode(self): + return self.postcode() diff --git a/faker/providers/address/en_US/__init__.py b/faker/providers/address/en_US/__init__.py index c15c771a..451d5d72 100644 --- a/faker/providers/address/en_US/__init__.py +++ b/faker/providers/address/en_US/__init__.py @@ -332,7 +332,7 @@ class Provider(AddressProvider): def state_abbr(self): return self.random_element(self.states_abbr) - def zipcode(self): + def postcode(self): return "%05d" % self.generator.random.randint(501, 99950) def zipcode_plus4(self): @@ -364,8 +364,11 @@ class Provider(AddressProvider): return self.numerify(self.military_dpo_format) # Aliases + def zipcode(self): + return self.postcode() + def postalcode(self): - return self.zipcode() + return self.postcode() def postalcode_plus4(self): return self.zipcode_plus4() diff --git a/faker/providers/address/ja_JP/__init__.py b/faker/providers/address/ja_JP/__init__.py index 3444e6a1..9d08197f 100644 --- a/faker/providers/address/ja_JP/__init__.py +++ b/faker/providers/address/ja_JP/__init__.py @@ -347,9 +347,12 @@ class Provider(AddressProvider): """ return self.random_element(self.building_names) - def zipcode(self): + def postcode(self): """ :example '101-1212' """ return "%03d-%04d" % (self.generator.random.randint(0, 999), self.generator.random.randint(0, 9999)) + + def zipcode(self): + return self.postcode() diff --git a/faker/providers/address/ko_KR/__init__.py b/faker/providers/address/ko_KR/__init__.py index 0a0ee206..956f7e11 100644 --- a/faker/providers/address/ko_KR/__init__.py +++ b/faker/providers/address/ko_KR/__init__.py @@ -381,8 +381,14 @@ class Provider(AddressProvider): """ return self.bothify(self.random_element(self.postcode_formats)) - def postal_code(self): + def postcode(self): """ :example 12345 """ return self.bothify(self.random_element(self.new_postal_code_formats)) + + def postal_code(self): + """ + :example 12345 + """ + return self.postcode()
en_CA should implement postcode, not postalcode All of the address providers use `postcode` to generate post codes. This is misspelled as `postalcode` by the localization for `en_CA`. ### Expected behavior It would be easier to use faker in a multilingual context if this were spelled consistently. Recommended fix: provide a courtesy alias definition of `postcode` so that CA works the same as everyone else. Perhaps `postalcode` should be deprecated, too. ### Actual behavior ```bash $ grep -r "{{postalcode}}" * | grep -v ".pyc" providers/address/en_CA/__init__.py: "{{street_address}}\n{{city}}, {{province_abbr}} {{postalcode}}", $ grep -r "{{postcode}}" * | grep -v ".pyc" providers/address/fa_IR/__init__.py: "{{street_address}}\n{{city}}, {{state}} {{postcode}}", providers/address/fi_FI/__init__.py: address_formats = ("{{street_address}}\n{{postcode}} {{city}}", ) providers/address/nl_BE/__init__.py: "{{street_address}}\n{{postcode}}\n{{city}}", providers/address/nl_BE/__init__.py: "{{street_address}}\n{{postcode}} {{city}}", providers/address/sk_SK/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) providers/address/uk_UA/__init__.py: address_formats = ['{{street_address}}, {{city}}, {{postcode}}'] providers/address/en_US/__init__.py: "{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", providers/address/en_US/__init__.py: ("{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", 25), providers/address/en_US/__init__.py: ("{{military_apo}}\nAPO {{military_state}} {{postcode}}", 1), providers/address/en_US/__init__.py: ("{{military_ship}} {{last_name}}\nFPO {{military_state}} {{postcode}}", 1), providers/address/en_US/__init__.py: ("{{military_dpo}}\nDPO {{military_state}} {{postcode}}", 1), providers/address/ne_NP/__init__.py: "{{street_name}} {{building_prefix}} {{building_number}} \n{{city}}\n{{district}} {{postcode}}", providers/address/sv_SE/__init__.py: address_formats = ("{{street_address}}\n{{postcode}} {{city}}", ) providers/address/id_ID/__init__.py: '{{street_address}}\n{{city}}, {{state}} {{postcode}}', providers/address/id_ID/__init__.py: '{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}', providers/address/pt_BR/__init__.py: "{{street_address}}\n{{bairro}}\n{{postcode}} {{city}} / {{estado_sigla}}", ) providers/address/it_IT/__init__.py: "{{street_address}}\n{{city}}, {{postcode}} {{state}} ({{state_abbr}})", providers/address/zh_TW/__init__.py: "{{postcode}} {{city}}{{street_address}}{{secondary_address}}", ) providers/address/pt_PT/__init__.py: "{{street_address}}\n{{postcode}} {{city}}", providers/address/hr_HR/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) providers/address/cs_CZ/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) providers/address/__init__.py: address_formats = ('{{street_address}} {{postcode}} {{city}}', ) providers/address/fr_CH/__init__.py: address_formats = ("{{street_address}}\n{{postcode}} {{city}}",) providers/address/he_IL/__init__.py: address_formats = ('{{street_address}}, {{city}}, {{postcode}}', ) providers/address/hi_IN/__init__.py: address_formats = ('{{street_address}}\n{{city}} {{postcode}}', providers/address/hi_IN/__init__.py: '{{street_address}}\n{{city}}-{{postcode}}',) providers/address/sl_SI/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) providers/address/zh_CN/__init__.py: "{{province}}{{city}}{{district}}{{street_address}} {{postcode}}",) providers/address/nl_NL/__init__.py: "{{street_address}}\n{{postcode}}\n{{city}}", providers/address/hu_HU/__init__.py: address_formats = ("{{street_address}}\n{{postcode}} {{city}}",) providers/address/en_AU/__init__.py: "{{street_address}}\n{{city}}, {{state_abbr}}, {{postcode}}", ) providers/address/en_GB/__init__.py: "{{street_address}}\n{{city}}\n{{postcode}}", providers/address/es_MX/__init__.py: "{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", providers/address/ru_RU/__init__.py: address_formats = ('{{city}}, {{street_address}}, {{postcode}}', ) providers/address/es_ES/__init__.py: "{{street_address}}\n{{city}}, {{postcode}}", providers/address/el_GR/__init__.py: "{{street_address}},\n{{postcode}} {{city}}", providers/address/el_GR/__init__.py: "{{street_address}}, {{postcode}} {{city}}", providers/address/no_NO/__init__.py: address_formats = ('{{street_address}}, {{postcode}} {{city}}',) providers/address/pl_PL/__init__.py: "{{street_address}}\n{{postcode}} {{city}}", providers/address/fr_FR/__init__.py: "{{street_address}}\n{{postcode}} {{city}}", providers/address/de_AT/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) providers/address/de_DE/__init__.py: address_formats = ('{{street_address}}\n{{postcode}} {{city}}', ) ```
joke2k/faker
diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py index e7385664..585e0869 100644 --- a/tests/providers/test_address.py +++ b/tests/providers/test_address.py @@ -230,6 +230,12 @@ class TestEnCA(unittest.TestCase): def setUp(self): self.factory = Faker('en_CA') + def test_postcode(self): + for _ in range(100): + postcode = self.factory.postcode() + assert re.match("[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]", + postcode) + def test_postalcode(self): for _ in range(100): postalcode = self.factory.postalcode() @@ -292,6 +298,11 @@ class TestEnUS(unittest.TestCase): assert isinstance(state_abbr, string_types) assert state_abbr in EnUsProvider.states_abbr + def test_postcode(self): + for _ in range(100): + postcode = self.factory.postcode() + assert re.match("\d{5}", postcode) + def test_zipcode(self): for _ in range(100): zipcode = self.factory.zipcode() @@ -420,6 +431,10 @@ class TestJaJP(unittest.TestCase): assert isinstance(building_name, string_types) assert building_name in JaProvider.building_names + postcode = self.factory.postcode() + assert isinstance(postcode, string_types) + assert re.match("\d{3}-\d{4}", postcode) + zipcode = self.factory.zipcode() assert isinstance(zipcode, string_types) assert re.match("\d{3}-\d{4}", zipcode) @@ -428,6 +443,26 @@ class TestJaJP(unittest.TestCase): assert isinstance(address, string_types) +class TestKoKR(unittest.TestCase): + """ Tests addresses in the ko_KR locale """ + + def setUp(self): + self.factory = Faker('ko_KR') + + def test_address(self): + postcode = self.factory.postcode() + assert isinstance(postcode, string_types) + assert re.match("\d{5}", postcode) + + postal_code = self.factory.postal_code() + assert isinstance(postal_code, string_types) + assert re.match("\d{5}", postal_code) + + old_postal_code = self.factory.old_postal_code() + assert isinstance(old_postal_code, string_types) + assert re.match("\d{3}-\d{3}", old_postal_code) + + class TestNeNP(unittest.TestCase): """ Tests addresses in the ne_NP locale """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 4 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tests/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 dnspython==2.2.1 email-validator==1.0.3 -e git+https://github.com/joke2k/faker.git@29dff0a0f2a31edac21a18cfa50b5bc9206304b2#egg=Faker idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 mock==2.0.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 six==1.17.0 text-unidecode==1.2 tomli==1.2.3 typing_extensions==4.1.1 UkPostcodeParser==1.1.2 zipp==3.6.0
name: faker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - dnspython==2.2.1 - email-validator==1.0.3 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==2.0.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - six==1.17.0 - text-unidecode==1.2 - tomli==1.2.3 - typing-extensions==4.1.1 - ukpostcodeparser==1.1.2 - zipp==3.6.0 prefix: /opt/conda/envs/faker
[ "tests/providers/test_address.py::TestEnCA::test_postcode", "tests/providers/test_address.py::TestJaJP::test_address", "tests/providers/test_address.py::TestKoKR::test_address" ]
[]
[ "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_alpha_2_country_codes_as_default", "tests/providers/test_address.py::TestBaseProvider::test_alpha_3_country_codes", "tests/providers/test_address.py::TestBaseProvider::test_bad_country_code_representation", "tests/providers/test_address.py::TestAr_AA::test_alpha_2_country_codes", "tests/providers/test_address.py::TestAr_AA::test_alpha_2_country_codes_as_default", "tests/providers/test_address.py::TestAr_AA::test_alpha_3_country_codes", "tests/providers/test_address.py::TestAr_AA::test_bad_country_code_representation", "tests/providers/test_address.py::TestDeAT::test_city", "tests/providers/test_address.py::TestDeAT::test_country", "tests/providers/test_address.py::TestDeAT::test_latitude", "tests/providers/test_address.py::TestDeAT::test_longitude", "tests/providers/test_address.py::TestDeAT::test_postcode", "tests/providers/test_address.py::TestDeAT::test_state", "tests/providers/test_address.py::TestDeAT::test_street_suffix_long", "tests/providers/test_address.py::TestDeAT::test_street_suffix_short", "tests/providers/test_address.py::TestDeDE::test_city", "tests/providers/test_address.py::TestDeDE::test_country", "tests/providers/test_address.py::TestDeDE::test_state", "tests/providers/test_address.py::TestDeDE::test_street_suffix_long", "tests/providers/test_address.py::TestDeDE::test_street_suffix_short", "tests/providers/test_address.py::TestFiFI::test_city", "tests/providers/test_address.py::TestFiFI::test_street_suffix", "tests/providers/test_address.py::TestElGR::test_city", "tests/providers/test_address.py::TestElGR::test_latlng", "tests/providers/test_address.py::TestElGR::test_line_address", "tests/providers/test_address.py::TestElGR::test_region", "tests/providers/test_address.py::TestEnAU::test_city_prefix", "tests/providers/test_address.py::TestEnAU::test_postcode", "tests/providers/test_address.py::TestEnAU::test_state", "tests/providers/test_address.py::TestEnAU::test_state_abbr", "tests/providers/test_address.py::TestEnCA::test_city_prefix", "tests/providers/test_address.py::TestEnCA::test_postal_code_letter", "tests/providers/test_address.py::TestEnCA::test_postalcode", "tests/providers/test_address.py::TestEnCA::test_province", "tests/providers/test_address.py::TestEnCA::test_province_abbr", "tests/providers/test_address.py::TestEnCA::test_secondary_address", "tests/providers/test_address.py::TestEnGB::test_postcode", "tests/providers/test_address.py::TestEnUS::test_city_prefix", "tests/providers/test_address.py::TestEnUS::test_military_apo", "tests/providers/test_address.py::TestEnUS::test_military_dpo", "tests/providers/test_address.py::TestEnUS::test_military_ship", "tests/providers/test_address.py::TestEnUS::test_military_state", "tests/providers/test_address.py::TestEnUS::test_postcode", "tests/providers/test_address.py::TestEnUS::test_state", "tests/providers/test_address.py::TestEnUS::test_state_abbr", "tests/providers/test_address.py::TestEnUS::test_zipcode", "tests/providers/test_address.py::TestEnUS::test_zipcode_plus4", "tests/providers/test_address.py::TestHuHU::test_address", "tests/providers/test_address.py::TestHuHU::test_postcode_first_digit", "tests/providers/test_address.py::TestHuHU::test_street_address", "tests/providers/test_address.py::TestHuHU::test_street_address_with_county", "tests/providers/test_address.py::TestNeNP::test_address", "tests/providers/test_address.py::TestNoNO::test_address", "tests/providers/test_address.py::TestNoNO::test_city_suffix", "tests/providers/test_address.py::TestNoNO::test_postcode", "tests/providers/test_address.py::TestNoNO::test_street_suffix", "tests/providers/test_address.py::TestZhTW::test_address", "tests/providers/test_address.py::TestZhCN::test_address", "tests/providers/test_address.py::TestPtBr::test_address", "tests/providers/test_address.py::TestPtPT::test_distrito", "tests/providers/test_address.py::TestPtPT::test_freguesia" ]
[]
MIT License
2,847
863
[ "faker/providers/address/en_CA/__init__.py", "faker/providers/address/en_US/__init__.py", "faker/providers/address/ja_JP/__init__.py", "faker/providers/address/ko_KR/__init__.py" ]
nipy__nipype-2669
69dce12bdf256c3bb0a8b6da9a1d1cdce48b66ec
2018-08-02 04:22:30
24e52aa4229fc3ce7c3e3ac79b3317999d35f1d3
diff --git a/nipype/pipeline/engine/base.py b/nipype/pipeline/engine/base.py index 9d0bc3c69..7f7afd392 100644 --- a/nipype/pipeline/engine/base.py +++ b/nipype/pipeline/engine/base.py @@ -36,11 +36,11 @@ class EngineBase(object): """ self._hierarchy = None - self._name = None + self.name = name + self._id = self.name # for compatibility with node expansion using iterables self.base_dir = base_dir self.config = deepcopy(config._sections) - self.name = name @property def name(self): @@ -66,6 +66,14 @@ class EngineBase(object): def outputs(self): raise NotImplementedError + @property + def itername(self): + """Name for expanded iterable""" + itername = self._id + if self._hierarchy: + itername = '%s.%s' % (self._hierarchy, self._id) + return itername + def clone(self, name): """Clone an EngineBase object @@ -95,6 +103,9 @@ class EngineBase(object): def __str__(self): return self.fullname + def __repr__(self): + return self.itername + def save(self, filename=None): if filename is None: filename = 'temp.pklz' diff --git a/nipype/pipeline/engine/nodes.py b/nipype/pipeline/engine/nodes.py index 5ac9e72fa..af93fd140 100644 --- a/nipype/pipeline/engine/nodes.py +++ b/nipype/pipeline/engine/nodes.py @@ -159,7 +159,6 @@ class Node(EngineBase): self._got_inputs = False self._originputs = None self._output_dir = None - self._id = self.name # for compatibility with node expansion using iterables self.iterables = iterables self.synchronize = synchronize @@ -249,14 +248,6 @@ class Node(EngineBase): if hasattr(self._interface.inputs, 'num_threads'): self._interface.inputs.num_threads = self._n_procs - @property - def itername(self): - """Name for expanded iterable""" - itername = self._id - if self._hierarchy: - itername = '%s.%s' % (self._hierarchy, self._id) - return itername - def output_dir(self): """Return the location of the output directory for the node""" # Output dir is cached diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 4ec36afe6..0bb5351ad 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -507,7 +507,7 @@ def _write_detailed_dot(graph, dotfilename): # write nodes edges = [] for n in nx.topological_sort(graph): - nodename = str(n) + nodename = n.itername inports = [] for u, v, d in graph.in_edges(nbunch=n, data=True): for cd in d['connect']: @@ -519,8 +519,8 @@ def _write_detailed_dot(graph, dotfilename): ipstrip = 'in%s' % _replacefunk(inport) opstrip = 'out%s' % _replacefunk(outport) edges.append( - '%s:%s:e -> %s:%s:w;' % (str(u).replace('.', ''), opstrip, - str(v).replace('.', ''), ipstrip)) + '%s:%s:e -> %s:%s:w;' % (u.itername.replace('.', ''), opstrip, + v.itername.replace('.', ''), ipstrip)) if inport not in inports: inports.append(inport) inputstr = ['{IN'] + [
incorrect detailed graphs being generated ### Summary the detailed graph is not listing names of nodes appropriately resulting in incorrect graphs. scroll down to see the multiple arrows containing nodes in the figures of the following notebook. https://miykael.github.io/nipype_tutorial/notebooks/introduction_quickstart.html an example here: ![image](https://user-images.githubusercontent.com/184063/43534422-50e73862-9585-11e8-83d9-697675db63e8.png) i suspect this has something to do with how `__repr__` and `__str__` are being used. @oesteban, @effigies - any quick ideas before i look into the code? ### Actual behavior ### Expected behavior should have printed the old style with multiple nodes. see cell 14 in this notebook: https://github.com/ReproNim/reproducible-imaging/blob/master/notebooks/introductory_dataflows.ipynb ### How to replicate the behavior run the current quickstart notebook in @miykael binder repo.
nipy/nipype
diff --git a/nipype/pipeline/engine/tests/test_engine.py b/nipype/pipeline/engine/tests/test_engine.py index 151849241..44afbb2e2 100644 --- a/nipype/pipeline/engine/tests/test_engine.py +++ b/nipype/pipeline/engine/tests/test_engine.py @@ -441,6 +441,7 @@ def test_write_graph_runs(tmpdir): assert os.path.exists('graph.dot') or os.path.exists( 'graph_detailed.dot') + try: os.remove('graph.dot') except OSError: @@ -484,6 +485,164 @@ def test_deep_nested_write_graph_runs(tmpdir): pass +# examples of dot files used in the following test +dotfile_orig = ['strict digraph {\n', + '"mod1 (engine)";\n', + '"mod2 (engine)";\n', + '"mod1 (engine)" -> "mod2 (engine)";\n', + '}\n'] + +dotfile_detailed_orig = ['digraph structs {\n', + 'node [shape=record];\n', + 'pipemod1 [label="{IN}|{ mod1 | engine | }|{OUT|<outoutput1> output1}"];\n', + 'pipemod2 [label="{IN|<ininput1> input1}|{ mod2 | engine | }|{OUT}"];\n', + 'pipemod1:outoutput1:e -> pipemod2:ininput1:w;\n', + '}'] + + +dotfile_hierarchical = ['digraph pipe{\n', + ' label="pipe";\n', + ' pipe_mod1[label="mod1 (engine)"];\n', + ' pipe_mod2[label="mod2 (engine)"];\n', + ' pipe_mod1 -> pipe_mod2;\n', + '}'] + +dotfile_colored = ['digraph pipe{\n', + ' label="pipe";\n', + ' pipe_mod1[label="mod1 (engine)", style=filled, fillcolor="#FFFFC8"];\n', + ' pipe_mod2[label="mod2 (engine)", style=filled, fillcolor="#FFFFC8"];\n', + ' pipe_mod1 -> pipe_mod2;\n', + '}'] + +dotfiles = { + "orig": dotfile_orig, + "flat": dotfile_orig, + "exec": dotfile_orig, + "hierarchical": dotfile_hierarchical, + "colored": dotfile_colored + } + [email protected]("simple", [True, False]) [email protected]("graph_type", ['orig', 'flat', 'exec', 'hierarchical', 'colored']) +def test_write_graph_dotfile(tmpdir, graph_type, simple): + """ checking dot files for a workflow without iterables""" + tmpdir.chdir() + + pipe = pe.Workflow(name='pipe') + mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') + mod2 = pe.Node(interface=EngineTestInterface(), name='mod2') + pipe.connect([(mod1, mod2, [('output1', 'input1')])]) + pipe.write_graph( + graph2use=graph_type, simple_form=simple, format='dot') + + with open("graph.dot") as f: + graph_str = f.read() + + if simple: + for line in dotfiles[graph_type]: + assert line in graph_str + else: + # if simple=False graph.dot uses longer names + for line in dotfiles[graph_type]: + if graph_type in ["hierarchical", "colored"]: + assert line.replace("mod1 (engine)", "mod1.EngineTestInterface.engine").replace( + "mod2 (engine)", "mod2.EngineTestInterface.engine") in graph_str + else: + assert line.replace( + "mod1 (engine)", "pipe.mod1.EngineTestInterface.engine").replace( + "mod2 (engine)", "pipe.mod2.EngineTestInterface.engine") in graph_str + + # graph_detailed is the same for orig, flat, exec (if no iterables) + # graph_detailed is not created for hierachical or colored + if graph_type not in ["hierarchical", "colored"]: + with open("graph_detailed.dot") as f: + graph_str = f.read() + for line in dotfile_detailed_orig: + assert line in graph_str + + +# examples of dot files used in the following test +dotfile_detailed_iter_exec = [ + 'digraph structs {\n', + 'node [shape=record];\n', + 'pipemod1aIa1 [label="{IN}|{ a1 | engine | mod1.aI }|{OUT|<outoutput1> output1}"];\n', + 'pipemod2a1 [label="{IN|<ininput1> input1}|{ a1 | engine | mod2 }|{OUT}"];\n', + 'pipemod1aIa0 [label="{IN}|{ a0 | engine | mod1.aI }|{OUT|<outoutput1> output1}"];\n', + 'pipemod2a0 [label="{IN|<ininput1> input1}|{ a0 | engine | mod2 }|{OUT}"];\n', + 'pipemod1aIa0:outoutput1:e -> pipemod2a0:ininput1:w;\n', + 'pipemod1aIa1:outoutput1:e -> pipemod2a1:ininput1:w;\n', + '}'] + +dotfile_iter_hierarchical = [ + 'digraph pipe{\n', + ' label="pipe";\n', + ' pipe_mod1[label="mod1 (engine)", shape=box3d,style=filled, color=black, colorscheme=greys7 fillcolor=2];\n', + ' pipe_mod2[label="mod2 (engine)"];\n', + ' pipe_mod1 -> pipe_mod2;\n', + '}'] + +dotfile_iter_colored = [ + 'digraph pipe{\n', + ' label="pipe";\n', + ' pipe_mod1[label="mod1 (engine)", shape=box3d,style=filled, color=black, colorscheme=greys7 fillcolor=2];\n', + ' pipe_mod2[label="mod2 (engine)", style=filled, fillcolor="#FFFFC8"];\n', + ' pipe_mod1 -> pipe_mod2;\n', + '}'] + +dotfiles_iter = { + "orig": dotfile_orig, + "flat": dotfile_orig, + "exec": dotfile_orig, + "hierarchical": dotfile_iter_hierarchical, + "colored": dotfile_iter_colored + } + +dotfiles_detailed_iter = { + "orig": dotfile_detailed_orig, + "flat": dotfile_detailed_orig, + "exec": dotfile_detailed_iter_exec + } + [email protected]("simple", [True, False]) [email protected]("graph_type", ['orig', 'flat', 'exec', 'hierarchical', 'colored']) +def test_write_graph_dotfile_iterables(tmpdir, graph_type, simple): + """ checking dot files for a workflow with iterables""" + tmpdir.chdir() + + pipe = pe.Workflow(name='pipe') + mod1 = pe.Node(interface=EngineTestInterface(), name='mod1') + mod1.iterables = ('input1', [1, 2]) + mod2 = pe.Node(interface=EngineTestInterface(), name='mod2') + pipe.connect([(mod1, mod2, [('output1', 'input1')])]) + pipe.write_graph( + graph2use=graph_type, simple_form=simple, format='dot') + + with open("graph.dot") as f: + graph_str = f.read() + + if simple: + for line in dotfiles_iter[graph_type]: + assert line in graph_str + else: + # if simple=False graph.dot uses longer names + for line in dotfiles_iter[graph_type]: + if graph_type in ["hierarchical", "colored"]: + assert line.replace("mod1 (engine)", "mod1.EngineTestInterface.engine").replace( + "mod2 (engine)", "mod2.EngineTestInterface.engine") in graph_str + else: + assert line.replace( + "mod1 (engine)", "pipe.mod1.EngineTestInterface.engine").replace( + "mod2 (engine)", "pipe.mod2.EngineTestInterface.engine") in graph_str + + # graph_detailed is not created for hierachical or colored + if graph_type not in ["hierarchical", "colored"]: + with open("graph_detailed.dot") as f: + graph_str = f.read() + for line in dotfiles_detailed_iter[graph_type]: + assert line in graph_str + + + def test_io_subclass(): """Ensure any io subclass allows dynamic traits""" from nipype.interfaces.io import IOBase
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 3 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 configparser==5.2.0 coverage==6.2 cycler==0.11.0 decorator==4.4.2 docutils==0.18.1 execnet==1.9.0 funcsigs==1.0.2 future==1.0.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 Jinja2==3.0.3 kiwisolver==1.3.1 lxml==5.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mock==5.2.0 networkx==2.5.1 nibabel==3.2.2 -e git+https://github.com/nipy/nipype.git@69dce12bdf256c3bb0a8b6da9a1d1cdce48b66ec#egg=nipype numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 prov==1.5.0 py==1.11.0 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-env==0.6.2 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 rdflib==5.0.0 requests==2.27.1 scipy==1.5.4 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traits==6.4.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: nipype channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - configparser==5.2.0 - coverage==6.2 - cycler==0.11.0 - decorator==4.4.2 - docutils==0.18.1 - execnet==1.9.0 - funcsigs==1.0.2 - future==1.0.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - lxml==5.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mock==5.2.0 - networkx==2.5.1 - nibabel==3.2.2 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - prov==1.5.0 - py==1.11.0 - pydot==1.4.2 - pydotplus==2.0.2 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-env==0.6.2 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - rdflib==5.0.0 - requests==2.27.1 - scipy==1.5.4 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traits==6.4.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/nipype
[ "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[exec-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[exec-False]" ]
[ "nipype/pipeline/engine/tests/test_engine.py::test_parameterize_dirs_false" ]
[ "nipype/pipeline/engine/tests/test_engine.py::test_2mods[iterables0-expected0]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[hierarchical-True]", "nipype/pipeline/engine/tests/test_engine.py::test_1mod[iterables0-expected0]", "nipype/pipeline/engine/tests/test_engine.py::test_io_subclass", "nipype/pipeline/engine/tests/test_engine.py::test_iterable_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_synchronize_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_3mods[iterables1-expected1-connect1]", "nipype/pipeline/engine/tests/test_engine.py::test_3mods[iterables0-expected0-connect0]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[colored-False]", "nipype/pipeline/engine/tests/test_engine.py::test_itersource_synchronize1_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[hierarchical-False]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[hierarchical-False]", "nipype/pipeline/engine/tests/test_engine.py::test_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_itersource_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[colored-True]", "nipype/pipeline/engine/tests/test_engine.py::test_3mods[iterables2-expected2-connect2]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[colored-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[exec-False]", "nipype/pipeline/engine/tests/test_engine.py::test_old_config", "nipype/pipeline/engine/tests/test_engine.py::test_2mods[iterables1-expected1]", "nipype/pipeline/engine/tests/test_engine.py::test_itersource_synchronize2_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[flat-False]", "nipype/pipeline/engine/tests/test_engine.py::test_1mod[iterables1-expected1]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[colored-False]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[hierarchical-True]", "nipype/pipeline/engine/tests/test_engine.py::test_2mods[iterables2-expected2]", "nipype/pipeline/engine/tests/test_engine.py::test_synchronize_tuples_expansion", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[orig-False]", "nipype/pipeline/engine/tests/test_engine.py::test_mapnode_json", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[exec-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[orig-False]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[orig-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[orig-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[flat-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile_iterables[flat-False]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_dotfile[flat-True]", "nipype/pipeline/engine/tests/test_engine.py::test_write_graph_runs", "nipype/pipeline/engine/tests/test_engine.py::test_deep_nested_write_graph_runs", "nipype/pipeline/engine/tests/test_engine.py::test_serial_input" ]
[]
Apache License 2.0
2,855
949
[ "nipype/pipeline/engine/base.py", "nipype/pipeline/engine/nodes.py", "nipype/pipeline/engine/utils.py" ]
nipy__nipype-2673
69dce12bdf256c3bb0a8b6da9a1d1cdce48b66ec
2018-08-02 16:39:58
24e52aa4229fc3ce7c3e3ac79b3317999d35f1d3
diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 4ec36afe6..cc47de5d4 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -233,15 +233,78 @@ def write_report(node, report_type=None, is_mapnode=False): return +def _identify_collapses(hastraits): + """ Identify traits that will collapse when being set to themselves. + + ``OutputMultiObject``s automatically unwrap a list of length 1 to directly + reference the element of that list. + If that element is itself a list of length 1, then the following will + result in modified values. + + hastraits.trait_set(**hastraits.trait_get()) + + Cloning performs this operation on a copy of the original traited object, + allowing us to identify traits that will be affected. + """ + raw = hastraits.trait_get() + cloned = hastraits.clone_traits().trait_get() + + collapsed = set() + for key in cloned: + orig = raw[key] + new = cloned[key] + # Allow numpy to handle the equality checks, as mixed lists and arrays + # can be problematic. + if isinstance(orig, list) and len(orig) == 1 and ( + not np.array_equal(orig, new) and np.array_equal(orig[0], new)): + collapsed.add(key) + + return collapsed + + +def _uncollapse(indexable, collapsed): + """ Wrap collapsible values in a list to prevent double-collapsing. + + Should be used with _identify_collapses to provide the following + idempotent operation: + + collapsed = _identify_collapses(hastraits) + hastraits.trait_set(**_uncollapse(hastraits.trait_get(), collapsed)) + + NOTE: Modifies object in-place, in addition to returning it. + """ + + for key in indexable: + if key in collapsed: + indexable[key] = [indexable[key]] + return indexable + + +def _protect_collapses(hastraits): + """ A collapse-protected replacement for hastraits.trait_get() + + May be used as follows to provide an idempotent trait_set: + + hastraits.trait_set(**_protect_collapses(hastraits)) + """ + collapsed = _identify_collapses(hastraits) + return _uncollapse(hastraits.trait_get(), collapsed) + + def save_resultfile(result, cwd, name): """Save a result pklz file to ``cwd``""" resultsfile = os.path.join(cwd, 'result_%s.pklz' % name) if result.outputs: try: - outputs = result.outputs.trait_get() + collapsed = _identify_collapses(result.outputs) + outputs = _uncollapse(result.outputs.trait_get(), collapsed) + # Double-protect tosave so that the original, uncollapsed trait + # is saved in the pickle file. Thus, when the loading process + # collapses, the original correct value is loaded. + tosave = _uncollapse(outputs.copy(), collapsed) except AttributeError: - outputs = result.outputs.dictcopy() # outputs was a bunch - result.outputs.set(**modify_paths(outputs, relative=True, basedir=cwd)) + tosave = outputs = result.outputs.dictcopy() # outputs was a bunch + result.outputs.set(**modify_paths(tosave, relative=True, basedir=cwd)) savepkl(resultsfile, result) logger.debug('saved results in %s', resultsfile) @@ -293,7 +356,7 @@ def load_resultfile(path, name): else: if result.outputs: try: - outputs = result.outputs.trait_get() + outputs = _protect_collapses(result.outputs) except AttributeError: outputs = result.outputs.dictcopy() # outputs == Bunch try:
Node de-listifies output lists with a single element ### Summary / Actual behavior A `Select` interface can return a single-element list, when that is the element selected. However, if placed in a `Node`, this will be unwrapped and the output will be the element itself. ### Expected behavior `Node` should not modify the outputs of an interface. ### How to replicate the behavior ```Python from nipype.pipeline import engine as pe from nipype.interfaces import utility as niu select_if = niu.Select(inlist=[[1, 2, 3], [4]], index=1) select_nd = pe.Node(niu.Select(inlist=[[1, 2, 3], [4]], index=1), name='select_nd') ifres = select_if.run() ndres = select_nd.run() assert ifres.outputs.out == [4] assert ndres.outputs.out == 4 ``` ### Platform details: ``` {'pkg_path': '/anaconda3/lib/python3.6/site-packages/nipype', 'commit_source': 'archive substitution', 'commit_hash': '%h', 'nipype_version': '1.1.0', 'sys_version': '3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]', 'sys_executable': '/anaconda3/bin/python', 'sys_platform': 'darwin', 'numpy_version': '1.14.3', 'scipy_version': '1.1.0', 'networkx_version': '2.1', 'nibabel_version': '2.3.0', 'traits_version': '4.6.0'} 1.1.0 ``` ### Execution environment Choose one - My python environment outside container
nipy/nipype
diff --git a/nipype/pipeline/engine/tests/test_nodes.py b/nipype/pipeline/engine/tests/test_nodes.py index 4a04b9476..ea03fe69a 100644 --- a/nipype/pipeline/engine/tests/test_nodes.py +++ b/nipype/pipeline/engine/tests/test_nodes.py @@ -290,3 +290,18 @@ def test_inputs_removal(tmpdir): n1.overwrite = True n1.run() assert not tmpdir.join(n1.name, 'file1.txt').check() + + +def test_outputmultipath_collapse(tmpdir): + """Test an OutputMultiPath whose initial value is ``[[x]]`` to ensure that + it is returned as ``[x]``, regardless of how accessed.""" + select_if = niu.Select(inlist=[[1, 2, 3], [4]], index=1) + select_nd = pe.Node(niu.Select(inlist=[[1, 2, 3], [4]], index=1), + name='select_nd') + + ifres = select_if.run() + ndres = select_nd.run() + + assert ifres.outputs.out == [4] + assert ndres.outputs.out == [4] + assert select_nd.result.outputs.out == [4]
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 codecov==2.1.13 configparser==5.2.0 coverage==6.2 cycler==0.11.0 decorator==4.4.2 docutils==0.18.1 execnet==1.9.0 funcsigs==1.0.2 future==1.0.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isodate==0.6.1 Jinja2==3.0.3 kiwisolver==1.3.1 lxml==5.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mock==5.2.0 networkx==2.5.1 nibabel==3.2.2 -e git+https://github.com/nipy/nipype.git@69dce12bdf256c3bb0a8b6da9a1d1cdce48b66ec#egg=nipype numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 prov==1.5.0 py==1.11.0 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-env==0.6.2 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 rdflib==5.0.0 requests==2.27.1 scipy==1.5.4 simplejson==3.20.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 traits==6.4.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: nipype channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - codecov==2.1.13 - configparser==5.2.0 - coverage==6.2 - cycler==0.11.0 - decorator==4.4.2 - docutils==0.18.1 - execnet==1.9.0 - funcsigs==1.0.2 - future==1.0.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isodate==0.6.1 - jinja2==3.0.3 - kiwisolver==1.3.1 - lxml==5.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mock==5.2.0 - networkx==2.5.1 - nibabel==3.2.2 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - prov==1.5.0 - py==1.11.0 - pydot==1.4.2 - pydotplus==2.0.2 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-env==0.6.2 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - rdflib==5.0.0 - requests==2.27.1 - scipy==1.5.4 - simplejson==3.20.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - traits==6.4.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/nipype
[ "nipype/pipeline/engine/tests/test_nodes.py::test_outputmultipath_collapse" ]
[]
[ "nipype/pipeline/engine/tests/test_nodes.py::test_node_init", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[3-f_exp0]", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[x_inp1-f_exp1]", "nipype/pipeline/engine/tests/test_nodes.py::test_outputs_removal", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[Str-f_exp4]", "nipype/pipeline/engine/tests/test_nodes.py::test_node_get_output", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_check", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_expansion", "nipype/pipeline/engine/tests/test_nodes.py::test_inputs_removal", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[x_inp3-f_exp3]", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[x_inp2-f_exp2]", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_iterfield_type[x_inp5-f_exp5]", "nipype/pipeline/engine/tests/test_nodes.py::test_mapnode_nested", "nipype/pipeline/engine/tests/test_nodes.py::test_node_hash" ]
[]
Apache License 2.0
2,856
922
[ "nipype/pipeline/engine/utils.py" ]
pennmem__cmlreaders-169
355bb312d51b4429738ea491b7cfea4d2fec490c
2018-08-02 17:07:52
355bb312d51b4429738ea491b7cfea4d2fec490c
diff --git a/cmlreaders/base_reader.py b/cmlreaders/base_reader.py index 08f4c49..9a6da5d 100644 --- a/cmlreaders/base_reader.py +++ b/cmlreaders/base_reader.py @@ -148,6 +148,7 @@ class BaseCMLReader(object, metaclass=_MetaReader): Subject code to use; required when we need to determine the protocol experiment session + data_type """ if subject is None: diff --git a/cmlreaders/readers/eeg.py b/cmlreaders/readers/eeg.py index 0c8dd9b..727e617 100644 --- a/cmlreaders/readers/eeg.py +++ b/cmlreaders/readers/eeg.py @@ -102,14 +102,49 @@ class BaseEEGReader(ABC): self.epochs = epochs self.scheme = scheme - self._unique_contacts = np.union1d( - self.scheme["contact_1"], - self.scheme["contact_2"] - ) if self.scheme is not None else None + try: + if self.scheme_type == "contacts": + self._unique_contacts = self.scheme.contact.unique() + elif self.scheme_type == "pairs": + self._unique_contacts = np.union1d( + self.scheme["contact_1"], + self.scheme["contact_2"] + ) + else: + self._unique_contacts = None + except KeyError: + self._unique_contacts = None # in cases where we can't rereference, this will get changed to False self.rereferencing_possible = True + @property + def scheme_type(self) -> Union[str, None]: + """Returns "contacts" when the input scheme is in the form of monopolar + contacts and "pairs" when bipolar. + + Returns + ------- + The scheme type or ``None`` is no scheme was specified. + + Raises + ------ + KeyError + When the passed scheme doesn't include any of the following keys: + ``contact_1``, ``contact_2``, ``contact`` + + """ + if self.scheme is None: + return None + + if "contact_1" in self.scheme and "contact_2" in self.scheme: + return "pairs" + elif "contact" in self.scheme: + return "contacts" + else: + raise KeyError("The passed scheme appears to be neither contacts " + "nor pairs") + def include_contact(self, contact_num: int): """Filter to determine if we need to include a contact number when reading data. @@ -126,7 +161,7 @@ class BaseEEGReader(ABC): def rereference(self, data: np.ndarray, contacts: List[int]) -> Tuple[np.ndarray, List[str]]: - """Attempt to rereference the EEG data using the specified scheme. + """Rereference and/or select a subset of raw channels. Parameters ---------- @@ -154,15 +189,22 @@ class BaseEEGReader(ABC): for i, c in enumerate(contacts) } - c1 = [contact_to_index[c] for c in self.scheme["contact_1"] - if c in contact_to_index] - c2 = [contact_to_index[c] for c in self.scheme["contact_2"] - if c in contact_to_index] + if self.scheme_type == "pairs": + c1 = [contact_to_index[c] for c in self.scheme["contact_1"] + if c in contact_to_index] + c2 = [contact_to_index[c] for c in self.scheme["contact_2"] + if c in contact_to_index] - reref = np.array( - [data[i, c1, :] - data[i, c2, :] for i in range(data.shape[0])] - ) - return reref, self.scheme["label"].tolist() + reref = np.array( + [data[i, c1, :] - data[i, c2, :] for i in range(data.shape[0])] + ) + return reref, self.scheme["label"].tolist() + else: + channels = [contact_to_index[c] for c in self.scheme["contact"]] + subset = np.array( + [data[i, channels, :] for i in range(data.shape[0])] + ) + return subset, self.scheme["label"].tolist() class NumpyEEGReader(BaseEEGReader): @@ -261,7 +303,7 @@ class RamulatorHDF5Reader(BaseEEGReader): passed scheme or if rereferencing is even possible in the first place. """ - if self.rereferencing_possible: + if self.rereferencing_possible or self.scheme_type == "contacts": return BaseEEGReader.rereference(self, data, contacts) with h5py.File(self.filename, 'r') as hfile:
contacts/pairs scheme input I'm still getting a bit of a handle how to use cmlreaders to load eeg vs using PTSA, and I have some questions about the `scheme` input. I see that if you enter a set of pairs, the code will automatically rereference the data, and the `channels` parameter will be defined by the pairs `label` column. However, is there a way to simply load a specific non-bipolar channel? In the PTSA eeg functions, as well as the old matlab eeg_toolbox, you could enter an arbitrary channel number and load that data. Also, if you don't enter a scheme, the `channels` parameter is just a list of incremented channel numbers, instead of the label from the json file. I guess another way of summarizing what I'm asking is, given that you can load pairs.json and pass those as a scheme to `load_eeg`, could we similarly load contacts.json, filter it to any subset, and pass those in as a scheme?
pennmem/cmlreaders
diff --git a/cmlreaders/test/test_eeg.py b/cmlreaders/test/test_eeg.py index a870afa..acfd8fd 100644 --- a/cmlreaders/test/test_eeg.py +++ b/cmlreaders/test/test_eeg.py @@ -24,6 +24,11 @@ from cmlreaders.test.utils import patched_cmlreader from cmlreaders.warnings import MissingChannelsWarning +class DummyReader(BaseEEGReader): + def read(self): + return + + @pytest.fixture def events(): with patched_cmlreader(): @@ -51,18 +56,18 @@ class TestEEGMetaReader: class TestBaseEEGReader: + @staticmethod + def make_reader(scheme=None): + return DummyReader("", np.int16, [(0, None)], scheme=scheme) + @pytest.mark.parametrize("use_scheme", [True, False]) def test_include_contact(self, use_scheme): - class DummyReader(BaseEEGReader): - def read(self): - return - scheme = pd.DataFrame({ "contact_1": list(range(1, 10)), "contact_2": list(range(2, 11)), }) if use_scheme else None - reader = DummyReader("", np.int16, [(0, None)], scheme=scheme) + reader = self.make_reader(scheme) if use_scheme: assert len(reader._unique_contacts) == 10 @@ -73,6 +78,28 @@ class TestBaseEEGReader: else: assert not reader.include_contact(i) + @pytest.mark.parametrize("filename,expected", [ + (resource_filename("cmlreaders.test.data", "contacts.json"), "contacts"), + (resource_filename("cmlreaders.test.data", "pairs.json"), "pairs"), + ("", None) + ]) + def test_scheme_type(self, filename, expected): + if len(filename): + scheme = MontageReader.fromfile(filename, data_type=expected) + else: + scheme = pd.DataFrame({"foo": [1, 2, 3]}) + + reader = self.make_reader(scheme) + + if expected is None: + with pytest.raises(KeyError): + _ = reader.scheme_type # noqa + + reader = self.make_reader() + assert reader.scheme_type is None + else: + assert reader.scheme_type == expected + class TestFileReaders: def get_finder(self, subject, experiment, session, rootdir): @@ -244,12 +271,14 @@ class TestEEGReader: with pytest.raises(ErrorType): reader.load_eeg(events=word_events) - @pytest.mark.parametrize("subject,reref_possible,index,channel", [ - ("R1384J", False, 43, "LS12-LS1"), - ("R1111M", True, 43, "LPOG23-LPOG31"), + @pytest.mark.parametrize("subject,scheme_type,reref_possible,index,channel", [ + ("R1384J", "pairs", False, 43, "LS12-LS1"), + ("R1111M", "pairs", True, 43, "LPOG23-LPOG31"), + ("R1111M", "contacts", True, 43, "LPOG44"), + ("R1286J", "contacts", True, 43, "LJ16") ]) - def test_rereference(self, subject, reref_possible, index, channel, - rhino_root): + def test_rereference(self, subject, scheme_type, reref_possible, index, + channel, rhino_root): reader = CMLReader(subject=subject, experiment='FR1', session=0, rootdir=rhino_root) rate = reader.load("sources")["sample_rate"] @@ -259,22 +288,28 @@ class TestEEGReader: rel_start, rel_stop = 0, 100 expected_samples = int(rate * rel_stop / 1000) - scheme = reader.load('pairs') + scheme = reader.load(scheme_type) load_eeg = partial(reader.load_eeg, events=events, rel_start=rel_start, rel_stop=rel_stop) - if reref_possible: - data = load_eeg() - assert data.shape == (1, 100, expected_samples) + if scheme_type == "pairs": + if reref_possible: + data = load_eeg() + assert data.shape == (1, 100, expected_samples) + data = load_eeg(scheme=scheme) + assert data.shape == (1, 141, expected_samples) + assert data.channels[index] == channel + else: + data_noreref = load_eeg() + data_reref = load_eeg(scheme=scheme) + assert_equal(data_noreref.data, data_reref.data) + assert data_reref.channels[index] == channel + else: data = load_eeg(scheme=scheme) - assert data.shape == (1, 141, expected_samples) + count = 100 if subject == "R1111M" else 124 + assert data.shape == (1, count, expected_samples) assert data.channels[index] == channel - else: - data_noreref = load_eeg() - data_reref = load_eeg(scheme=scheme) - assert_equal(data_noreref.data, data_reref.data) - assert data_reref.channels[index] == channel @pytest.mark.rhino @pytest.mark.parametrize("subject,region_key,region_name,expected_channels,tlen", [
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 2 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@355bb312d51b4429738ea491b7cfea4d2fec490c#egg=cmlreaders codecov==2.1.13 coverage==6.2 cycler==0.11.0 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/contacts.json-contacts]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/pairs.json-pairs]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[-None]" ]
[ "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader_missing_contacts", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1345D-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1363T-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1392N-PAL1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_rereference", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1298E-87-CH88]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1387E-13-CH14]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_read_whole_session[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1387E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1384J-pairs-False-43-LS12-LS1]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-pairs-True-43-LPOG23-LPOG31]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-contacts-True-43-LPOG44]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1286J-contacts-True-43-LJ16]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1384J-ind.region-insula-10-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1288P-ind.region-lateralorbitofrontal-5-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1111M-ind.region-middletemporal-18-100]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-True]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-False]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects0-experiments0]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects1-experiments1]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects2-experiments2]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_channel_discrepancies[R1387E-catFR5-0-120-125]" ]
[ "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[R1389J-sources.json-int16-1641165-1000]", "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[TJ001-TJ001_pyFR_params.txt-int16-None-400.0]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[True]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[False]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_npy_reader", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[TJ001-TJ001_events.mat-expected_basenames0]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[R1389J-task_events.json-expected_basenames1]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[SplitEEGReader-True]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_with_empty_events" ]
[]
null
2,858
1,166
[ "cmlreaders/base_reader.py", "cmlreaders/readers/eeg.py" ]
scieloorg__xylose-158
135018ec4be1a30320d1f59caee922ee4a730f41
2018-08-02 17:20:25
6bb32ebe34da88381518e84790963315b54db9c8
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py index da4d426..f3559c9 100644 --- a/xylose/scielodocument.py +++ b/xylose/scielodocument.py @@ -1,7 +1,6 @@ # encoding: utf-8 import sys from functools import wraps -import warnings import re import unicodedata import datetime @@ -2826,80 +2825,33 @@ class Citation(object): if self.publication_type == 'article': return self.data.get('v35', None) - @property - def analytic_institution_authors(self): - """ - It retrieves the analytic institution authors of a reference, - no matter the publication type of the reference. - It is not desirable to restrict the conditioned return to the - publication type, because some reference standards are very peculiar - and not only articles or books have institution authors. - IT REPLACES analytic_institution - """ - institutions = [] - for institution in self.data.get('v11', []): - institutions.append(html_decode(institution['_'])) - if len(institutions) > 0: - return institutions @property def analytic_institution(self): """ This method retrieves the institutions in the given citation. The citation must be an article or book citation, if it exists. - IT WILL BE DEPRECATED """ - warn_future_deprecation( - 'analytic_institution', - 'analytic_institution_authors', - 'analytic_institution_authors is more suitable name and ' - 'returns the authors independending on publication type' - ) institutions = [] - if self.publication_type in [u'article', u'book']: + if self.publication_type in [u'article', u'book'] and 'v11' in self.data: if 'v11' in self.data: for institution in self.data['v11']: - institutions.append(html_decode(institution['_'])) + institutions.append(html_decode(self.data['v11'][0]['_'])) if len(institutions) > 0: return institutions - @property - def monographic_institution_authors(self): - """ - It retrieves the monographic institution authors of a reference, - no matter the publication type of the reference. - It is not desirable to restrict the conditioned return to the - publication type, because some reference standards are very peculiar - and not only books have institution authors. - IT REPLACES monographic_institution - """ - if 'v30' in self.data: - return - institutions = [] - for institution in self.data.get('v17', []): - institutions.append(html_decode(institution['_'])) - if len(institutions) > 0: - return institutions - @property def monographic_institution(self): """ This method retrieves the institutions in the given citation. The citation must be a book citation, if it exists. - IT WILL BE DEPRECATED """ - warn_future_deprecation( - 'monographic_institution', - 'monographic_institution_authors', - 'monographic_institution_authors is more suitable name and ' - 'returns the authors independending on publication type' - ) institutions = [] if self.publication_type == u'book' and 'v17' in self.data: if 'v17' in self.data: for institution in self.data['v17']: - institutions.append(html_decode(institution['_'])) + institutions.append(html_decode(self.data['v17'][0]['_'])) if len(institutions) > 0: return institutions @@ -3063,13 +3015,40 @@ class Citation(object): ma = self.monographic_authors or [] return aa + ma + @property + def analytic_person_authors(self): + """ + It retrieves the analytic person authors of a reference, + no matter the publication type of the reference. + It is not desirable to restrict the conditioned return to the + publication type, because some reference standards are very peculiar + and not only articles or books have person authors. + IT REPLACES analytic_authors + """ + authors = [] + for author in self.data.get('v10', []): + authordict = {} + if 's' in author: + authordict['surname'] = html_decode(author['s']) + if 'n' in author: + authordict['given_names'] = html_decode(author['n']) + if 's' in author or 'n' in author: + authors.append(authordict) + if len(authors) > 0: + return authors + @property def analytic_authors(self): """ This method retrieves the authors of the given citation. These authors may correspond to an article, book analytic, link or thesis. + IT WILL BE DEPRECATED. Use analytic_person_authors instead """ - + warn_future_deprecation( + 'analytic_authors', + 'analytic_person_authors', + 'analytic_person_authors is more suitable name' + ) authors = [] if 'v10' in self.data: for author in self.data['v10']: @@ -3084,13 +3063,41 @@ class Citation(object): if len(authors) > 0: return authors + @property + def monographic_person_authors(self): + """ + It retrieves the monographic person authors of a reference, + no matter the publication type of the reference. + It is not desirable to restrict the conditioned return to the + publication type, because some reference standards are very peculiar + and not only articles or books have person authors. + IT REPLACES monographic_authors + """ + authors = [] + for author in self.data.get('v16', []): + authordict = {} + if 's' in author: + authordict['surname'] = html_decode(author['s']) + if 'n' in author: + authordict['given_names'] = html_decode(author['n']) + if 's' in author or 'n' in author: + authors.append(authordict) + if len(authors) > 0: + return authors + @property def monographic_authors(self): """ - This method retrieves the authors of the given book citation. These authors may + This method retrieves the authors of the given book citation. + These authors may correspond to a book monography citation. + IT WILL BE DEPRECATED. Use monographic_person_authors instead. """ - + warn_future_deprecation( + 'monographic_authors', + 'monographic_person_authors', + 'monographic_person_authors is more suitable name' + ) authors = [] if 'v16' in self.data: for author in self.data['v16']:
[referências] Trocar o nome dos atributos analytic_authors e monographic_authors - De analytic_authors para analytic_person_authors - De monographic_authors para monographic_person_authors Indicar obsolescência ``` @property def analytic_authors(self): """ This method retrieves the authors of the given citation. These authors may correspond to an article, book analytic, link or thesis. """ authors = [] if 'v10' in self.data: for author in self.data['v10']: authordict = {} if 's' in author: authordict['surname'] = html_decode(author['s']) if 'n' in author: authordict['given_names'] = html_decode(author['n']) if 's' in author or 'n' in author: authors.append(authordict) if len(authors) > 0: return authors @property def monographic_authors(self): """ This method retrieves the authors of the given book citation. These authors may correspond to a book monography citation. """ authors = [] if 'v16' in self.data: for author in self.data['v16']: authordict = {} if 's' in author: authordict['surname'] = html_decode(author['s']) if 'n' in author: authordict['given_names'] = html_decode(author['n']) if 's' in author or 'n' in author: authors.append(authordict) if len(authors) > 0: return authors ```
scieloorg/xylose
diff --git a/tests/test_document.py b/tests/test_document.py index b2b37dd..464098b 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -4136,106 +4136,20 @@ class CitationTest(unittest.TestCase): json_citation['v30'] = [{u'_': u'It is the journal title'}] json_citation['v12'] = [{u'_': u'It is the article title'}] json_citation['v11'] = [{u'_': u'Article Institution'}] - json_citation['v11'] = [ - {u'_': u'Article Institution'}, - {u'_': u'Article Institution 2'}, - ] citation = Citation(json_citation) - self.assertEqual( - citation.analytic_institution, - [u'Article Institution', u'Article Institution 2'] - ) + + self.assertEqual(citation.analytic_institution, [u'Article Institution']) def test_analytic_institution_for_a_book_citation(self): json_citation = {} json_citation['v18'] = [{u'_': u'It is the book title'}] - json_citation['v11'] = [ - {u'_': u'Book Institution'}, - {u'_': u'Book Institution 2'}, - ] - - citation = Citation(json_citation) - - self.assertEqual( - citation.analytic_institution, - [u'Book Institution', u'Book Institution 2'] - ) - - def test_pending_deprecation_warning_of_analytic_institution(self): - citation = Citation({}) - with warnings.catch_warnings(record=True) as w: - items = citation.analytic_institution - assert items is None - assert len(w) == 1 - assert issubclass(w[-1].category, PendingDeprecationWarning) - - def test_pending_deprecation_warning_of_monographic_institution(self): - citation = Citation({}) - with warnings.catch_warnings(record=True) as w: - items = citation.monographic_institution - assert items is None - assert len(w) == 1 - assert issubclass(w[-1].category, PendingDeprecationWarning) + json_citation['v11'] = [{u'_': u'Book Institution'}] - def test_analytic_institution_authors_for_an_article_citation(self): - json_citation = {} - - json_citation['v30'] = [{u'_': u'It is the journal title'}] - json_citation['v12'] = [{u'_': u'It is the article title'}] - json_citation['v11'] = [{u'_': u'Article Institution'}] - json_citation['v11'] = [ - {u'_': u'Article Institution'}, - {u'_': u'Article Institution 2'}, - ] citation = Citation(json_citation) - self.assertEqual( - citation.analytic_institution_authors, - [u'Article Institution', u'Article Institution 2'] - ) - def test_analytic_institution_authors_for_a_book_citation(self): - json_citation = {} - - json_citation['v18'] = [{u'_': u'It is the book title'}] - json_citation['v11'] = [ - {u'_': u'Book Institution'}, - {u'_': u'Book Institution 2'}, - ] - citation = Citation(json_citation) - self.assertEqual( - citation.analytic_institution_authors, - [u'Book Institution', u'Book Institution 2'] - ) - - def test_monographic_institution_authors_for_an_article_citation(self): - json_citation = {} - - json_citation['v30'] = [{u'_': u'It is the journal title'}] - json_citation['v12'] = [{u'_': u'It is the article title'}] - json_citation['v17'] = [ - {u'_': u'Article Institution'}, - {u'_': u'Article Institution 2'}, - ] - citation = Citation(json_citation) - self.assertEqual( - citation.monographic_institution_authors, - None - ) - - def test_monographic_institution_authors_for_a_book_citation(self): - json_citation = {} - - json_citation['v18'] = [{u'_': u'It is the book title'}] - json_citation['v17'] = [ - {u'_': u'Book Institution'}, - ] - citation = Citation(json_citation) - self.assertEqual( - citation.monographic_institution_authors, - [u'Book Institution'] - ) + self.assertEqual(citation.analytic_institution, [u'Book Institution']) def test_thesis_institution(self): json_citation = {} @@ -4386,6 +4300,112 @@ class CitationTest(unittest.TestCase): self.assertEqual(citation.authors, []) + def test_analytic_person_authors(self): + json_citation = {} + + json_citation['v18'] = [{u'_': u'It is the book title'}] + json_citation['v12'] = [{u'_': u'It is the chapter title'}] + json_citation['v10'] = [{u's': u'Sullivan', u'n': u'Mike'}, + {u's': u'Hurricane Carter', u'n': u'Rubin'}, + {u's': u'Maguila Rodrigues', u'n': u'Adilson'}, + {u'n': u'Acelino Popó Freitas'}, + {u's': u'Zé Marreta'}] + + expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'}, + {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'}, + {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'}, + {u'given_names': u'Acelino Popó Freitas'}, + {u'surname': u'Zé Marreta'}] + + citation = Citation(json_citation) + + self.assertEqual(citation.analytic_person_authors, expected) + + def test_without_analytic_person_authors(self): + json_citation = {} + + json_citation['v18'] = [{u'_': u'It is the book title'}] + json_citation['v12'] = [{u'_': u'It is the chapter title'}] + + citation = Citation(json_citation) + + self.assertEqual(citation.analytic_person_authors, None) + + def test_without_analytic_person_authors_but_not_a_book_citation(self): + json_citation = {} + + json_citation['v30'] = [{u'_': u'It is the journal title'}] + json_citation['v12'] = [{u'_': u'It is the article title'}] + json_citation['v10'] = [{u's': u'Sullivan', u'n': u'Mike'}, + {u's': u'Hurricane Carter', u'n': u'Rubin'}, + {u's': u'Maguila Rodrigues', u'n': u'Adilson'}, + {u'n': u'Acelino Popó Freitas'}, + {u's': u'Zé Marreta'}] + + expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'}, + {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'}, + {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'}, + {u'given_names': u'Acelino Popó Freitas'}, + {u'surname': u'Zé Marreta'}] + + citation = Citation(json_citation) + + self.assertEqual(citation.analytic_person_authors, expected) + + def test_monographic_person_authors(self): + json_citation = {} + + json_citation['v18'] = [{u'_': u'It is the book title'}] + json_citation['v16'] = [{u's': u'Sullivan', u'n': u'Mike'}, + {u's': u'Hurricane Carter', u'n': u'Rubin'}, + {u's': u'Maguila Rodrigues', u'n': u'Adilson'}, + {u'n': u'Acelino Popó Freitas'}, + {u's': u'Zé Marreta'}] + + expected = [{u'given_names': u'Mike', u'surname': u'Sullivan'}, + {u'given_names': u'Rubin', u'surname': u'Hurricane Carter'}, + {u'given_names': u'Adilson', u'surname': u'Maguila Rodrigues'}, + {u'given_names': u'Acelino Popó Freitas'}, + {u'surname': u'Zé Marreta'}] + + citation = Citation(json_citation) + + self.assertEqual(citation.monographic_person_authors, expected) + + def test_without_monographic_person_authors(self): + json_citation = {} + + json_citation['v18'] = [{u'_': u'It is the book title'}] + json_citation['v16'] = [] + + citation = Citation(json_citation) + + self.assertEqual(citation.monographic_person_authors, None) + + def test_without_monographic_person_authors_but_not_a_book_citation(self): + json_citation = {} + + json_citation['v30'] = [{u'_': u'It is the journal title'}] + json_citation['v12'] = [{u'_': u'It is the article title'}] + + citation = Citation(json_citation) + + self.assertEqual(citation.monographic_person_authors, None) + + def test_pending_deprecation_warning_of_analytic_authors(self): + citation = Citation({}) + with warnings.catch_warnings(record=True) as w: + assert citation.analytic_authors is None + assert len(w) == 1 + assert issubclass(w[-1].category, PendingDeprecationWarning) + + def test_pending_deprecation_warning_of_monographic_authors(self): + citation = Citation({}) + with warnings.catch_warnings(record=True) as w: + self.assertEqual(citation.monographic_authors, None) + assert len(w) == 1 + assert issubclass(w[-1].category, PendingDeprecationWarning) + def test_monographic_authors(self): json_citation = {}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
1.31
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work legendarium==2.0.6 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/scieloorg/xylose.git@135018ec4be1a30320d1f59caee922ee4a730f41#egg=xylose
name: xylose channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - legendarium==2.0.6 prefix: /opt/conda/envs/xylose
[ "tests/test_document.py::CitationTest::test_analytic_person_authors", "tests/test_document.py::CitationTest::test_monographic_person_authors", "tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_analytic_authors", "tests/test_document.py::CitationTest::test_pending_deprecation_warning_of_monographic_authors", "tests/test_document.py::CitationTest::test_without_analytic_person_authors", "tests/test_document.py::CitationTest::test_without_analytic_person_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_monographic_person_authors", "tests/test_document.py::CitationTest::test_without_monographic_person_authors_but_not_a_book_citation" ]
[]
[ "tests/test_document.py::ToolsTests::test_creative_commons_html_1", "tests/test_document.py::ToolsTests::test_creative_commons_html_2", "tests/test_document.py::ToolsTests::test_creative_commons_html_3", "tests/test_document.py::ToolsTests::test_creative_commons_html_4", "tests/test_document.py::ToolsTests::test_creative_commons_html_5", "tests/test_document.py::ToolsTests::test_creative_commons_html_6", "tests/test_document.py::ToolsTests::test_creative_commons_text_1", "tests/test_document.py::ToolsTests::test_creative_commons_text_2", "tests/test_document.py::ToolsTests::test_creative_commons_text_3", "tests/test_document.py::ToolsTests::test_creative_commons_text_4", "tests/test_document.py::ToolsTests::test_creative_commons_text_5", "tests/test_document.py::ToolsTests::test_creative_commons_text_6", "tests/test_document.py::ToolsTests::test_creative_commons_text_7", "tests/test_document.py::ToolsTests::test_creative_commons_text_8", "tests/test_document.py::ToolsTests::test_get_date_wrong_day", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_year", "tests/test_document.py::ToolsTests::test_get_date_year_day", "tests/test_document.py::ToolsTests::test_get_date_year_month", "tests/test_document.py::ToolsTests::test_get_date_year_month_day", "tests/test_document.py::ToolsTests::test_get_date_year_month_day_31", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined", "tests/test_document.py::ToolsTests::test_get_language_without_iso_format", "tests/test_document.py::IssueTests::test_assets_code_month", "tests/test_document.py::IssueTests::test_collection_acronym", "tests/test_document.py::IssueTests::test_creation_date", "tests/test_document.py::IssueTests::test_creation_date_1", "tests/test_document.py::IssueTests::test_creation_date_2", "tests/test_document.py::IssueTests::test_ctrl_vocabulary", "tests/test_document.py::IssueTests::test_ctrl_vocabulary_out_of_choices", "tests/test_document.py::IssueTests::test_is_ahead", "tests/test_document.py::IssueTests::test_is_ahead_1", "tests/test_document.py::IssueTests::test_is_marked_up", "tests/test_document.py::IssueTests::test_is_press_release_false_1", "tests/test_document.py::IssueTests::test_is_press_release_false_2", "tests/test_document.py::IssueTests::test_is_press_release_true", "tests/test_document.py::IssueTests::test_issue", "tests/test_document.py::IssueTests::test_issue_journal_without_journal_metadata", "tests/test_document.py::IssueTests::test_issue_label", "tests/test_document.py::IssueTests::test_issue_url", "tests/test_document.py::IssueTests::test_order", "tests/test_document.py::IssueTests::test_permission_from_journal", "tests/test_document.py::IssueTests::test_permission_id", "tests/test_document.py::IssueTests::test_permission_t0", "tests/test_document.py::IssueTests::test_permission_t1", "tests/test_document.py::IssueTests::test_permission_t2", "tests/test_document.py::IssueTests::test_permission_t3", "tests/test_document.py::IssueTests::test_permission_t4", "tests/test_document.py::IssueTests::test_permission_text", "tests/test_document.py::IssueTests::test_permission_url", "tests/test_document.py::IssueTests::test_permission_without_v540", "tests/test_document.py::IssueTests::test_permission_without_v540_t", "tests/test_document.py::IssueTests::test_processing_date", "tests/test_document.py::IssueTests::test_processing_date_1", "tests/test_document.py::IssueTests::test_publication_date", "tests/test_document.py::IssueTests::test_sections", "tests/test_document.py::IssueTests::test_standard", "tests/test_document.py::IssueTests::test_standard_out_of_choices", "tests/test_document.py::IssueTests::test_start_end_month", "tests/test_document.py::IssueTests::test_start_end_month_1", "tests/test_document.py::IssueTests::test_start_end_month_2", "tests/test_document.py::IssueTests::test_start_end_month_3", "tests/test_document.py::IssueTests::test_start_end_month_4", "tests/test_document.py::IssueTests::test_start_end_month_5", "tests/test_document.py::IssueTests::test_start_end_month_6", "tests/test_document.py::IssueTests::test_supplement_number", "tests/test_document.py::IssueTests::test_supplement_volume", "tests/test_document.py::IssueTests::test_title_titles", "tests/test_document.py::IssueTests::test_title_titles_1", "tests/test_document.py::IssueTests::test_title_without_titles", "tests/test_document.py::IssueTests::test_total_documents", "tests/test_document.py::IssueTests::test_total_documents_without_data", "tests/test_document.py::IssueTests::test_type_pressrelease", "tests/test_document.py::IssueTests::test_type_regular", "tests/test_document.py::IssueTests::test_type_supplement_1", "tests/test_document.py::IssueTests::test_type_supplement_2", "tests/test_document.py::IssueTests::test_update_date", "tests/test_document.py::IssueTests::test_update_date_1", "tests/test_document.py::IssueTests::test_update_date_2", "tests/test_document.py::IssueTests::test_update_date_3", "tests/test_document.py::IssueTests::test_volume", "tests/test_document.py::IssueTests::test_without_ctrl_vocabulary", "tests/test_document.py::IssueTests::test_without_ctrl_vocabulary_also_in_journal", "tests/test_document.py::IssueTests::test_without_issue", "tests/test_document.py::IssueTests::test_without_processing_date", "tests/test_document.py::IssueTests::test_without_publication_date", "tests/test_document.py::IssueTests::test_without_standard", "tests/test_document.py::IssueTests::test_without_standard_also_in_journal", "tests/test_document.py::IssueTests::test_without_suplement_number", "tests/test_document.py::IssueTests::test_without_supplement_volume", "tests/test_document.py::IssueTests::test_without_volume", "tests/test_document.py::JournalTests::test_abstract_languages", "tests/test_document.py::JournalTests::test_abstract_languages_without_v350", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_print", "tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print", "tests/test_document.py::JournalTests::test_cnn_code", "tests/test_document.py::JournalTests::test_collection_acronym", "tests/test_document.py::JournalTests::test_creation_date", "tests/test_document.py::JournalTests::test_ctrl_vocabulary", "tests/test_document.py::JournalTests::test_ctrl_vocabulary_out_of_choices", "tests/test_document.py::JournalTests::test_current_status", "tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_current_status_some_changes", "tests/test_document.py::JournalTests::test_current_without_v51", "tests/test_document.py::JournalTests::test_editor_address", "tests/test_document.py::JournalTests::test_editor_address_without_data", "tests/test_document.py::JournalTests::test_editor_email", "tests/test_document.py::JournalTests::test_editor_email_without_data", "tests/test_document.py::JournalTests::test_first_number", "tests/test_document.py::JournalTests::test_first_number_1", "tests/test_document.py::JournalTests::test_first_volume", "tests/test_document.py::JournalTests::test_first_volume_1", "tests/test_document.py::JournalTests::test_first_year", "tests/test_document.py::JournalTests::test_first_year_1", "tests/test_document.py::JournalTests::test_first_year_2", "tests/test_document.py::JournalTests::test_first_year_3", "tests/test_document.py::JournalTests::test_first_year_4", "tests/test_document.py::JournalTests::test_in_ahci", "tests/test_document.py::JournalTests::test_in_scie", "tests/test_document.py::JournalTests::test_in_ssci", "tests/test_document.py::JournalTests::test_institutional_url", "tests/test_document.py::JournalTests::test_is_publishing_model_continuous", "tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_with_field_regular", "tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_with_field_undefined", "tests/test_document.py::JournalTests::test_is_publishing_model_continuous_false_without_field", "tests/test_document.py::JournalTests::test_is_publishing_model_continuous_true", "tests/test_document.py::JournalTests::test_is_publishing_model_regular_1", "tests/test_document.py::JournalTests::test_is_publishing_model_regular_2", "tests/test_document.py::JournalTests::test_journal", "tests/test_document.py::JournalTests::test_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_journal_acronym", "tests/test_document.py::JournalTests::test_journal_copyrighter", "tests/test_document.py::JournalTests::test_journal_copyrighter_without_copyright", "tests/test_document.py::JournalTests::test_journal_fulltitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_subtitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_title", "tests/test_document.py::JournalTests::test_journal_mission", "tests/test_document.py::JournalTests::test_journal_mission_without_language_key", "tests/test_document.py::JournalTests::test_journal_mission_without_mission", "tests/test_document.py::JournalTests::test_journal_mission_without_mission_text", "tests/test_document.py::JournalTests::test_journal_mission_without_mission_text_and_language", "tests/test_document.py::JournalTests::test_journal_other_title_without_other_titles", "tests/test_document.py::JournalTests::test_journal_other_titles", "tests/test_document.py::JournalTests::test_journal_publisher_country", "tests/test_document.py::JournalTests::test_journal_publisher_country_not_findable_code", "tests/test_document.py::JournalTests::test_journal_publisher_country_without_country", "tests/test_document.py::JournalTests::test_journal_sponsors", "tests/test_document.py::JournalTests::test_journal_sponsors_with_empty_items", "tests/test_document.py::JournalTests::test_journal_sponsors_without_sponsors", "tests/test_document.py::JournalTests::test_journal_subtitle", "tests/test_document.py::JournalTests::test_journal_title", "tests/test_document.py::JournalTests::test_journal_title_nlm", "tests/test_document.py::JournalTests::test_journal_url", "tests/test_document.py::JournalTests::test_journal_without_subtitle", "tests/test_document.py::JournalTests::test_languages", "tests/test_document.py::JournalTests::test_languages_without_v350", "tests/test_document.py::JournalTests::test_last_cnn_code_1", "tests/test_document.py::JournalTests::test_last_number", "tests/test_document.py::JournalTests::test_last_number_1", "tests/test_document.py::JournalTests::test_last_volume", "tests/test_document.py::JournalTests::test_last_volume_1", "tests/test_document.py::JournalTests::test_last_year", "tests/test_document.py::JournalTests::test_last_year_1", "tests/test_document.py::JournalTests::test_last_year_2", "tests/test_document.py::JournalTests::test_last_year_3", "tests/test_document.py::JournalTests::test_last_year_4", "tests/test_document.py::JournalTests::test_load_issn_with_v435", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35", "tests/test_document.py::JournalTests::test_periodicity", "tests/test_document.py::JournalTests::test_periodicity_in_months", "tests/test_document.py::JournalTests::test_periodicity_in_months_out_of_choices", "tests/test_document.py::JournalTests::test_periodicity_out_of_choices", "tests/test_document.py::JournalTests::test_permission_id", "tests/test_document.py::JournalTests::test_permission_t0", "tests/test_document.py::JournalTests::test_permission_t1", "tests/test_document.py::JournalTests::test_permission_t2", "tests/test_document.py::JournalTests::test_permission_t3", "tests/test_document.py::JournalTests::test_permission_t4", "tests/test_document.py::JournalTests::test_permission_text", "tests/test_document.py::JournalTests::test_permission_url", "tests/test_document.py::JournalTests::test_permission_without_v540", "tests/test_document.py::JournalTests::test_permission_without_v540_t", "tests/test_document.py::JournalTests::test_plevel", "tests/test_document.py::JournalTests::test_plevel_out_of_choices", "tests/test_document.py::JournalTests::test_previous_title", "tests/test_document.py::JournalTests::test_previous_title_without_data", "tests/test_document.py::JournalTests::test_publisher_city", "tests/test_document.py::JournalTests::test_publisher_loc", "tests/test_document.py::JournalTests::test_publisher_name", "tests/test_document.py::JournalTests::test_publisher_state", "tests/test_document.py::JournalTests::test_scielo_issn", "tests/test_document.py::JournalTests::test_secs_code", "tests/test_document.py::JournalTests::test_standard", "tests/test_document.py::JournalTests::test_standard_out_of_choices", "tests/test_document.py::JournalTests::test_status", "tests/test_document.py::JournalTests::test_status_lots_of_changes", "tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_status_lots_of_changes_with_reason", "tests/test_document.py::JournalTests::test_status_some_changes", "tests/test_document.py::JournalTests::test_status_without_v51", "tests/test_document.py::JournalTests::test_subject_areas", "tests/test_document.py::JournalTests::test_subject_descriptors", "tests/test_document.py::JournalTests::test_subject_index_coverage", "tests/test_document.py::JournalTests::test_submission_url", "tests/test_document.py::JournalTests::test_update_date", "tests/test_document.py::JournalTests::test_without_ctrl_vocabulary", "tests/test_document.py::JournalTests::test_without_index_coverage", "tests/test_document.py::JournalTests::test_without_institutional_url", "tests/test_document.py::JournalTests::test_without_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_without_journal_acronym", "tests/test_document.py::JournalTests::test_without_journal_title", "tests/test_document.py::JournalTests::test_without_journal_title_nlm", "tests/test_document.py::JournalTests::test_without_journal_url", "tests/test_document.py::JournalTests::test_without_periodicity", "tests/test_document.py::JournalTests::test_without_periodicity_in_months", "tests/test_document.py::JournalTests::test_without_plevel", "tests/test_document.py::JournalTests::test_without_publisher_city", "tests/test_document.py::JournalTests::test_without_publisher_loc", "tests/test_document.py::JournalTests::test_without_publisher_name", "tests/test_document.py::JournalTests::test_without_publisher_state", "tests/test_document.py::JournalTests::test_without_scielo_domain", "tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690", "tests/test_document.py::JournalTests::test_without_secs_code", "tests/test_document.py::JournalTests::test_without_standard", "tests/test_document.py::JournalTests::test_without_subject_areas", "tests/test_document.py::JournalTests::test_without_subject_descriptors", "tests/test_document.py::JournalTests::test_without_wos_citation_indexes", "tests/test_document.py::JournalTests::test_without_wos_subject_areas", "tests/test_document.py::JournalTests::test_wos_citation_indexes", "tests/test_document.py::JournalTests::test_wos_subject_areas", "tests/test_document.py::ArticleTests::test_abstracts", "tests/test_document.py::ArticleTests::test_abstracts_iso639_2", "tests/test_document.py::ArticleTests::test_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_acceptance_date", "tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliation_with_country_iso_3166", "tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliations", "tests/test_document.py::ArticleTests::test_ahead_publication_date", "tests/test_document.py::ArticleTests::test_article", "tests/test_document.py::ArticleTests::test_author_with_two_affiliations", "tests/test_document.py::ArticleTests::test_author_with_two_role", "tests/test_document.py::ArticleTests::test_author_without_affiliations", "tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names", "tests/test_document.py::ArticleTests::test_authors", "tests/test_document.py::ArticleTests::test_collection_acronym", "tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection", "tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992", "tests/test_document.py::ArticleTests::test_collection_name_brazil", "tests/test_document.py::ArticleTests::test_collection_name_undefined", "tests/test_document.py::ArticleTests::test_corporative_authors", "tests/test_document.py::ArticleTests::test_creation_date", "tests/test_document.py::ArticleTests::test_creation_date_1", "tests/test_document.py::ArticleTests::test_creation_date_2", "tests/test_document.py::ArticleTests::test_data_model_version_html", "tests/test_document.py::ArticleTests::test_data_model_version_html_1", "tests/test_document.py::ArticleTests::test_data_model_version_xml", "tests/test_document.py::ArticleTests::test_document_type", "tests/test_document.py::ArticleTests::test_document_without_issue_metadata", "tests/test_document.py::ArticleTests::test_document_without_journal_metadata", "tests/test_document.py::ArticleTests::test_doi", "tests/test_document.py::ArticleTests::test_doi_clean_1", "tests/test_document.py::ArticleTests::test_doi_clean_2", "tests/test_document.py::ArticleTests::test_doi_v237", "tests/test_document.py::ArticleTests::test_e_location", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_file_code", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2", "tests/test_document.py::ArticleTests::test_first_author", "tests/test_document.py::ArticleTests::test_first_author_without_author", "tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts", "tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts", "tests/test_document.py::ArticleTests::test_html_url", "tests/test_document.py::ArticleTests::test_invalid_document_type", "tests/test_document.py::ArticleTests::test_issue_url", "tests/test_document.py::ArticleTests::test_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_keywords", "tests/test_document.py::ArticleTests::test_keywords_iso639_2", "tests/test_document.py::ArticleTests::test_keywords_with_undefined_language", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_k", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_l", "tests/test_document.py::ArticleTests::test_languages_field_fulltexts", "tests/test_document.py::ArticleTests::test_languages_field_v40", "tests/test_document.py::ArticleTests::test_last_page", "tests/test_document.py::ArticleTests::test_mixed_affiliations_1", "tests/test_document.py::ArticleTests::test_normalized_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE", "tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p", "tests/test_document.py::ArticleTests::test_order", "tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined", "tests/test_document.py::ArticleTests::test_original_html_field_body", "tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_original", "tests/test_document.py::ArticleTests::test_original_section_field_v49", "tests/test_document.py::ArticleTests::test_original_title_subfield_t", "tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_title_without_language_defined", "tests/test_document.py::ArticleTests::test_pdf_url", "tests/test_document.py::ArticleTests::test_processing_date", "tests/test_document.py::ArticleTests::test_processing_date_1", "tests/test_document.py::ArticleTests::test_project_name", "tests/test_document.py::ArticleTests::test_project_sponsors", "tests/test_document.py::ArticleTests::test_publication_contract", "tests/test_document.py::ArticleTests::test_publication_date_with_article_date", "tests/test_document.py::ArticleTests::test_publication_date_without_article_date", "tests/test_document.py::ArticleTests::test_publisher_ahead_id", "tests/test_document.py::ArticleTests::test_publisher_ahead_id_none", "tests/test_document.py::ArticleTests::test_publisher_id", "tests/test_document.py::ArticleTests::test_receive_date", "tests/test_document.py::ArticleTests::test_review_date", "tests/test_document.py::ArticleTests::test_section_code_field_v49", "tests/test_document.py::ArticleTests::test_section_code_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_code_without_field_v49", "tests/test_document.py::ArticleTests::test_section_field_v49", "tests/test_document.py::ArticleTests::test_section_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_without_field_section", "tests/test_document.py::ArticleTests::test_section_without_field_v49", "tests/test_document.py::ArticleTests::test_start_page", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_start_page_sec", "tests/test_document.py::ArticleTests::test_start_page_sec_0", "tests/test_document.py::ArticleTests::test_start_page_sec_0_loaded_through_xml", "tests/test_document.py::ArticleTests::test_start_page_sec_loaded_through_xml", "tests/test_document.py::ArticleTests::test_subject_areas", "tests/test_document.py::ArticleTests::test_thesis_degree", "tests/test_document.py::ArticleTests::test_thesis_organization", "tests/test_document.py::ArticleTests::test_thesis_organization_and_division", "tests/test_document.py::ArticleTests::test_thesis_organization_without_name", "tests/test_document.py::ArticleTests::test_translated_abstracts", "tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2", "tests/test_document.py::ArticleTests::test_translated_htmls_field_body", "tests/test_document.py::ArticleTests::test_translated_section_field_v49", "tests/test_document.py::ArticleTests::test_translated_titles", "tests/test_document.py::ArticleTests::test_translated_titles_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles_without_v12", "tests/test_document.py::ArticleTests::test_update_date", "tests/test_document.py::ArticleTests::test_update_date_1", "tests/test_document.py::ArticleTests::test_update_date_2", "tests/test_document.py::ArticleTests::test_update_date_3", "tests/test_document.py::ArticleTests::test_whitwout_acceptance_date", "tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date", "tests/test_document.py::ArticleTests::test_whitwout_receive_date", "tests/test_document.py::ArticleTests::test_whitwout_review_date", "tests/test_document.py::ArticleTests::test_without_affiliations", "tests/test_document.py::ArticleTests::test_without_authors", "tests/test_document.py::ArticleTests::test_without_citations", "tests/test_document.py::ArticleTests::test_without_collection_acronym", "tests/test_document.py::ArticleTests::test_without_corporative_authors", "tests/test_document.py::ArticleTests::test_without_document_type", "tests/test_document.py::ArticleTests::test_without_doi", "tests/test_document.py::ArticleTests::test_without_e_location", "tests/test_document.py::ArticleTests::test_without_html_url", "tests/test_document.py::ArticleTests::test_without_issue_url", "tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_without_keywords", "tests/test_document.py::ArticleTests::test_without_last_page", "tests/test_document.py::ArticleTests::test_without_normalized_affiliations", "tests/test_document.py::ArticleTests::test_without_order", "tests/test_document.py::ArticleTests::test_without_original_abstract", "tests/test_document.py::ArticleTests::test_without_original_title", "tests/test_document.py::ArticleTests::test_without_pages", "tests/test_document.py::ArticleTests::test_without_pdf_url", "tests/test_document.py::ArticleTests::test_without_processing_date", "tests/test_document.py::ArticleTests::test_without_project_name", "tests/test_document.py::ArticleTests::test_without_project_sponsor", "tests/test_document.py::ArticleTests::test_without_publication_contract", "tests/test_document.py::ArticleTests::test_without_publication_date", "tests/test_document.py::ArticleTests::test_without_publisher_id", "tests/test_document.py::ArticleTests::test_without_scielo_domain", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690", "tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690", "tests/test_document.py::ArticleTests::test_without_start_page", "tests/test_document.py::ArticleTests::test_without_subject_areas", "tests/test_document.py::ArticleTests::test_without_thesis_degree", "tests/test_document.py::ArticleTests::test_without_thesis_organization", "tests/test_document.py::ArticleTests::test_without_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_without_wos_subject_areas", "tests/test_document.py::ArticleTests::test_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_wos_subject_areas", "tests/test_document.py::CitationTest::test_a_link_access_date", "tests/test_document.py::CitationTest::test_a_link_access_date_absent_v65", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation", "tests/test_document.py::CitationTest::test_article_title", "tests/test_document.py::CitationTest::test_article_without_title", "tests/test_document.py::CitationTest::test_authors_article", "tests/test_document.py::CitationTest::test_authors_book", "tests/test_document.py::CitationTest::test_authors_link", "tests/test_document.py::CitationTest::test_authors_thesis", "tests/test_document.py::CitationTest::test_book_chapter_title", "tests/test_document.py::CitationTest::test_book_edition", "tests/test_document.py::CitationTest::test_book_volume", "tests/test_document.py::CitationTest::test_book_without_chapter_title", "tests/test_document.py::CitationTest::test_citation_sample_congress", "tests/test_document.py::CitationTest::test_citation_sample_link", "tests/test_document.py::CitationTest::test_citation_sample_link_without_comment", "tests/test_document.py::CitationTest::test_conference_edition", "tests/test_document.py::CitationTest::test_conference_name", "tests/test_document.py::CitationTest::test_conference_sponsor", "tests/test_document.py::CitationTest::test_conference_without_name", "tests/test_document.py::CitationTest::test_conference_without_sponsor", "tests/test_document.py::CitationTest::test_date", "tests/test_document.py::CitationTest::test_doi", "tests/test_document.py::CitationTest::test_editor", "tests/test_document.py::CitationTest::test_elocation_14", "tests/test_document.py::CitationTest::test_elocation_514", "tests/test_document.py::CitationTest::test_end_page_14", "tests/test_document.py::CitationTest::test_end_page_514", "tests/test_document.py::CitationTest::test_end_page_withdout_data", "tests/test_document.py::CitationTest::test_first_author_article", "tests/test_document.py::CitationTest::test_first_author_book", "tests/test_document.py::CitationTest::test_first_author_link", "tests/test_document.py::CitationTest::test_first_author_thesis", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_index_number", "tests/test_document.py::CitationTest::test_institutions_all_fields", "tests/test_document.py::CitationTest::test_institutions_v11", "tests/test_document.py::CitationTest::test_institutions_v17", "tests/test_document.py::CitationTest::test_institutions_v29", "tests/test_document.py::CitationTest::test_institutions_v50", "tests/test_document.py::CitationTest::test_institutions_v58", "tests/test_document.py::CitationTest::test_invalid_edition", "tests/test_document.py::CitationTest::test_isbn", "tests/test_document.py::CitationTest::test_isbn_but_not_a_book", "tests/test_document.py::CitationTest::test_issn", "tests/test_document.py::CitationTest::test_issn_but_not_an_article", "tests/test_document.py::CitationTest::test_issue_part", "tests/test_document.py::CitationTest::test_issue_title", "tests/test_document.py::CitationTest::test_journal_issue", "tests/test_document.py::CitationTest::test_journal_volume", "tests/test_document.py::CitationTest::test_link", "tests/test_document.py::CitationTest::test_link_title", "tests/test_document.py::CitationTest::test_link_without_title", "tests/test_document.py::CitationTest::test_mixed_citation_1", "tests/test_document.py::CitationTest::test_mixed_citation_10", "tests/test_document.py::CitationTest::test_mixed_citation_11", "tests/test_document.py::CitationTest::test_mixed_citation_12", "tests/test_document.py::CitationTest::test_mixed_citation_13", "tests/test_document.py::CitationTest::test_mixed_citation_14", "tests/test_document.py::CitationTest::test_mixed_citation_15", "tests/test_document.py::CitationTest::test_mixed_citation_16", "tests/test_document.py::CitationTest::test_mixed_citation_17", "tests/test_document.py::CitationTest::test_mixed_citation_18", "tests/test_document.py::CitationTest::test_mixed_citation_19", "tests/test_document.py::CitationTest::test_mixed_citation_2", "tests/test_document.py::CitationTest::test_mixed_citation_3", "tests/test_document.py::CitationTest::test_mixed_citation_4", "tests/test_document.py::CitationTest::test_mixed_citation_5", "tests/test_document.py::CitationTest::test_mixed_citation_6", "tests/test_document.py::CitationTest::test_mixed_citation_7", "tests/test_document.py::CitationTest::test_mixed_citation_8", "tests/test_document.py::CitationTest::test_mixed_citation_9", "tests/test_document.py::CitationTest::test_mixed_citation_without_data", "tests/test_document.py::CitationTest::test_monographic_authors", "tests/test_document.py::CitationTest::test_monographic_first_author", "tests/test_document.py::CitationTest::test_pages_14", "tests/test_document.py::CitationTest::test_pages_514", "tests/test_document.py::CitationTest::test_pages_withdout_data", "tests/test_document.py::CitationTest::test_publication_type_article", "tests/test_document.py::CitationTest::test_publication_type_book", "tests/test_document.py::CitationTest::test_publication_type_book_chapter", "tests/test_document.py::CitationTest::test_publication_type_conference", "tests/test_document.py::CitationTest::test_publication_type_link", "tests/test_document.py::CitationTest::test_publication_type_thesis", "tests/test_document.py::CitationTest::test_publication_type_undefined", "tests/test_document.py::CitationTest::test_publisher", "tests/test_document.py::CitationTest::test_publisher_address", "tests/test_document.py::CitationTest::test_publisher_address_without_e", "tests/test_document.py::CitationTest::test_series_book", "tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation", "tests/test_document.py::CitationTest::test_series_conference", "tests/test_document.py::CitationTest::test_series_journal", "tests/test_document.py::CitationTest::test_source_book_title", "tests/test_document.py::CitationTest::test_source_journal", "tests/test_document.py::CitationTest::test_source_journal_without_journal_title", "tests/test_document.py::CitationTest::test_sponsor", "tests/test_document.py::CitationTest::test_start_page_14", "tests/test_document.py::CitationTest::test_start_page_514", "tests/test_document.py::CitationTest::test_start_page_withdout_data", "tests/test_document.py::CitationTest::test_thesis_institution", "tests/test_document.py::CitationTest::test_thesis_title", "tests/test_document.py::CitationTest::test_thesis_without_title", "tests/test_document.py::CitationTest::test_title_when_article_citation", "tests/test_document.py::CitationTest::test_title_when_conference_citation", "tests/test_document.py::CitationTest::test_title_when_link_citation", "tests/test_document.py::CitationTest::test_title_when_thesis_citation", "tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book", "tests/test_document.py::CitationTest::test_without_analytic_institution", "tests/test_document.py::CitationTest::test_without_authors", "tests/test_document.py::CitationTest::test_without_date", "tests/test_document.py::CitationTest::test_without_doi", "tests/test_document.py::CitationTest::test_without_edition", "tests/test_document.py::CitationTest::test_without_editor", "tests/test_document.py::CitationTest::test_without_first_author", "tests/test_document.py::CitationTest::test_without_index_number", "tests/test_document.py::CitationTest::test_without_institutions", "tests/test_document.py::CitationTest::test_without_issue", "tests/test_document.py::CitationTest::test_without_issue_part", "tests/test_document.py::CitationTest::test_without_issue_title", "tests/test_document.py::CitationTest::test_without_link", "tests/test_document.py::CitationTest::test_without_monographic_authors", "tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_publisher", "tests/test_document.py::CitationTest::test_without_publisher_address", "tests/test_document.py::CitationTest::test_without_series", "tests/test_document.py::CitationTest::test_without_sponsor", "tests/test_document.py::CitationTest::test_without_thesis_institution", "tests/test_document.py::CitationTest::test_without_volume" ]
[]
BSD 2-Clause "Simplified" License
2,859
1,613
[ "xylose/scielodocument.py" ]
pennmem__cmlreaders-170
355bb312d51b4429738ea491b7cfea4d2fec490c
2018-08-02 18:12:22
355bb312d51b4429738ea491b7cfea4d2fec490c
diff --git a/cmlreaders/cmlreader.py b/cmlreaders/cmlreader.py index ecd5506..b450da2 100644 --- a/cmlreaders/cmlreader.py +++ b/cmlreaders/cmlreader.py @@ -113,6 +113,15 @@ class CMLReader(object): setattr(self, "_" + which, value) return value + @staticmethod + def get_data_index(protocol: str = "all", + rootdir: Optional[str] = None) -> pd.DataFrame: + """Shortcut for the global :func:`get_data_index` function to only + need to import :class:`CMLReader`. + + """ + return get_data_index(protocol, rootdir) + @property def localization(self) -> int: """Determine the localization number."""
Make get_data_index a static method of CMLReader Ideally, the only entry point for `cmlreaders` should be the `CMLReader` class itself. Right now, to get the data index, one also needs to import the `get_data_index` function. This could be simplified by making this a classmethod: ```python >>> from cmlreaders import CMLReader >>> df = CMLReader.get_data_index("r1") ``` or maybe for less typing simply ```python df = CMLReader.index("r1") ```
pennmem/cmlreaders
diff --git a/cmlreaders/test/test_cmlreader.py b/cmlreaders/test/test_cmlreader.py index 05066bd..1ba646e 100644 --- a/cmlreaders/test/test_cmlreader.py +++ b/cmlreaders/test/test_cmlreader.py @@ -7,13 +7,25 @@ import pandas as pd from pkg_resources import resource_filename import pytest -from cmlreaders import CMLReader, exc +from cmlreaders import CMLReader, exc, get_data_index +from cmlreaders.path_finder import PathFinder from cmlreaders.test.utils import patched_cmlreader datafile = functools.partial(resource_filename, 'cmlreaders.test.data') class TestCMLReader: + @pytest.mark.parametrize("protocol", ["all", "r1"]) + def test_get_data_index(self, protocol): + if protocol is "all": + path = resource_filename("cmlreaders.test.data", "r1.json") + else: + path = resource_filename("cmlreaders.test.data", protocol + ".json") + + with patch.object(PathFinder, "find", return_value=path): + ix = CMLReader.get_data_index(protocol) + assert all(ix == get_data_index(protocol)) + @pytest.mark.parametrize("subject,experiment,session,localization,montage", [ ("R1278E", "catFR1", 0, 0, 1), ("R1278E", "catFR1", None, 0, 1),
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@355bb312d51b4429738ea491b7cfea4d2fec490c#egg=cmlreaders codecov==2.1.13 coverage==6.2 cycler==0.11.0 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_data_index[all]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_data_index[r1]" ]
[ "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[voxel_coordinates-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[voxel_coordinates-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_excluded_leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_excluded_leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[jacksheet-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[jacksheet-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[good_leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[good_leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[leads-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[leads-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_coordinates-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_coordinates-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[prior_stim_results-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[prior_stim_results-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[target_selection_table-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[target_selection_table-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_categories-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[electrode_categories-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[classifier_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[session_summary-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[session_summary-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[pairs-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[pairs-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[contacts-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[contacts-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[localization-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[localization-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[baseline_classifier-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[baseline_classifier-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[used_classifier-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[used_classifier-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[all_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[all_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[task_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[task_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_events-R1405E-FR1-1-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_from_rhino[math_events-LTP093-ltpFR2-0-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[baseline_classifier.zip]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[used_classifier.zip]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[baseline_classifier]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[used_classifier]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_ps_events[R1354E-PS4_FR-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_ps_events[R1111M-PS2-0]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_ps_events[R1025P-PS1-0]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[True-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[True-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[False-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_rhino[False-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_missing[contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories_missing[pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[R1111M-FR1-4]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects2-experiments2-5]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects3-None-22]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[subjects4-experiments4-6]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[None-experiments5-79]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[R1289C-experiments6-3]" ]
[ "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-catFR1-0-0-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-catFR1-None-0-1]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-PAL1-None-2-2]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-PAL3-2-2-2]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-TH1-0-0-0]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[R1278E-TH1-None-0-0]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_determine_localization_or_montage[LTP093-ltpFR2-0-None-None]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[voxel_coordinates.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[classifier_excluded_leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[jacksheet.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[good_leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[leads.txt]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[electrode_coordinates.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[prior_stim_results.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[target_selection_table.csv]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[pairs.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[contacts.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[localization.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[all_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[math_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load[task_events.json]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[voxel_coordinates]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[classifier_excluded_leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[jacksheet]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[good_leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[leads]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[electrode_coordinates]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[prior_stim_results]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[target_selection_table]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[pairs]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[contacts]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[localization]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[all_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[math_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_get_reader[task_events]", "cmlreaders/test/test_cmlreader.py::TestCMLReader::test_load_unimplemented", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[True-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[True-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[False-contacts]", "cmlreaders/test/test_cmlreader.py::TestLoadMontage::test_read_categories[False-pairs]", "cmlreaders/test/test_cmlreader.py::TestLoadAggregate::test_load_events[None-None-None]" ]
[]
null
2,860
200
[ "cmlreaders/cmlreader.py" ]
sigmavirus24__github3.py-879
87af5a1d26597d7cf1a843199a1b5a2449cd8069
2018-08-02 23:08:43
b8e7aa8eb221cd1eec7a8bc002b75de8098dc77a
sigmavirus24: You're right. This method, at this point in time is not going to be correct or conducive to the right behaviour for the future of the library. Here's what I think we should do: 1. Deprecate `Issue.assign`. It only accepts 1 user and that is outdated and likely going to be confusing going forward. 1. Add `add_assignees` (or something along those lines) that does the right thing (accepts a list of usernames/User objects) and calls `edit` appropriately. 1. Add `remove_assignees` which is the inverse of `add_assignees`. Does that make sense? jacquerie: > Does that make sense? Absolutely! I just pushed three commits that implement the three steps that you described.
diff --git a/src/github3/issues/issue.py b/src/github3/issues/issue.py index 15b7632a..cdf673fc 100644 --- a/src/github3/issues/issue.py +++ b/src/github3/issues/issue.py @@ -2,6 +2,7 @@ """Module containing the Issue logic.""" from __future__ import unicode_literals +import warnings from json import dumps from uritemplate import URITemplate @@ -67,6 +68,27 @@ class _Issue(models.GitHubCore): n=self.number, class_name=self.class_name, ) + @requires_auth + def add_assignees(self, users): + """Assign ``users`` to this issue. + + This is a shortcut for :meth:`~github3.issues.issue.Issue.edit`. + + :param users: + users or usernames to assign this issue to + :type users: + list of :class:`~github3.users.User` + :type users: + list of str + :returns: + True if successful, False otherwise + :rtype: + bool + """ + usernames = {getattr(user, 'login', user) for user in users} + assignees = list({a.login for a in self.assignees} | usernames) + return self.edit(assignees=assignees) + @requires_auth def add_labels(self, *args): """Add labels to this issue. @@ -86,6 +108,10 @@ class _Issue(models.GitHubCore): def assign(self, username): """Assign user ``username`` to this issue. + .. deprecated:: 1.2.0 + + Use :meth:`github3.issues.issue.Issue.add_assignees` instead. + This is a short cut for :meth:`~github3.issues.issue.Issue.edit`. :param str username: @@ -95,6 +121,9 @@ class _Issue(models.GitHubCore): :rtype: bool """ + warnings.warn( + 'This method is deprecated. Please use ``add_assignees`` ' + 'instead.', DeprecationWarning, stacklevel=2) if not username: return False number = self.milestone.number if self.milestone else None @@ -300,6 +329,27 @@ class _Issue(models.GitHubCore): json = self._json(self._get(pull_request_url), 200) return self._instance_or_null(pulls.PullRequest, json) + @requires_auth + def remove_assignees(self, users): + """Unassign ``users`` from this issue. + + This is a shortcut for :meth:`~github3.issues.issue.Issue.edit`. + + :param users: + users or usernames to unassign this issue from + :type users: + list of :class:`~github3.users.User` + :type users: + list of str + :returns: + True if successful, False otherwise + :rtype: + bool + """ + usernames = {getattr(user, 'login', user) for user in users} + assignees = list({a.login for a in self.assignees} - usernames) + return self.edit(assignees=assignees) + @requires_auth def remove_label(self, name): """Remove label ``name`` from this issue.
No way to unassign an issue There seems to be an assign function, but not an unassign method for Issue <bountysource-plugin> --- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/46179344-no-way-to-unassign-an-issue?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F183477&utm_medium=issues&utm_source=github). </bountysource-plugin>
sigmavirus24/github3.py
diff --git a/tests/cassettes/Issue_add_assignees.json b/tests/cassettes/Issue_add_assignees.json new file mode 100644 index 00000000..418ba17b --- /dev/null +++ b/tests/cassettes/Issue_add_assignees.json @@ -0,0 +1,1 @@ +{"http_interactions": [{"request": {"body": {"string": "", "encoding": "utf-8"}, "headers": {"Accept-Encoding": ["gzip, deflate"], "Accept": ["application/vnd.github.v3.full+json"], "User-Agent": ["github3.py/1.1.0"], "Accept-Charset": ["utf-8"], "Connection": ["keep-alive"], "Content-Type": ["application/json"], "Authorization": ["token <AUTH_TOKEN>"]}, "method": "GET", "uri": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA8VW/W/iNhj+V7xIm7aqISSkcGSBatPupP1Au9Poelo5IScx4GtiR/6Apaj/+147gQNEez2u0yQiiP2+j5/36zFrR4vciZyFUqWMPA+XtDWnaqGTVsoLT5CSS0/SeYGXVGgZhF6922mVlUel1ER6Pd93zh1rShUX1fR0SMDJcUJy+Q0YO7S8GmztMVyQRwCHmArC1GvBb+AAmSxfEbcGA9SFKvKDVOxU50V1oZkTBZ2Li34Y9v1zh/GMTM2aM/rtpvvnh6uH7PamGj3c+Nfj9+3r8dsBHMt0kRDhRFDZc0dRlROwv+JohSukONIMSzibIcyQ7QFw0dI4rJ2czykD64IQVWA21/e0wrBvjux1g/ZFp7NP4n33rw9XefopDUaffvFHDyNDAC+xwuKwCeyibDcNak5MOVOQd9ur2mvwL5eDEDDmokGx0RqKz3W6QZPeIevn839oPeN5zleAc0h8f6iOHOVtXYFn/Zuy+akw4Lr2uFoQyCCEZRp/TuWXuv4YLeu2hpmXCprGAEkogSDZ11NrHIHYigGntdUWi6gTmQpaKsrZCZnbcwc4LuaY0Qd8Ihy4S0Cxavb1QVo3cH+JGhzLd+239kpBlzitTHoESQldQsZPxTwAAEhVlWagb8zIQv6pIlOcFWZsZziX5HEjwk5099FWXBlzXhIG5jlP7wlMlDWFSbVKQMCA6Tz//C5r54LmRCrOtvtbyYwCkGNBADubYgX4Qdvvue2u63fG/kUU9KLQ/xvO02W2Z/PGbcMnGAedqN2P/L6xSXMuG5iGhVYLLqZAjqfUtoIRsOurt2Cc8KyamsGGpbgcjmFMCJKEFNJoW0KMqjX6NtMsNc7nKNEKMa7M3lb9CgKHZGjGBfrdqGDslcMJm7B4IeAboG8xUxYTp/dILais1fISxVIJzubDGKOFILPBZHv/rlarVsI1U5XkWqTEKltzz4Zdv9fvhKHLuAtK7Crubri4mLnW6lKrYpriosRQlUGZa1DjH+D1Z7teq+VACSBExPfBO/9NJ+z1tgYFyaguBvV529WayaC+eCYOEiQHxozXOjVxhn9wCZlBNW/E4VJQ38UeHsZeEye6haymKSlVbUSJREuK0Qvj/1+C+nWnCiaYVpzYskKRN02kyD+mcV+vg0z3TNiTbXMsz0+ldpd+qyH8ulwFcIUn3m1Xt+64odkwj+u65uvJiM7O7o4F9fHHzf/R/2Qenp0Fs7k/B2ZlbwZ+Ojt7Ku13u3n/QhhH2/qbubVsUbxjVfmslElV6/Xjv5qtd9IADAAA", "encoding": "utf-8"}, "headers": {"X-XSS-Protection": ["1; mode=block"], "Content-Security-Policy": ["default-src 'none'"], "Access-Control-Expose-Headers": ["ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval"], "Transfer-Encoding": ["chunked"], "Last-Modified": ["Thu, 02 Aug 2018 23:09:19 GMT"], "Access-Control-Allow-Origin": ["*"], "X-Frame-Options": ["deny"], "Status": ["200 OK"], "X-GitHub-Request-Id": ["A2E6:3FAE:2C29574:52316EC:5B6404DA"], "ETag": ["W/\"5b4dd8dd9fd32bdbfc73353b8813f599\""], "Date": ["Fri, 03 Aug 2018 07:31:38 GMT"], "X-RateLimit-Remaining": ["4999"], "Strict-Transport-Security": ["max-age=31536000; includeSubdomains; preload"], "Server": ["GitHub.com"], "X-OAuth-Scopes": ["public_repo, read:user"], "X-GitHub-Media-Type": ["github.v3; param=full; format=json"], "X-Content-Type-Options": ["nosniff"], "Content-Encoding": ["gzip"], "X-Runtime-rack": ["0.104248"], "Vary": ["Accept, Authorization, Cookie, X-GitHub-OTP"], "X-RateLimit-Limit": ["5000"], "Cache-Control": ["private, max-age=60, s-maxage=60"], "Referrer-Policy": ["origin-when-cross-origin, strict-origin-when-cross-origin"], "Content-Type": ["application/json; charset=utf-8"], "X-Accepted-OAuth-Scopes": ["repo"], "X-RateLimit-Reset": ["1533285098"]}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "recorded_at": "2018-08-03T07:31:38"}, {"request": {"body": {"string": "{\"assignees\": [\"jacquerie\"]}", "encoding": "utf-8"}, "headers": {"Content-Length": ["28"], "Accept-Encoding": ["gzip, deflate"], "Accept": ["application/vnd.github.v3.full+json"], "User-Agent": ["github3.py/1.1.0"], "Accept-Charset": ["utf-8"], "Connection": ["keep-alive"], "Content-Type": ["application/json"], "Authorization": ["token <AUTH_TOKEN>"]}, "method": "PATCH", "uri": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA+1YbW/iRhD+K66lVm0UY4wdSCgQXdWrdB8gdyppTg0ntLYX2MTe9e0L1EH57zdr82IsSMJL1Q89CQSsZ559dnae2R3mpuKR2TQnUiaiadsoIZUxkRPlVwIW2xwnTNiCjGM0JVyJmmfnT91KktpECIWF3XAc89zMTIlkPB0eDgk4EfJxJI7AKNCyc7C5TVGMnwEc1hRjKk8Fv4QDZDw9IW4OBqgTGUelUBR25037QkKzWXMvLq4878o5NykL8VCPmd3fb+t/fu49hXe3affp1rnpf6re9N+3YVqqYh9zswk7e25KIiMM9j1mzFBqSGYoigTMTQ1EjSwHwEUJ7TA3IzYmFKxjjGWM6Fg9khTBcz1lo16rXrjuJolP9b8+96LgIah1H9453aeuJoCmSCJeToJsUFQXCapnDBiVEPcsV5W9wL+etj3AGPMFSrZaTfGlTNdowi6zfjn+ZesRiyI2A5wy8U1RbZnKXrkCz/w7oeNDYcB1bjM5wRBBWJZO/DERr2X9NlqZ2xw0LyQkjQYSsAUch/tTWzgCsRkFTvOstmSIyhcBJ4kkjB4QuQ13gGN8jCh5QgfCgbsAlKya7b/IzA3c31INtsU795vbCSdTFKQ6PBwHmEwh4odilgAAUqaJFvStlizEn0g8RGGsZTtCkcDPyyJsNu+/ZDsutTlLMAXziAWPGBSVmYJSs0qAwWCt/QcUfFWYE10XtPjcS6d2Wd0u+67X7X/wuu/ar8m+tlP2OfwRqi/yfVnxRcu91L5yPFzpZYhjVL7GOkrha5jTqbuAWSwMhyh7DbWvqtee+yt67XsaNRe5bJSCNyl5qU8BYv6u0K2X3LwQl+UFxzgEeK+zuAzxXaG7O4ty0P+vCoUDNiYRFpJROEOpiqJ1lwIXd/jBMZy/4RBJCGat6jSsat1y3L5z0aw1mp7zN2SpSsINm0urCi+3X200XafpXmmbIGJiAZPPgpScMD6EAsECkl2XYILeTe89GPssTIf6KIShVtLpw1USGwLjWOj7v4/1zX/RA4wUDbTzueEraVAm9bNVhxBjmCQ0RowbH3Sn0LKTzoAOaGvC4ROg7xCVGSYKHg05ISLvKK6NlpCc0XGnhYwJx6P2YNWjzmazis8Ulalgigc4u/0velGv7jSuXM+zKLOgW7Eks5ZcLEStzOpayXgYoDhBcHNpJ5GCjuUn+PlrNp53FG3JgRDmP9b+cC5dr9FYGcQ4JCpu5/OtRnMm7bw5G5gGxxEwpiyvHwOz85EJiIyR8zYYNE7yh5aNOi17sU7jDqIaBDiRuRHBwpgSZLxx/f/Jon4r7IJeTKXlZ9sKm7xMIon/0Yl7ugzS2TOgO9NmW5x3hbZIv7IgfFquHLjCu1VMVyvPuI5+oN+WZemPnSs6O7vftqgvPy//s/lX9PCiFvTDTR3okQ0N/HJ2tivs98W4v7KMrWl9NLdKtin2tl1ZV0o/zevx8zchJQr2JBMAAA==", "encoding": "utf-8"}, "headers": {"X-XSS-Protection": ["1; mode=block"], "Content-Security-Policy": ["default-src 'none'"], "Access-Control-Expose-Headers": ["ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval"], "Transfer-Encoding": ["chunked"], "Access-Control-Allow-Origin": ["*"], "X-Frame-Options": ["deny"], "Status": ["200 OK"], "X-GitHub-Request-Id": ["A2E6:3FAE:2C295A6:5231732:5B6404DA"], "ETag": ["W/\"b4505c5c6261cbcfd05fc36ec2685139\""], "Date": ["Fri, 03 Aug 2018 07:31:39 GMT"], "X-RateLimit-Remaining": ["4998"], "Strict-Transport-Security": ["max-age=31536000; includeSubdomains; preload"], "Server": ["GitHub.com"], "X-OAuth-Scopes": ["public_repo, read:user"], "X-GitHub-Media-Type": ["github.v3; param=full; format=json"], "X-Content-Type-Options": ["nosniff"], "Content-Encoding": ["gzip"], "X-Runtime-rack": ["0.706423"], "Vary": ["Accept, Authorization, Cookie, X-GitHub-OTP"], "X-RateLimit-Limit": ["5000"], "Cache-Control": ["private, max-age=60, s-maxage=60"], "Referrer-Policy": ["origin-when-cross-origin, strict-origin-when-cross-origin"], "Content-Type": ["application/json; charset=utf-8"], "X-Accepted-OAuth-Scopes": [""], "X-RateLimit-Reset": ["1533285098"]}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "recorded_at": "2018-08-03T07:31:39"}], "recorded_with": "betamax/0.8.1"} \ No newline at end of file diff --git a/tests/cassettes/Issue_remove_assignees.json b/tests/cassettes/Issue_remove_assignees.json new file mode 100644 index 00000000..2a9ff031 --- /dev/null +++ b/tests/cassettes/Issue_remove_assignees.json @@ -0,0 +1,1 @@ +{"http_interactions": [{"request": {"body": {"string": "", "encoding": "utf-8"}, "headers": {"Accept-Encoding": ["gzip, deflate"], "Accept": ["application/vnd.github.v3.full+json"], "User-Agent": ["github3.py/1.1.0"], "Accept-Charset": ["utf-8"], "Connection": ["keep-alive"], "Content-Type": ["application/json"], "Authorization": ["token <AUTH_TOKEN>"]}, "method": "GET", "uri": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA+1YbW/iRhD+K66lVm0UY4wdSCgQXdWrdB8gdyppTg0ntLYX2MTe9e0L1EH57zdr82IsSMJL1Q89CQSsZ559dnae2R3mpuKR2TQnUiaiadsoIZUxkRPlVwIW2xwnTNiCjGM0JVyJmmfnT91KktpECIWF3XAc89zMTIlkPB0eDgk4EfJxJI7AKNCyc7C5TVGMnwEc1hRjKk8Fv4QDZDw9IW4OBqgTGUelUBR25037QkKzWXMvLq4878o5NykL8VCPmd3fb+t/fu49hXe3affp1rnpf6re9N+3YVqqYh9zswk7e25KIiMM9j1mzFBqSGYoigTMTQ1EjSwHwEUJ7TA3IzYmFKxjjGWM6Fg9khTBcz1lo16rXrjuJolP9b8+96LgIah1H9453aeuJoCmSCJeToJsUFQXCapnDBiVEPcsV5W9wL+etj3AGPMFSrZaTfGlTNdowi6zfjn+ZesRiyI2A5wy8U1RbZnKXrkCz/w7oeNDYcB1bjM5wRBBWJZO/DERr2X9NlqZ2xw0LyQkjQYSsAUch/tTWzgCsRkFTvOstmSIyhcBJ4kkjB4QuQ13gGN8jCh5QgfCgbsAlKya7b/IzA3c31INtsU795vbCSdTFKQ6PBwHmEwh4odilgAAUqaJFvStlizEn0g8RGGsZTtCkcDPyyJsNu+/ZDsutTlLMAXziAWPGBSVmYJSs0qAwWCt/QcUfFWYE10XtPjcS6d2Wd0u+67X7X/wuu/ar8m+tlP2OfwRqi/yfVnxRcu91L5yPFzpZYhjVL7GOkrha5jTqbuAWSwMhyh7DbWvqtee+yt67XsaNRe5bJSCNyl5qU8BYv6u0K2X3LwQl+UFxzgEeK+zuAzxXaG7O4ty0P+vCoUDNiYRFpJROEOpiqJ1lwIXd/jBMZy/4RBJCGat6jSsat1y3L5z0aw1mp7zN2SpSsINm0urCi+3X200XafpXmmbIGJiAZPPgpScMD6EAsECkl2XYILeTe89GPssTIf6KIShVtLpw1USGwLjWOj7v4/1zX/RA4wUDbTzueEraVAm9bNVhxBjmCQ0RowbH3Sn0LKTzoAOaGvC4ROg7xCVGSYKHg05ISLvKK6NlpCc0XGnhYwJx6P2YNWjzmazis8Ulalgigc4u/0velGv7jSuXM+zKLOgW7Eks5ZcLEStzOpayXgYoDhBcHNpJ5GCjuUn+PlrNp53FG3JgRDmP9b+cC5dr9FYGcQ4JCpu5/OtRnMm7bw5G5gGxxEwpiyvHwOz85EJiIyR8zYYNE7yh5aNOi17sU7jDqIaBDiRuRHBwpgSZLxx/f/Jon4r7IJeTKXlZ9sKm7xMIon/0Yl7ugzS2TOgO9NmW5x3hbZIv7IgfFquHLjCu1VMVyvPuI5+oN+WZemPnSs6O7vftqgvPy//s/lX9PCiFvTDTR3okQ0N/HJ2tivs98W4v7KMrWl9NLdKtin2tl1ZV0o/zevx8zchJQr2JBMAAA==", "encoding": "utf-8"}, "headers": {"X-XSS-Protection": ["1; mode=block"], "Content-Security-Policy": ["default-src 'none'"], "Access-Control-Expose-Headers": ["ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval"], "Transfer-Encoding": ["chunked"], "Last-Modified": ["Fri, 03 Aug 2018 07:31:39 GMT"], "Access-Control-Allow-Origin": ["*"], "X-Frame-Options": ["deny"], "Status": ["200 OK"], "X-GitHub-Request-Id": ["95AE:3FAE:2C780A7:52C3D04:5B640BE5"], "ETag": ["W/\"b4505c5c6261cbcfd05fc36ec2685139\""], "Date": ["Fri, 03 Aug 2018 08:01:41 GMT"], "X-RateLimit-Remaining": ["4997"], "Strict-Transport-Security": ["max-age=31536000; includeSubdomains; preload"], "Server": ["GitHub.com"], "X-OAuth-Scopes": ["public_repo, read:user"], "X-GitHub-Media-Type": ["github.v3; param=full; format=json"], "X-Content-Type-Options": ["nosniff"], "Content-Encoding": ["gzip"], "X-Runtime-rack": ["0.080789"], "Vary": ["Accept, Authorization, Cookie, X-GitHub-OTP"], "X-RateLimit-Limit": ["5000"], "Cache-Control": ["private, max-age=60, s-maxage=60"], "Referrer-Policy": ["origin-when-cross-origin, strict-origin-when-cross-origin"], "Content-Type": ["application/json; charset=utf-8"], "X-Accepted-OAuth-Scopes": ["repo"], "X-RateLimit-Reset": ["1533285098"]}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "recorded_at": "2018-08-03T08:01:41"}, {"request": {"body": {"string": "{\"assignees\": []}", "encoding": "utf-8"}, "headers": {"Content-Length": ["17"], "Accept-Encoding": ["gzip, deflate"], "Accept": ["application/vnd.github.v3.full+json"], "User-Agent": ["github3.py/1.1.0"], "Accept-Charset": ["utf-8"], "Connection": ["keep-alive"], "Content-Type": ["application/json"], "Authorization": ["token <AUTH_TOKEN>"]}, "method": "PATCH", "uri": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "response": {"body": {"string": "", "base64_string": "H4sIAAAAAAAAA8VW/W/iNhj+V7xIm7aqIQRSaHOBatNu0n6g3Wn0erpyQk5igq+JHfkDlqL+73vtBAaI9npcT5OIIPb7Pn7er8esHC1yJ3TmSpUy9Dxc0lZG1VzHrYQXniAll56kWYEXVGjZCbx6t9sqK49KqYn0+r7vnDrWlCouqunxkICT45jk8hswtmh5NdjKY7ggjwAOMRWEqdeCX8MBMlm8Im4NBqhzVeR7qdiqzovqQlMn7HTPzi6C4MI/dRhPydSsOaPfb3p/f7h6SG9vqtHDjX89fte+Hr8dwLFMFzERTgiVPXUUVTkB+yuOlrhCiiPNsISzGcIM2R4AFy2Nw8rJeUYZWBeEqAKzTN/TCsO+ObLf67TPut1dEu967z9c5cnnpDP6/Ks/ehgZAniBFRb7TWAXZbtpUHNiwpmCvNte1V6Df7kYBICRiQbFRmsoPtfpBk16+6yfz/++9YznOV8Czj7x3aE6cJS3cQWe9W/KsmNhwHXlcTUnkEEIyzR+RuWXuv4QLeu2gpmXCprGAEkogSDp11NrHIHYkgGnldUWi6hjmQhaKsrZEZnbcQc4LjLM6AM+Eg7cJaBYNfv6IK0buL9EDQ7lu/ZbeaWgC5xUJj2CJIQuIOPHYu4BAKSqSjPQN2ZkIf9UkSlOCzO2M5xL8rgWYSe8+2Qrrow5LwkD85wn9wQmyprCpFolIGDAdJ7/9y5r54LmRCrONvsbyQw7IMeCAHY6xQrwO22/77Z7rt8d+2dhpx8G/kc4T5fpjs2524ZPd9w+D9t+Y5PkXDYwDQut5lxMgRxPqG0FI2DXV28BMOZpNTWDDUtRORzDmBAkCSmk0baYGFVr9G2mWWKcT1GsFWJcmb2N+hUEDknRjAv0p1HByCuHEzZh0VzAN0DfYqYsJk7ukZpTWavlJYqkEpxlwwijuSCzwWRz/y6Xy1bMNVOV5FokxCpbc88GPb9/0Q0Cl3EXlNhV3F1zcTFzrdWlVsU0wUWJoSqDMtegxj/B6xu7XqvlQAkgRMSPnT/8827Q728MCpJSXQzq8zarNZNBffFMHCRIDowZr3Vq4gz/4hIyg2reiMOloH6IPDyMvCZOdAtZTRJSqtqIEokWFKMXxv+/BPXbVhVMMK0otmWFIq+bSJF/TOO+XgeZ7pmwJ9vmUJ6fSu02/VZD+HW5CuAKT7Tdrm7dcUOzYR7Xdc3XkxGdnNwdCurTz+v/o99lHp6dBbO5OwdmZWcGfjk5eSrtd9t5/0IYB9v6m7m1bFG8Q1WBNmiUMq5qvX78F2GbEbsADAAA", "encoding": "utf-8"}, "headers": {"X-XSS-Protection": ["1; mode=block"], "Content-Security-Policy": ["default-src 'none'"], "Access-Control-Expose-Headers": ["ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval"], "Transfer-Encoding": ["chunked"], "Access-Control-Allow-Origin": ["*"], "X-Frame-Options": ["deny"], "Status": ["200 OK"], "X-GitHub-Request-Id": ["95AE:3FAE:2C780CD:52C3D3D:5B640BE5"], "ETag": ["W/\"d2e139e7445377dc3ca16b5e4bf28495\""], "Date": ["Fri, 03 Aug 2018 08:01:41 GMT"], "X-RateLimit-Remaining": ["4996"], "Strict-Transport-Security": ["max-age=31536000; includeSubdomains; preload"], "Server": ["GitHub.com"], "X-OAuth-Scopes": ["public_repo, read:user"], "X-GitHub-Media-Type": ["github.v3; param=full; format=json"], "X-Content-Type-Options": ["nosniff"], "Content-Encoding": ["gzip"], "X-Runtime-rack": ["0.273701"], "Vary": ["Accept, Authorization, Cookie, X-GitHub-OTP"], "X-RateLimit-Limit": ["5000"], "Cache-Control": ["private, max-age=60, s-maxage=60"], "Referrer-Policy": ["origin-when-cross-origin, strict-origin-when-cross-origin"], "Content-Type": ["application/json; charset=utf-8"], "X-Accepted-OAuth-Scopes": [""], "X-RateLimit-Reset": ["1533285098"]}, "status": {"message": "OK", "code": 200}, "url": "https://api.github.com/repos/sigmavirus24/github3.py/issues/711"}, "recorded_at": "2018-08-03T08:01:41"}], "recorded_with": "betamax/0.8.1"} \ No newline at end of file diff --git a/tests/integration/test_issue.py b/tests/integration/test_issue.py index d9aadf2e..fc5426ad 100644 --- a/tests/integration/test_issue.py +++ b/tests/integration/test_issue.py @@ -11,6 +11,18 @@ class TestIssue(IntegrationHelper): """Integration tests for methods on the Issue class.""" + def test_add_assignees(self): + """Test the ability to add assignees to an issue.""" + self.auto_login() + cassette_name = self.cassette_name('add_assignees') + with self.recorder.use_cassette(cassette_name): + issue = self.gh.issue(username='sigmavirus24', + repository='github3.py', + number=711) + assigned = issue.add_assignees(['jacquerie']) + + assert assigned is True + def test_add_labels(self): """Test the ability to add a label to an issue.""" self.auto_login() @@ -203,6 +215,18 @@ class TestIssue(IntegrationHelper): assert reopened is True + def test_remove_assignees(self): + """Test the ability to remove assignees from an issue.""" + self.auto_login() + cassette_name = self.cassette_name('remove_assignees') + with self.recorder.use_cassette(cassette_name): + issue = self.gh.issue(username='sigmavirus24', + repository='github3.py', + number=711) + unassigned = issue.remove_assignees(['jacquerie']) + + assert unassigned is True + def test_remove_label(self): """Test the ability to remove a label from an issue.""" self.auto_login() diff --git a/tests/unit/test_issues_issue.py b/tests/unit/test_issues_issue.py index f8f1f0e0..f67cca29 100644 --- a/tests/unit/test_issues_issue.py +++ b/tests/unit/test_issues_issue.py @@ -44,6 +44,10 @@ class TestIssueRequiresAuth(helper.UnitRequiresAuthenticationHelper): def after_setup(self): self.session.has_auth.return_value = False + def test_add_assignees(self): + """Verify that adding assignees requires authentication.""" + self.assert_requires_auth(self.instance.add_assignees) + def test_add_labels(self): """Verify that adding a label requires authentication.""" self.assert_requires_auth(self.instance.add_labels, 'enhancement') @@ -73,6 +77,10 @@ class TestIssueRequiresAuth(helper.UnitRequiresAuthenticationHelper): """Verify that removing all labels requires authentication.""" self.assert_requires_auth(self.instance.remove_all_labels) + def test_remove_assignees(self): + """Verify that removing assignees requires authentication.""" + self.assert_requires_auth(self.instance.remove_assignees) + def test_remove_label(self): """Verify that removing a label requires authentication.""" self.assert_requires_auth(self.instance.remove_label, 'enhancement') @@ -92,6 +100,15 @@ class TestIssue(helper.UnitHelper): described_class = github3.issues.Issue example_data = get_issue_example_data() + def test_add_assignees(self): + """Verify the request for adding assignees to an issue.""" + self.instance.add_assignees(['jacquerie']) + + self.session.patch.assert_called_with( + url_for(), + data='{"assignees": ["jacquerie"]}' + ) + def test_add_labels(self): """Verify the request for adding a label.""" self.instance.add_labels('enhancement') @@ -294,6 +311,15 @@ class TestIssue(helper.UnitHelper): assert self.instance.remove_all_labels() == [] replace_labels.assert_called_once_with([]) + def test_remove_assignees(self): + """Verify the request for removing assignees from an issue.""" + self.instance.remove_assignees(['octocat']) + + self.session.patch.assert_called_once_with( + url_for(), + data='{"assignees": []}' + ) + def test_remove_label(self): """Verify the request for removing a label from an issue.""" self.instance.remove_label('enhancement')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-xdist", "betamax", "betamax_matchers" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "dev-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 betamax==0.8.1 betamax-matchers==0.4.0 certifi==2021.5.30 charset-normalizer==2.0.12 distlib==0.3.9 execnet==1.9.0 filelock==3.4.1 -e git+https://github.com/sigmavirus24/github3.py.git@87af5a1d26597d7cf1a843199a1b5a2449cd8069#egg=github3.py idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 mock==1.0.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 requests==2.27.1 requests-toolbelt==1.0.0 six==1.17.0 swebench-matterhorn @ file:///swebench_matterhorn toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 uritemplate==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 zipp==3.6.0
name: github3.py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - betamax==0.8.1 - betamax-matchers==0.4.0 - charset-normalizer==2.0.12 - distlib==0.3.9 - execnet==1.9.0 - filelock==3.4.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mock==1.0.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - requests==2.27.1 - requests-toolbelt==1.0.0 - six==1.17.0 - swebench-matterhorn==0.0.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - uritemplate==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wheel==0.21.0 - zipp==3.6.0 prefix: /opt/conda/envs/github3.py
[ "tests/integration/test_issue.py::TestIssue::test_add_assignees", "tests/integration/test_issue.py::TestIssue::test_remove_assignees", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_add_assignees", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_remove_assignees", "tests/unit/test_issues_issue.py::TestIssue::test_add_assignees", "tests/unit/test_issues_issue.py::TestIssue::test_remove_assignees" ]
[]
[ "tests/integration/test_issue.py::TestIssue::test_add_labels", "tests/integration/test_issue.py::TestIssue::test_assign", "tests/integration/test_issue.py::TestIssue::test_closed", "tests/integration/test_issue.py::TestIssue::test_comment", "tests/integration/test_issue.py::TestIssue::test_comments", "tests/integration/test_issue.py::TestIssue::test_create_comment", "tests/integration/test_issue.py::TestIssue::test_edit", "tests/integration/test_issue.py::TestIssue::test_edit_both_assignee_and_assignees", "tests/integration/test_issue.py::TestIssue::test_edit_multiple_assignees", "tests/integration/test_issue.py::TestIssue::test_events", "tests/integration/test_issue.py::TestIssue::test_labels", "tests/integration/test_issue.py::TestIssue::test_lock", "tests/integration/test_issue.py::TestIssue::test_pull_request", "tests/integration/test_issue.py::TestIssue::test_remove_all_labels", "tests/integration/test_issue.py::TestIssue::test_remove_label", "tests/integration/test_issue.py::TestIssue::test_reopen", "tests/integration/test_issue.py::TestIssue::test_replace_labels", "tests/integration/test_issue.py::TestIssue::test_unlock", "tests/integration/test_issue.py::TestLabel::test_delete", "tests/integration/test_issue.py::TestLabel::test_update", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_add_labels", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_assign", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_close", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_create_comment", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_edit_comment", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_lock", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_remove_all_labels", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_remove_label", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_reopen", "tests/unit/test_issues_issue.py::TestIssueRequiresAuth::test_unlock", "tests/unit/test_issues_issue.py::TestIssue::test_add_labels", "tests/unit/test_issues_issue.py::TestIssue::test_assign", "tests/unit/test_issues_issue.py::TestIssue::test_assign_empty_username", "tests/unit/test_issues_issue.py::TestIssue::test_close", "tests/unit/test_issues_issue.py::TestIssue::test_close_with_unicode_labels", "tests/unit/test_issues_issue.py::TestIssue::test_comment", "tests/unit/test_issues_issue.py::TestIssue::test_comment_positive_id", "tests/unit/test_issues_issue.py::TestIssue::test_create_comment", "tests/unit/test_issues_issue.py::TestIssue::test_create_comment_required_body", "tests/unit/test_issues_issue.py::TestIssue::test_create_lock", "tests/unit/test_issues_issue.py::TestIssue::test_edit", "tests/unit/test_issues_issue.py::TestIssue::test_edit_milestone", "tests/unit/test_issues_issue.py::TestIssue::test_edit_multiple_assignees", "tests/unit/test_issues_issue.py::TestIssue::test_edit_no_parameters", "tests/unit/test_issues_issue.py::TestIssue::test_enterprise", "tests/unit/test_issues_issue.py::TestIssue::test_equality", "tests/unit/test_issues_issue.py::TestIssue::test_is_closed", "tests/unit/test_issues_issue.py::TestIssue::test_issue_137", "tests/unit/test_issues_issue.py::TestIssue::test_pull_request", "tests/unit/test_issues_issue.py::TestIssue::test_pull_request_without_urls", "tests/unit/test_issues_issue.py::TestIssue::test_remove_all_labels", "tests/unit/test_issues_issue.py::TestIssue::test_remove_label", "tests/unit/test_issues_issue.py::TestIssue::test_remove_lock", "tests/unit/test_issues_issue.py::TestIssue::test_reopen", "tests/unit/test_issues_issue.py::TestIssue::test_replace_labels", "tests/unit/test_issues_issue.py::TestIssueIterators::test_comments", "tests/unit/test_issues_issue.py::TestIssueIterators::test_events", "tests/unit/test_issues_issue.py::TestIssueIterators::test_labels", "tests/unit/test_issues_issue.py::TestLabelRequiresAuth::test_delete", "tests/unit/test_issues_issue.py::TestLabelRequiresAuth::test_update", "tests/unit/test_issues_issue.py::TestLabel::test_delete", "tests/unit/test_issues_issue.py::TestLabel::test_equality", "tests/unit/test_issues_issue.py::TestLabel::test_repr", "tests/unit/test_issues_issue.py::TestLabel::test_str", "tests/unit/test_issues_issue.py::TestLabel::test_update", "tests/unit/test_issues_issue.py::TestLabel::test_update_without_description", "tests/unit/test_issues_issue.py::TestIssueEvent::test_assignee", "tests/unit/test_issues_issue.py::TestIssueEvent::test_created_at", "tests/unit/test_issues_issue.py::TestIssueEvent::test_equality", "tests/unit/test_issues_issue.py::TestIssueEvent::test_repr" ]
[]
BSD 3-Clause "New" or "Revised" License
2,862
780
[ "src/github3/issues/issue.py" ]
python-metar__python-metar-43
6b5dcc358c1a7b2c46679e83d7ef5f3af25e4f2e
2018-08-03 02:30:55
94a48ea3b965ed1b38c5ab52553dd4cbcc23867c
diff --git a/metar/Metar.py b/metar/Metar.py index 0e773cb..338e172 100755 --- a/metar/Metar.py +++ b/metar/Metar.py @@ -587,7 +587,7 @@ class Metar(object): self.vis_dir = direction(vis_dir) self.vis = distance(vis_dist, vis_units, vis_less) - def _handleRunway( self, d ): + def _handleRunway(self, d): """ Parse a runway visual range group. @@ -596,15 +596,17 @@ class Metar(object): . name [string] . low [distance] . high [distance] - """ - if d['name']: - name = d['name'] - low = distance(d['low']) - if d['high']: - high = distance(d['high']) - else: - high = low - self.runway.append((name,low,high)) + . unit [string] + """ + if d['name'] is None: + return + unit = d['unit'] if d['unit'] is not None else 'FT' + low = distance(d['low'], unit) + if d['high'] is None: + high = low + else: + high = distance(d['high'], unit) + self.runway.append([d['name'], low, high, unit]) def _handleWeather( self, d ): """ @@ -1119,16 +1121,23 @@ class Metar(object): text += "; %s" % self.max_vis.string(units) return text - def runway_visual_range( self, units=None ): + def runway_visual_range(self, units=None): """ Return a textual description of the runway visual range. """ lines = [] - for name,low,high in self.runway: + for name, low, high, unit in self.runway: + reportunits = unit if units is None else units if low != high: - lines.append("on runway %s, from %d to %s" % (name, low.value(units), high.string(units))) + lines.append( + ("on runway %s, from %d to %s" + ) % (name, low.value(reportunits), + high.string(reportunits)) + ) else: - lines.append("on runway %s, %s" % (name, low.string(units))) + lines.append( + "on runway %s, %s" % (name, low.string(reportunits)) + ) return "; ".join(lines) def present_weather( self ):
Feet vs. Meters This METAR has R28L/2600FT but reduction reads: visual range: on runway 28L, 2600 meters (should read: visual range: on runway 28L, 2600 feet) Reference: METAR KPIT 091955Z COR 22015G25KT 3/4SM R28L/2600FT TSRA OVC010CB 18/16 A2992 RMK SLP045 T01820159
python-metar/python-metar
diff --git a/test/test_metar.py b/test/test_metar.py index 76147e1..e6c8fee 100644 --- a/test/test_metar.py +++ b/test/test_metar.py @@ -17,6 +17,17 @@ class MetarTest(unittest.TestCase): def raisesParserError(self, code): self.assertRaises(Metar.ParserError, Metar.Metar, code ) + def test_issue40_runwayunits(self): + """Check reported units on runway visual range.""" + report = Metar.Metar( + "METAR KPIT 091955Z COR 22015G25KT 3/4SM R28L/2600FT TSRA OVC010CB " + "18/16 A2992 RMK SLP045 T01820159" + ) + res = report.runway_visual_range() + self.assertEquals(res, 'on runway 28L, 2600 feet') + res = report.runway_visual_range('M') + self.assertTrue(res, 'on runway 28L, 792 meters') + def test_010_parseType_default(self): """Check default value of the report type.""" self.assertEqual( Metar.Metar("KEWR").type, "METAR" )
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/python-metar/python-metar.git@6b5dcc358c1a7b2c46679e83d7ef5f3af25e4f2e#egg=metar more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: python-metar channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/python-metar
[ "test/test_metar.py::MetarTest::test_issue40_runwayunits" ]
[]
[ "test/test_metar.py::MetarTest::test_010_parseType_default", "test/test_metar.py::MetarTest::test_011_parseType_legal", "test/test_metar.py::MetarTest::test_020_parseStation_legal", "test/test_metar.py::MetarTest::test_021_parseStation_illegal", "test/test_metar.py::MetarTest::test_030_parseTime_legal", "test/test_metar.py::MetarTest::test_031_parseTime_specify_year", "test/test_metar.py::MetarTest::test_032_parseTime_specify_month", "test/test_metar.py::MetarTest::test_033_parseTime_auto_month", "test/test_metar.py::MetarTest::test_034_parseTime_auto_year", "test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month", "test/test_metar.py::MetarTest::test_040_parseModifier_default", "test/test_metar.py::MetarTest::test_041_parseModifier", "test/test_metar.py::MetarTest::test_042_parseModifier_nonstd", "test/test_metar.py::MetarTest::test_043_parseModifier_illegal", "test/test_metar.py::MetarTest::test_140_parseWind", "test/test_metar.py::MetarTest::test_141_parseWind_nonstd", "test/test_metar.py::MetarTest::test_142_parseWind_illegal", "test/test_metar.py::MetarTest::test_150_parseVisibility", "test/test_metar.py::MetarTest::test_151_parseVisibility_direction", "test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature", "test/test_metar.py::MetarTest::test_290_ranway_state", "test/test_metar.py::MetarTest::test_300_parseTrend", "test/test_metar.py::MetarTest::test_310_parse_sky_conditions", "test/test_metar.py::MetarTest::test_not_strict_mode", "test/test_metar.py::MetarTest::test_snowdepth" ]
[]
BSD License
2,864
630
[ "metar/Metar.py" ]
HECBioSim__Longbow-107
585dc2198b0f3817e4822da13725489585efcf15
2018-08-03 14:42:57
c81fcaccfa7fb2dc147e40970ef806dc6d6b22a4
diff --git a/longbow/schedulers/lsf.py b/longbow/schedulers/lsf.py index ab20689..8992636 100644 --- a/longbow/schedulers/lsf.py +++ b/longbow/schedulers/lsf.py @@ -98,6 +98,10 @@ def prepare(job): jobfile.write("#BSUB -m " + job["lsf-cluster"] + "\n") + if job["memory"] is not "": + + jobfile.write('#BSUB -R "rusage[mem=' + job["memory"] + 'G]"\n') + # Account to charge (if supplied). if job["account"] is not "": diff --git a/longbow/schedulers/pbs.py b/longbow/schedulers/pbs.py index 1f490a5..dd5a1e1 100644 --- a/longbow/schedulers/pbs.py +++ b/longbow/schedulers/pbs.py @@ -131,16 +131,13 @@ def prepare(job): # Number of mpi processes per node. mpiprocs = cpn - # Memory size (used to select nodes with minimum memory). - memory = job["memory"] - tmp = "select=" + nodes + ":ncpus=" + ncpus + ":mpiprocs=" + mpiprocs # If user has specified memory append the flag (not all machines support # this). - if memory is not "": + if job["memory"] is not "": - tmp = tmp + ":mem=" + memory + "gb" + tmp = tmp + ":mem=" + job["memory"] + "gb" # Write the resource requests jobfile.write("#PBS -l " + tmp + "\n") diff --git a/longbow/schedulers/sge.py b/longbow/schedulers/sge.py index a249375..c1acd0f 100644 --- a/longbow/schedulers/sge.py +++ b/longbow/schedulers/sge.py @@ -102,6 +102,10 @@ def prepare(job): jobfile.write("#$ -l h_rt=" + job["maxtime"] + ":00\n") + if job["memory"] is not "": + + jobfile.write("#$ -l h_vmem=" + job["memory"] + "G\n") + # Email user. if job["email-address"] is not "": diff --git a/longbow/schedulers/slurm.py b/longbow/schedulers/slurm.py index 22b8661..752e83a 100644 --- a/longbow/schedulers/slurm.py +++ b/longbow/schedulers/slurm.py @@ -100,6 +100,10 @@ def prepare(job): jobfile.write("#SBATCH " + job["accountflag"] + " " + job["account"] + "\n") + if job["memory"] is not "": + + jobfile.write("#SBATCH --mem=" + job["memory"] + "G" + "\n") + # Generic resource (if supplied) if job["slurm-gres"] is not "": diff --git a/longbow/schedulers/soge.py b/longbow/schedulers/soge.py index a1d0223..9217a95 100644 --- a/longbow/schedulers/soge.py +++ b/longbow/schedulers/soge.py @@ -103,6 +103,10 @@ def prepare(job): jobfile.write("#$ -l h_rt=" + job["maxtime"] + ":00\n") + if job["memory"] is not "": + + jobfile.write("#$ -l h_vmem=" + job["memory"] + "G\n") + # Email user. if job["email-address"] is not "":
memory parameter only used in PBS Either rename this to pbs-memory to denote that it is pbs only or add support in the other schedulers.
HECBioSim/Longbow
diff --git a/tests/standards/lsf_submitfiles/case9.txt b/tests/standards/lsf_submitfiles/case9.txt new file mode 100644 index 0000000..60275d9 --- /dev/null +++ b/tests/standards/lsf_submitfiles/case9.txt @@ -0,0 +1,10 @@ +#!/bin/bash --login +#BSUB -J testjob +#BSUB -q debug +#BSUB -R "rusage[mem=10G]" +#BSUB -W 24:00 +#BSUB -n 24 + +module load amber + +mpiexec.hydra pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out diff --git a/tests/standards/sge_submitfiles/case8.txt b/tests/standards/sge_submitfiles/case8.txt new file mode 100644 index 0000000..f05a1be --- /dev/null +++ b/tests/standards/sge_submitfiles/case8.txt @@ -0,0 +1,9 @@ +#!/bin/bash --login +#$ -cwd -V +#$ -N testjob +#$ -q debug +#$ -l h_rt=24:00:00 +#$ -l h_vmem=10G +module load amber + +mpiexec pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out diff --git a/tests/standards/slurm_submitfiles/case8.txt b/tests/standards/slurm_submitfiles/case8.txt new file mode 100644 index 0000000..bcef936 --- /dev/null +++ b/tests/standards/slurm_submitfiles/case8.txt @@ -0,0 +1,15 @@ +#!/bin/bash --login +#SBATCH -J testjob +#SBATCH -p debug +#SBATCH --mem=10G +#SBATCH --gres=gpu:1 +#SBATCH -n 24 +#SBATCH -N 1 +#SBATCH -t 24:00:00 + +ls /dir +cd /dir + +module load amber + +mpirun pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out diff --git a/tests/standards/soge_submitfiles/case8.txt b/tests/standards/soge_submitfiles/case8.txt new file mode 100644 index 0000000..5166c90 --- /dev/null +++ b/tests/standards/soge_submitfiles/case8.txt @@ -0,0 +1,12 @@ +#!/bin/bash --login +#$ -cwd -V +#$ -N testjob +#$ -q debug +#$ -l h_rt=24:00:00 +#$ -l h_vmem=10G +#$ -l nodes=1 +#$ -pe ib 12 + +module load amber + +mpiexec pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out diff --git a/tests/unit/schedulers_lsf/test_lsf_prepare.py b/tests/unit/schedulers_lsf/test_lsf_prepare.py index 3a4d462..e22c2b9 100644 --- a/tests/unit/schedulers_lsf/test_lsf_prepare.py +++ b/tests/unit/schedulers_lsf/test_lsf_prepare.py @@ -55,6 +55,7 @@ def test_prepare_case1(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -89,6 +90,7 @@ def test_prepare_case2(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "5", @@ -121,6 +123,7 @@ def test_prepare_case3(): "localworkdir": "/tmp", "lsf-cluster": "cluster1", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -154,6 +157,7 @@ def test_prepare_case4(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -187,6 +191,7 @@ def test_prepare_case5(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -220,6 +225,7 @@ def test_prepare_case6(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -253,6 +259,7 @@ def test_prepare_case7(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -286,6 +293,7 @@ def test_prepare_case8(): "localworkdir": "/tmp", "lsf-cluster": "", "maxtime": "24:00", + "memory": "", "modules": "amber", "queue": "debug", "replicates": "1", @@ -299,3 +307,37 @@ def test_prepare_case8(): os.path.join( os.getcwd(), "tests/standards/lsf_submitfiles/case8.txt"), "rb").read() + + +def test_prepare_case9(): + + """ + Test handler parameters + """ + + job = { + "account": "", + "accountflag": "", + "cores": "24", + "executableargs": "pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out", + "handler": "mpiexec.hydra", + "email-address": "", + "email-flags": "", + "jobname": "testjob", + "localworkdir": "/tmp", + "lsf-cluster": "", + "maxtime": "24:00", + "memory": "10", + "modules": "amber", + "queue": "debug", + "replicates": "1", + "scripts": "", + "upload-include": "file1, file2" + } + + prepare(job) + + assert open("/tmp/submit.lsf", "rb").read() == open( + os.path.join( + os.getcwd(), + "tests/standards/lsf_submitfiles/case9.txt"), "rb").read() diff --git a/tests/unit/schedulers_sge/test_sge_prepare.py b/tests/unit/schedulers_sge/test_sge_prepare.py index f08aac8..a462308 100644 --- a/tests/unit/schedulers_sge/test_sge_prepare.py +++ b/tests/unit/schedulers_sge/test_sge_prepare.py @@ -295,3 +295,40 @@ def test_prepare_case7(): os.path.join( os.getcwd(), "tests/standards/sge_submitfiles/case7.txt"), "rb").read() + + +def test_prepare_case8(): + + """ + Test memory param + """ + + job = { + "account": "", + "accountflag": "", + "cluster": "", + "cores": "1", + "corespernode": "", + "executableargs": "pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out", + "handler": "mpiexec", + "email-address": "", + "email-flags": "", + "jobname": "testjob", + "localworkdir": "/tmp", + "maxtime": "24:00", + "memory": "10", + "modules": "amber", + "queue": "debug", + "replicates": "1", + "scripts": "", + "sge-peflag": "mpi", + "sge-peoverride": "false", + "upload-include": "file1, file2" + } + + prepare(job) + + assert open("/tmp/submit.sge", "rb").read() == open( + os.path.join( + os.getcwd(), + "tests/standards/sge_submitfiles/case8.txt"), "rb").read() diff --git a/tests/unit/schedulers_slurm/test_slurm_prepare.py b/tests/unit/schedulers_slurm/test_slurm_prepare.py index 9219865..f40bebe 100644 --- a/tests/unit/schedulers_slurm/test_slurm_prepare.py +++ b/tests/unit/schedulers_slurm/test_slurm_prepare.py @@ -302,3 +302,41 @@ def test_prepare_case7(): os.path.join( os.getcwd(), "tests/standards/slurm_submitfiles/case7.txt"), "rb").read() + + +def test_prepare_case8(): + + """ + Test gres parameters + """ + + job = { + "account": "", + "accountflag": "", + "cluster": "", + "cores": "24", + "corespernode": "24", + "executableargs": "pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out", + "handler": "mpirun", + "email-address": "", + "email-flags": "", + "jobname": "testjob", + "localworkdir": "/tmp", + "maxtime": "24:00", + "memory": "10", + "modules": "amber", + "queue": "debug", + "replicates": "1", + "scripts": "ls /dir, cd /dir", + "slurm-gres": "gpu:1", + "sge-peflag": "mpi", + "sge-peoverride": "false", + "upload-include": "file1, file2" + } + + prepare(job) + + assert open("/tmp/submit.slurm", "rb").read() == open( + os.path.join( + os.getcwd(), + "tests/standards/slurm_submitfiles/case8.txt"), "rb").read() diff --git a/tests/unit/schedulers_soge/test_soge_prepare.py b/tests/unit/schedulers_soge/test_soge_prepare.py index e8666c8..dbf9615 100644 --- a/tests/unit/schedulers_soge/test_soge_prepare.py +++ b/tests/unit/schedulers_soge/test_soge_prepare.py @@ -295,3 +295,40 @@ def test_prepare_case7(): os.path.join( os.getcwd(), "tests/standards/soge_submitfiles/case7.txt"), "rb").read() + + +def test_prepare_case8(): + + """ + Test under subscription + """ + + job = { + "account": "", + "accountflag": "", + "cluster": "", + "cores": "12", + "corespernode": "24", + "executableargs": "pmemd.MPI -O -i e.in -c e.min -p e.top -o e.out", + "handler": "mpiexec", + "email-address": "", + "email-flags": "", + "jobname": "testjob", + "localworkdir": "/tmp", + "maxtime": "24:00", + "memory": "10", + "modules": "amber", + "queue": "debug", + "replicates": "1", + "scripts": "", + "sge-peflag": "mpi", + "sge-peoverride": "false", + "upload-include": "file1, file2" + } + + prepare(job) + + assert open("/tmp/submit.soge", "rb").read() == open( + os.path.join( + os.getcwd(), + "tests/standards/soge_submitfiles/case8.txt"), "rb").read()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 5 }
.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage", "coveralls" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/HECBioSim/Longbow.git@585dc2198b0f3817e4822da13725489585efcf15#egg=Longbow packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: Longbow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/Longbow
[ "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case9", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case8", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case8", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case8" ]
[]
[ "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case1", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case2", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case3", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case4", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case5", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case6", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case7", "tests/unit/schedulers_lsf/test_lsf_prepare.py::test_prepare_case8", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case1", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case2", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case3", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case4", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case5", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case6", "tests/unit/schedulers_sge/test_sge_prepare.py::test_prepare_case7", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case1", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case2", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case3", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case4", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case5", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case6", "tests/unit/schedulers_slurm/test_slurm_prepare.py::test_prepare_case7", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case1", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case2", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case3", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case4", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case5", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case6", "tests/unit/schedulers_soge/test_soge_prepare.py::test_prepare_case7" ]
[]
BSD 3-Clause License
2,865
915
[ "longbow/schedulers/lsf.py", "longbow/schedulers/pbs.py", "longbow/schedulers/sge.py", "longbow/schedulers/slurm.py", "longbow/schedulers/soge.py" ]
pennmem__cmlreaders-180
2ffd443b75a0095a5c1edaaadf6e6e764c0e8a78
2018-08-03 19:26:06
06f314e3c0ceb982fe72f94e7a636ab1fff06c29
diff --git a/cmlreaders/constants.py b/cmlreaders/constants.py index c4b84e3..3736269 100644 --- a/cmlreaders/constants.py +++ b/cmlreaders/constants.py @@ -100,7 +100,8 @@ rhino_paths = { 'protocols/{protocol}/subjects/{subject}/experiments/{experiment}/sessions/{session}/behavioral/current_processed/ps4_events.json' ], 'sources': [ - 'protocols/{protocol}/subjects/{subject}/experiments/{experiment}/sessions/{session}/ephys/current_processed/sources.json' + "protocols/{protocol}/subjects/{subject}/experiments/{experiment}/sessions/{session}/ephys/current_processed/sources.json", + "data/eeg/{subject}/eeg.noreref/params.txt", ], # Processed EEG data basename diff --git a/cmlreaders/readers/readers.py b/cmlreaders/readers/readers.py index fadd626..ac415ba 100644 --- a/cmlreaders/readers/readers.py +++ b/cmlreaders/readers/readers.py @@ -131,6 +131,10 @@ class EventReader(BaseCMLReader): if self.session is not None: df = df[df["session"] == self.session] + # ensure we have an experiment column + if "experiment" not in df: + df.loc[:, "experiment"] = self.experiment + return df def as_dataframe(self):
Error attempting to load pyFR eeg I can load pyFR events, but I receive an error when attempting to load eeg: ``` reader = CMLReader("TJ039", experiment="pyFR", session=0) events = reader.load("events") word = events[events.type=='WORD'] eeg = reader.load_eeg(events=word, rel_start=-100, rel_stop=100) ... KeyError: 'experiment' ``` Adding an `experiment` column to the DF then yields a `FileNotFoundError`.
pennmem/cmlreaders
diff --git a/cmlreaders/test/test_eeg.py b/cmlreaders/test/test_eeg.py index acfd8fd..1e2e02e 100644 --- a/cmlreaders/test/test_eeg.py +++ b/cmlreaders/test/test_eeg.py @@ -225,13 +225,13 @@ class TestFileReaders: @pytest.mark.rhino class TestEEGReader: - # FIXME: add LTP, pyFR cases - @pytest.mark.parametrize("subject,index,channel", [ - ("R1298E", 87, "CH88"), # Split EEG - ("R1387E", 13, "CH14"), # Ramulator HDF5 + @pytest.mark.parametrize("subject,experiment,index,channel", [ + ("R1298E", "FR1", 87, "CH88"), # Split EEG + ("R1387E", "FR1", 13, "CH14"), # Ramulator HDF5 + ("TJ039", "pyFR", 14, "CH15"), # pyFR ]) - def test_eeg_reader(self, subject, index, channel, rhino_root): - reader = CMLReader(subject=subject, experiment='FR1', session=0, + def test_eeg_reader(self, subject, experiment, index, channel, rhino_root): + reader = CMLReader(subject=subject, experiment=experiment, session=0, rootdir=rhino_root) events = reader.load("events") events = events[events["type"] == "WORD"].iloc[:2] diff --git a/cmlreaders/test/test_readers.py b/cmlreaders/test/test_readers.py index e95211d..e785219 100644 --- a/cmlreaders/test/test_readers.py +++ b/cmlreaders/test/test_readers.py @@ -221,6 +221,7 @@ class TestEventReader: path = datafile(filename) df = EventReader.fromfile(path) assert df.columns[0] == "eegoffset" + assert "experiment" in df.columns assert len(df)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@2ffd443b75a0095a5c1edaaadf6e6e764c0e8a78#egg=cmlreaders codecov==2.1.13 coverage==6.2 cycler==0.11.0 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_readers.py::TestEventReader::test_load_matlab[all_events]", "cmlreaders/test/test_readers.py::TestEventReader::test_load_matlab[task_events]", "cmlreaders/test/test_readers.py::TestEventReader::test_load_matlab[math_events]" ]
[ "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader_missing_contacts", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1345D-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1363T-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1392N-PAL1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_rereference", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1298E-FR1-87-CH88]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1387E-FR1-13-CH14]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[TJ039-pyFR-14-CH15]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_read_whole_session[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1387E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1384J-pairs-False-43-LS12-LS1]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-pairs-True-43-LPOG23-LPOG31]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-contacts-True-43-LPOG44]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1286J-contacts-True-43-LJ16]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1384J-ind.region-insula-10-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1288P-ind.region-lateralorbitofrontal-5-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1111M-ind.region-middletemporal-18-100]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-True]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-False]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects0-experiments0]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects1-experiments1]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects2-experiments2]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_channel_discrepancies[R1387E-catFR5-0-120-125]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1405E-0-0-contacts]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1405E-0-0-pairs]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1006P-0-0-contacts]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1006P-0-0-pairs]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1006P-0-1-contacts]", "cmlreaders/test/test_readers.py::TestMontageReader::test_load[R1006P-0-1-pairs]", "cmlreaders/test/test_readers.py::TestElectrodeCategoriesReader::test_load[R1111M-lens0]", "cmlreaders/test/test_readers.py::TestElectrodeCategoriesReader::test_load[R1052E-lens1]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_as_methods[baseline_classifier-pyobject]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_as_methods[used_classifier-pyobject]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_to_methods[baseline_classifier-binary]", "cmlreaders/test/test_readers.py::TestClassifierContainerReader::test_to_methods[used_classifier-binary]" ]
[ "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[R1389J-sources.json-int16-1641165-1000]", "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[TJ001-TJ001_pyFR_params.txt-int16-None-400.0]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[True]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[False]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/contacts.json-contacts]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/pairs.json-pairs]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[-None]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_npy_reader", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[TJ001-TJ001_events.mat-expected_basenames0]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[R1389J-task_events.json-expected_basenames1]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[SplitEEGReader-True]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_with_empty_events", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-voxel_coordinates-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-classifier_excluded_leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-good_leads-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-jacksheet-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-dataframe]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-recarray]", "cmlreaders/test/test_readers.py::TestTextReader::test_as_methods[R1389J-0-area-dict]", "cmlreaders/test/test_readers.py::TestTextReader::test_read_jacksheet", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-voxel_coordinates-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-voxel_coordinates-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-classifier_excluded_leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-classifier_excluded_leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-good_leads-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-good_leads-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-jacksheet-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-jacksheet-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-area-json]", "cmlreaders/test/test_readers.py::TestTextReader::test_to_methods[R1389J-0-area-csv]", "cmlreaders/test/test_readers.py::TestTextReader::test_failures", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-electrode_coordinates-dataframe]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-electrode_coordinates-recarray]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-electrode_coordinates-dict]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-prior_stim_results-dataframe]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-prior_stim_results-recarray]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-prior_stim_results-dict]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-target_selection_table-dataframe]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-target_selection_table-recarray]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_as_methods[R1409D-0-target_selection_table-dict]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-electrode_coordinates-json]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-electrode_coordinates-csv]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-prior_stim_results-json]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-prior_stim_results-csv]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-target_selection_table-json]", "cmlreaders/test/test_readers.py::TestRAMCSVReader::test_to_methods[R1409D-0-target_selection_table-csv]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-dataframe]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-recarray]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_as_methods[R1409D-catFR1-1-event_log-dict]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_to_methods[R1409D-catFR1-1-event_log-json]", "cmlreaders/test/test_readers.py::TestRamulatorEventLogReader::test_to_methods[R1409D-catFR1-1-event_log-csv]", "cmlreaders/test/test_readers.py::TestBaseJSONReader::test_load", "cmlreaders/test/test_readers.py::TestEventReader::test_load_json", "cmlreaders/test/test_readers.py::TestLocalizationReader::test_load", "cmlreaders/test/test_readers.py::test_fromfile[ElectrodeCategoriesReader-/cmlreaders/cmlreaders/test/data/electrode_categories.txt-dict]", "cmlreaders/test/test_readers.py::test_fromfile[MontageReader-/cmlreaders/cmlreaders/test/data/pairs.json-DataFrame]", "cmlreaders/test/test_readers.py::test_fromfile[MontageReader-/cmlreaders/cmlreaders/test/data/contacts.json-DataFrame]", "cmlreaders/test/test_readers.py::test_fromfile[RamulatorEventLogReader-/cmlreaders/cmlreaders/test/data/event_log.json-DataFrame]" ]
[]
null
2,866
354
[ "cmlreaders/constants.py", "cmlreaders/readers/readers.py" ]
swaroopch__edn_format-43
7a3865c6d7ddc1a8d2d8ecb4114f11ed8b96fda8
2018-08-04 10:41:01
7a3865c6d7ddc1a8d2d8ecb4114f11ed8b96fda8
bfontaine: Note this doesn’t work with top-level `#_` usage: ```clojure ;; fails foo #_ bar ;; works [foo #_ bar] ``` We may want to fix this later. swaroopch: @bfontaine `Note this doesn’t work with top-level #_ usage` - is this valid syntax though? bfontaine: > `Note this doesn’t work with top-level #_ usage` - is this valid syntax though? The spec is not clear whether we can or not, but `clojure.edn` accepts it. It also accepts empty files even if we don’t know if [it’s valid EDN](https://github.com/edn-format/edn/issues/5). There are three basic cases I thought about: 1. `#_ value` → raise an EOF error 2. `#_ value1 value2` → parse as `value2` 3. `value1 #_ value2` → parse as `value1` I haven’t tested it yet but I guess changing the grammar like this should work: ```bnf root_expression = expression | discarded_expression | discarded_expressions expression | expression discarded_expressions ```
diff --git a/edn_format/edn_lex.py b/edn_format/edn_lex.py index ac0a3af..fc2026e 100644 --- a/edn_format/edn_lex.py +++ b/edn_format/edn_lex.py @@ -102,7 +102,8 @@ tokens = ('WHITESPACE', 'MAP_START', 'SET_START', 'MAP_OR_SET_END', - 'TAG') + 'TAG', + 'DISCARD_TAG') PARTS = {} PARTS["non_nums"] = r"\w.*+!\-_?$%&=:#<>@" @@ -138,7 +139,7 @@ KEYWORD = (":" "[{all}]+" ")").format(**PARTS) TAG = (r"\#" - r"\w" + r"[a-zA-Z]" # https://github.com/edn-format/edn/issues/30#issuecomment-8540641 "(" "[{all}]*" r"\/" @@ -147,6 +148,8 @@ TAG = (r"\#" "[{all}]*" ")").format(**PARTS) +DISCARD_TAG = r"\#\_" + t_VECTOR_START = r'\[' t_VECTOR_END = r'\]' t_LIST_START = r'\(' @@ -228,9 +231,10 @@ def t_COMMENT(t): pass # ignore -def t_DISCARD(t): - r'\#_\S+\b' - pass # ignore [email protected](DISCARD_TAG) +def t_DISCARD_TAG(t): + t.value = t.value[1:] + return t @ply.lex.TOKEN(TAG) diff --git a/edn_format/edn_parse.py b/edn_format/edn_parse.py index c2be09d..329584e 100644 --- a/edn_format/edn_parse.py +++ b/edn_format/edn_parse.py @@ -56,41 +56,21 @@ def p_term_leaf(p): p[0] = p[1] -def p_empty_vector(p): - """vector : VECTOR_START VECTOR_END""" - p[0] = ImmutableList([]) - - def p_vector(p): """vector : VECTOR_START expressions VECTOR_END""" p[0] = ImmutableList(p[2]) -def p_empty_list(p): - """list : LIST_START LIST_END""" - p[0] = tuple() - - def p_list(p): """list : LIST_START expressions LIST_END""" p[0] = tuple(p[2]) -def p_empty_set(p): - """set : SET_START MAP_OR_SET_END""" - p[0] = frozenset() - - def p_set(p): """set : SET_START expressions MAP_OR_SET_END""" p[0] = frozenset(p[2]) -def p_empty_map(p): - """map : MAP_START MAP_OR_SET_END""" - p[0] = ImmutableDict({}) - - def p_map(p): """map : MAP_START expressions MAP_OR_SET_END""" terms = p[2] @@ -100,14 +80,20 @@ def p_map(p): p[0] = ImmutableDict(dict([terms[i:i + 2] for i in range(0, len(terms), 2)])) -def p_expressions_expressions_expression(p): - """expressions : expressions expression""" - p[0] = p[1] + [p[2]] +def p_discarded_expressions(p): + """discarded_expressions : DISCARD_TAG expression discarded_expressions + |""" + p[0] = [] + +def p_expressions_expression_expressions(p): + """expressions : expression expressions""" + p[0] = [p[1]] + p[2] -def p_expressions_expression(p): - """expressions : expression""" - p[0] = [p[1]] + +def p_expressions_empty(p): + """expressions : discarded_expressions""" + p[0] = [] def p_expression(p): @@ -119,6 +105,11 @@ def p_expression(p): p[0] = p[1] +def p_expression_discard_expression_expression(p): + """expression : DISCARD_TAG expression expression""" + p[0] = p[3] + + def p_expression_tagged_element(p): """expression : TAG expression""" tag = p[1] @@ -144,9 +135,13 @@ def p_expression_tagged_element(p): p[0] = output +def eof(): + raise EDNDecodeError('EOF Reached') + + def p_error(p): if p is None: - raise EDNDecodeError('EOF Reached') + eof() else: raise EDNDecodeError(p)
not handling discard as expected `[x #_ y z]` should yield `[Symbol(x), Symbol(z)]` but instead it is failing saying: "Don't know how to handle tag _"
swaroopch/edn_format
diff --git a/tests.py b/tests.py index 8f7fcc1..29562d5 100644 --- a/tests.py +++ b/tests.py @@ -133,6 +133,12 @@ class EdnTest(unittest.TestCase): def check_roundtrip(self, data_input, **kw): self.assertEqual(data_input, loads(dumps(data_input, **kw))) + def check_eof(self, data_input, **kw): + with self.assertRaises(EDNDecodeError) as ctx: + loads(data_input, **kw) + + self.assertEqual('EOF Reached', str(ctx.exception)) + def test_dump(self): self.check_roundtrip({1, 2, 3}) self.check_roundtrip({1, 2, 3}, sort_sets=True) @@ -339,6 +345,57 @@ class EdnTest(unittest.TestCase): set(seq), sort_sets=True) + def test_discard(self): + for expected, edn_data in ( + ('[x]', '[x #_ z]'), + ('[z]', '[#_ x z]'), + ('[x z]', '[x #_ y z]'), + ('{1 4}', '{1 #_ 2 #_ 3 4}'), + ('[1 2]', '[1 #_ [ #_ [ #_ [ #_ [ #_ 42 ] ] ] ] 2 ]'), + ('[1 2 11]', '[1 2 #_ #_ #_ #_ 4 5 6 #_ 7 #_ #_ 8 9 10 11]'), + ('()', '(#_(((((((1))))))))'), + ('[6]', '[#_ #_ #_ #_ #_ 1 2 3 4 5 6]'), + ('[4]', '[#_ #_ 1 #_ 2 3 4]'), + ('{:a 1}', '{:a #_:b 1}'), + ('[42]', '[42 #_ {:a [1 2 3 4] true false 1 #inst "2017"}]'), + ('#{1}', '#{1 #_foo}'), + ('"#_ foo"', '"#_ foo"'), + ('["#" _]', '[\#_]'), + ('[_]', '[#_\#_]'), + ('[1]', '[1 #_\n\n42]'), + ('{}', '{#_ 1}'), + ): + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + + def test_discard_syntax_errors(self): + for edn_data in ('#_', '#_ #_ 1', '#inst #_ 2017', '[#_]'): + with self.assertRaises(EDNDecodeError): + loads(edn_data) + + def test_discard_all(self): + for edn_data in ( + '42', '-1', 'nil', 'true', 'false', '"foo"', '\\space', '\\a', + ':foo', ':foo/bar', '[]', '{}', '#{}', '()', '(a)', '(a b)', + '[a [[[b] c]] 2]', '#inst "2017"', + ): + self.assertEqual([1], loads('[1 #_ {}]'.format(edn_data)), edn_data) + self.assertEqual([1], loads('[#_ {} 1]'.format(edn_data)), edn_data) + + self.check_eof('#_ {}'.format(edn_data)) + + for coll in ('[%s]', '(%s)', '{%s}', '#{%s}'): + expected = coll % "" + edn_data = coll % '#_ {}'.format(edn_data) + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + + def test_chained_discards(self): + for expected, edn_data in ( + ('[]', '[#_ 1 #_ 2 #_ 3]'), + ('[]', '[#_ #_ 1 2 #_ 3]'), + ('[]', '[#_ #_ #_ 1 2 3]'), + ): + self.assertEqual(expected, dumps(loads(edn_data)), edn_data) + class EdnInstanceTest(unittest.TestCase): def test_hashing(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/swaroopch/edn_format.git@7a3865c6d7ddc1a8d2d8ecb4114f11ed8b96fda8#egg=edn_format importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 ply==3.11 py==1.11.0 pyparsing==3.1.4 pyRFC3339==2.0.1 pytest==7.0.1 pytz==2025.2 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: edn_format channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - ply==3.11 - py==1.11.0 - pyparsing==3.1.4 - pyrfc3339==2.0.1 - pytest==7.0.1 - pytz==2025.2 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/edn_format
[ "tests.py::EdnTest::test_chained_discards", "tests.py::EdnTest::test_discard", "tests.py::EdnTest::test_discard_all", "tests.py::EdnTest::test_discard_syntax_errors" ]
[]
[ "tests.py::ConsoleTest::test_dumping", "tests.py::EdnTest::test_chars", "tests.py::EdnTest::test_dump", "tests.py::EdnTest::test_exceptions", "tests.py::EdnTest::test_keyword_keys", "tests.py::EdnTest::test_lexer", "tests.py::EdnTest::test_parser", "tests.py::EdnTest::test_proper_unicode_escape", "tests.py::EdnTest::test_round_trip_conversion", "tests.py::EdnTest::test_round_trip_inst_short", "tests.py::EdnTest::test_round_trip_same", "tests.py::EdnTest::test_round_trip_sets", "tests.py::EdnTest::test_sort_keys", "tests.py::EdnTest::test_sort_sets", "tests.py::EdnInstanceTest::test_equality", "tests.py::EdnInstanceTest::test_hashing", "tests.py::ImmutableListTest::test_list" ]
[]
Apache License 2.0
2,872
1,137
[ "edn_format/edn_lex.py", "edn_format/edn_parse.py" ]
python-metar__python-metar-45
b9e9aec2a429d2512ec931ce8cf6b281abacc5e5
2018-08-06 14:29:56
94a48ea3b965ed1b38c5ab52553dd4cbcc23867c
diff --git a/metar/Metar.py b/metar/Metar.py index 338e172..c089afb 100755 --- a/metar/Metar.py +++ b/metar/Metar.py @@ -1216,12 +1216,14 @@ class Metar(object): what = "clouds" else: what = "" + label = "%s %s" % (SKY_COVER[cover], what) + # HACK here to account for 'empty' entries with above format + label = " ".join(label.strip().split()) if cover == "VV": - text_list.append("%s%s, vertical visibility to %s" % - (SKY_COVER[cover],what,str(height))) + label += ", vertical visibility to %s" % (str(height), ) else: - text_list.append("%s%s at %s" % - (SKY_COVER[cover],what,str(height))) + label += " at %s" % (str(height), ) + text_list.append(label) return sep.join(text_list) def trend( self ):
Spacing issue sky: overcastcumulonimbus at 1000 feet should read sky: overcast^cumulonimbus at 1000 feet
python-metar/python-metar
diff --git a/test/test_metar.py b/test/test_metar.py index e6c8fee..990b7b0 100644 --- a/test/test_metar.py +++ b/test/test_metar.py @@ -457,6 +457,9 @@ class MetarTest(unittest.TestCase): self.assertEqual( report('SCT030').sky_conditions(), 'scattered clouds at 3000 feet' ) self.assertEqual( report('BKN001').sky_conditions(), 'broken clouds at 100 feet' ) self.assertEqual( report('OVC008').sky_conditions(), 'overcast at 800 feet' ) + self.assertEqual( + report('OVC010CB').sky_conditions(), 'overcast cumulonimbus at 1000 feet' + ) self.assertEqual( report('SCT020TCU').sky_conditions(), 'scattered towering cumulus at 2000 feet' ) self.assertEqual( report('BKN015CB').sky_conditions(), 'broken cumulonimbus at 1500 feet' ) self.assertEqual( report('FEW030').sky_conditions(), 'a few clouds at 3000 feet' )
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coveralls", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/python-metar/python-metar.git@b9e9aec2a429d2512ec931ce8cf6b281abacc5e5#egg=metar more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 requests==2.27.1 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: python-metar channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - docopt==0.6.2 - idna==3.10 - nose==1.3.7 - requests==2.27.1 - urllib3==1.26.20 prefix: /opt/conda/envs/python-metar
[ "test/test_metar.py::MetarTest::test_310_parse_sky_conditions" ]
[]
[ "test/test_metar.py::MetarTest::test_010_parseType_default", "test/test_metar.py::MetarTest::test_011_parseType_legal", "test/test_metar.py::MetarTest::test_020_parseStation_legal", "test/test_metar.py::MetarTest::test_021_parseStation_illegal", "test/test_metar.py::MetarTest::test_030_parseTime_legal", "test/test_metar.py::MetarTest::test_031_parseTime_specify_year", "test/test_metar.py::MetarTest::test_032_parseTime_specify_month", "test/test_metar.py::MetarTest::test_033_parseTime_auto_month", "test/test_metar.py::MetarTest::test_034_parseTime_auto_year", "test/test_metar.py::MetarTest::test_035_parseTime_suppress_auto_month", "test/test_metar.py::MetarTest::test_040_parseModifier_default", "test/test_metar.py::MetarTest::test_041_parseModifier", "test/test_metar.py::MetarTest::test_042_parseModifier_nonstd", "test/test_metar.py::MetarTest::test_043_parseModifier_illegal", "test/test_metar.py::MetarTest::test_140_parseWind", "test/test_metar.py::MetarTest::test_141_parseWind_nonstd", "test/test_metar.py::MetarTest::test_142_parseWind_illegal", "test/test_metar.py::MetarTest::test_150_parseVisibility", "test/test_metar.py::MetarTest::test_151_parseVisibility_direction", "test/test_metar.py::MetarTest::test_152_parseVisibility_with_following_temperature", "test/test_metar.py::MetarTest::test_290_ranway_state", "test/test_metar.py::MetarTest::test_300_parseTrend", "test/test_metar.py::MetarTest::test_issue40_runwayunits", "test/test_metar.py::MetarTest::test_not_strict_mode", "test/test_metar.py::MetarTest::test_snowdepth" ]
[]
BSD License
2,877
267
[ "metar/Metar.py" ]
mahmoud__glom-49
917343ee7d3576a7497ec348f6fb2e94d239acb0
2018-08-08 03:00:19
917343ee7d3576a7497ec348f6fb2e94d239acb0
diff --git a/glom/core.py b/glom/core.py index 69ae4dc..9cbd27b 100644 --- a/glom/core.py +++ b/glom/core.py @@ -721,6 +721,12 @@ class _TType(object): def __repr__(self): return _format_t(_T_PATHS[self][1:]) + def __getstate__(self): + return tuple(_T_PATHS[self]) + + def __setstate__(self, state): + _T_PATHS[self] = state + def _format_t(path): def kwarg_fmt(kw):
KeyError in _t_child from weakref I'm running into a weird issue using glom in PySpark on Databricks. This expression: `glom(ping, (T[stub]["values"].values(), sum), default=0)` (where `stub` is `"a11y_time"`) is consistently throwing this exception when I run it on my real data: ``` /databricks/spark/python/lib/py4j-0.10.6-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 raise Py4JJavaError( 319 "An error occurred while calling {0}{1}{2}.\n". --> 320 format(target_id, ".", name), value) 321 else: 322 raise Py4JError( Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 22.0 failed 4 times, most recent failure: Lost task 0.3 in stage 22.0 (TID 243, 10.166.248.213, executor 2): org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/databricks/spark/python/pyspark/worker.py", line 229, in main process() File "/databricks/spark/python/pyspark/worker.py", line 224, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/databricks/spark/python/pyspark/serializers.py", line 372, in dump_stream vs = list(itertools.islice(iterator, batch)) File "/databricks/spark/python/pyspark/rdd.py", line 1354, in takeUpToNumLeft yield next(iterator) File "<command-26292>", line 10, in to_row File "<command-26292>", line 5, in histogram_measures File "/databricks/python/local/lib/python2.7/site-packages/glom/core.py", line 753, in __getitem__ return _t_child(self, '[', item) File "/databricks/python/local/lib/python2.7/site-packages/glom/core.py", line 791, in _t_child _T_PATHS[t] = _T_PATHS[parent] + (operation, arg) File "/usr/lib/python2.7/weakref.py", line 330, in __getitem__ return self.data[ref(key)] KeyError: <weakref at 0x7f84c7d2f6d8; to '_TType' at 0x7f84c8933f30> ``` The object that's crashing it is, itself, totally unremarkable: `{'submission_date': u'20180718', 'a11y_count': None, 'a11y_node_inspected_count': None, 'a11y_service_time': None, 'toolbox_time': None, 'toolbox_count': None, 'a11y_time': None, 'branch': u'Treatment', 'client_id': u'some-random-uuid', 'a11y_picker_time': None, 'a11y_select_accessible_for_node': None} ` The Python that Databricks is running looks like `2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609]`. I can't reproduce it on my Mac in 2.7.14 or 2.7.12.
mahmoud/glom
diff --git a/glom/test/test_path_and_t.py b/glom/test/test_path_and_t.py index 394525f..614899f 100644 --- a/glom/test/test_path_and_t.py +++ b/glom/test/test_path_and_t.py @@ -69,3 +69,19 @@ def test_path_access_error_message(): assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" in exc_info.exconly()) assert repr(exc_info.value) == """PathAccessError(AttributeError("\'dict\' object has no attribute \'b\'",), Path(\'a\', T.b), 1)""" + + +def test_t_picklability(): + import pickle + + class TargetType(object): + def __init__(self): + self.attribute = lambda: None + self.attribute.method = lambda: {'key': lambda x: x * 2} + + spec = T.attribute.method()['key'](x=5) + + rt_spec = pickle.loads(pickle.dumps(spec)) + assert repr(spec) == repr(rt_spec) + + assert glom(TargetType(), spec) == 10
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
18.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "coverage" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 boltons==25.0.0 coverage==7.8.0 exceptiongroup==1.2.2 face==24.0.0 -e git+https://github.com/mahmoud/glom.git@917343ee7d3576a7497ec348f6fb2e94d239acb0#egg=glom iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: glom channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - boltons==25.0.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - face==24.0.0 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/glom
[ "glom/test/test_path_and_t.py::test_t_picklability" ]
[ "glom/test/test_path_and_t.py::test_path_access_error_message" ]
[ "glom/test/test_path_and_t.py::test_list_path_access", "glom/test/test_path_and_t.py::test_path", "glom/test/test_path_and_t.py::test_empty_path_access", "glom/test/test_path_and_t.py::test_path_t_roundtrip" ]
[]
BSD 3-Clause License
2,885
149
[ "glom/core.py" ]
pypa__setuptools_scm-299
3ae1cad231545abfeedea9aaa7405e15fb28d95c
2018-08-08 09:26:04
3ae1cad231545abfeedea9aaa7405e15fb28d95c
diff --git a/src/setuptools_scm/file_finder_git.py b/src/setuptools_scm/file_finder_git.py index d886d06..b7b55ed 100644 --- a/src/setuptools_scm/file_finder_git.py +++ b/src/setuptools_scm/file_finder_git.py @@ -1,8 +1,11 @@ import os import subprocess import tarfile - +import logging from .file_finder import scm_find_files +from .utils import trace + +log = logging.getLogger(__name__) def _git_toplevel(path): @@ -14,6 +17,7 @@ def _git_toplevel(path): universal_newlines=True, stderr=devnull, ) + trace("find files toplevel", out) return os.path.normcase(os.path.realpath(out.strip())) except subprocess.CalledProcessError: # git returned error, we are not in a git repo @@ -23,12 +27,8 @@ def _git_toplevel(path): return None -def _git_ls_files_and_dirs(toplevel): - # use git archive instead of git ls-file to honor - # export-ignore git attribute - cmd = ["git", "archive", "--prefix", toplevel + os.path.sep, "HEAD"] - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) - tf = tarfile.open(fileobj=proc.stdout, mode="r|*") +def _git_interpret_archive(fd, toplevel): + tf = tarfile.open(fileobj=fd, mode="r|*") git_files = set() git_dirs = {toplevel} for member in tf.getmembers(): @@ -40,6 +40,19 @@ def _git_ls_files_and_dirs(toplevel): return git_files, git_dirs +def _git_ls_files_and_dirs(toplevel): + # use git archive instead of git ls-file to honor + # export-ignore git attribute + cmd = ["git", "archive", "--prefix", toplevel + os.path.sep, "HEAD"] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=toplevel) + try: + return _git_interpret_archive(proc.stdout, toplevel) + except Exception: + if proc.wait() != 0: + log.exception("listing git files failed - pretending there aren't any") + return (), () + + def git_find_files(path=""): toplevel = _git_toplevel(path) if not toplevel:
tarfile.ReadError: empty file - in filefinder on no commits ``` /usr/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'test_requires' warnings.warn(msg) /home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/version.py:191: UserWarning: meta invoked without explicit configuration, will use defaults where required. "meta invoked without explicit configuration," running egg_info writing rio_redis.egg-info/PKG-INFO writing dependency_links to rio_redis.egg-info/dependency_links.txt writing requirements to rio_redis.egg-info/requires.txt writing top-level names to rio_redis.egg-info/top_level.txt fatal: Not a valid object name Traceback (most recent call last): File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 2287, in next tarinfo = self.tarinfo.fromtarfile(self) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1093, in fromtarfile obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1029, in frombuf raise EmptyHeaderError("empty header") tarfile.EmptyHeaderError: empty header During handling of the above exception, another exception occurred: Traceback (most recent call last): File "setup.py", line 39, in <module> python_requires=">=3.6.0", File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/__init__.py", line 131, in setup return distutils.core.setup(**attrs) File "/usr/lib64/python3.7/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib64/python3.7/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/usr/lib64/python3.7/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 278, in run self.find_sources() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 293, in find_sources mm.run() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 524, in run self.add_defaults() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/egg_info.py", line 563, in add_defaults rcfiles = list(walk_revctrl()) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/site-packages/setuptools/command/sdist.py", line 20, in walk_revctrl for item in ep.load()(dirname): File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/integration.py", line 33, in find_files res = command(path) File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/file_finder_git.py", line 47, in git_find_files git_files, git_dirs = _git_ls_files_and_dirs(toplevel) File "/home/laura/dev/libs/rio-redis/.eggs/setuptools_scm-3.0.6-py3.7.egg/setuptools_scm/file_finder_git.py", line 31, in _git_ls_files_and_dirs tf = tarfile.open(fileobj=proc.stdout, mode="r|*") File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1601, in open t = cls(name, filemode, stream, **kwargs) File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 1482, in __init__ self.firstmember = self.next() File "/home/laura/.local/share/virtualenvs/rio-redis-wQCA5cC-/lib/python3.7/tarfile.py", line 2302, in next raise ReadError("empty file") tarfile.ReadError: empty file ```
pypa/setuptools_scm
diff --git a/testing/test_git.py b/testing/test_git.py index d854a7c..f498db0 100644 --- a/testing/test_git.py +++ b/testing/test_git.py @@ -4,6 +4,7 @@ from setuptools_scm import git import pytest from datetime import date from os.path import join as opj +from setuptools_scm.file_finder_git import git_find_files @pytest.fixture @@ -28,6 +29,14 @@ def test_parse_describe_output(given, tag, number, node, dirty): assert parsed == (tag, number, node, dirty) [email protected]("https://github.com/pypa/setuptools_scm/issues/298") +def test_file_finder_no_history(wd, caplog): + file_list = git_find_files(str(wd.cwd)) + assert file_list == [] + + assert "listing git files failed - pretending there aren't any" in caplog.text + + @pytest.mark.issue("https://github.com/pypa/setuptools_scm/issues/281") def test_parse_call_order(wd): git.parse(str(wd.cwd), git.DEFAULT_DESCRIBE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "python setup.py egg_info" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 -e git+https://github.com/pypa/setuptools_scm.git@3ae1cad231545abfeedea9aaa7405e15fb28d95c#egg=setuptools_scm tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: setuptools_scm channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/setuptools_scm
[ "testing/test_git.py::test_file_finder_no_history" ]
[]
[ "testing/test_git.py::test_parse_describe_output[3.3.1-rc26-0-g9df187b-3.3.1-rc26-0-g9df187b-False]", "testing/test_git.py::test_parse_describe_output[17.33.0-rc-17-g38c3047c0-17.33.0-rc-17-g38c3047c0-False]", "testing/test_git.py::test_parse_call_order", "testing/test_git.py::test_version_from_git", "testing/test_git.py::test_unicode_version_scheme", "testing/test_git.py::test_git_worktree", "testing/test_git.py::test_git_dirty_notag", "testing/test_git.py::test_git_parse_shallow_warns", "testing/test_git.py::test_git_parse_shallow_fail", "testing/test_git.py::test_git_shallow_autocorrect", "testing/test_git.py::test_find_files_stop_at_root_git", "testing/test_git.py::test_parse_no_worktree", "testing/test_git.py::test_alphanumeric_tags_match", "testing/test_git.py::test_git_archive_export_ignore", "testing/test_git.py::test_git_archive_subdirectory", "testing/test_git.py::test_git_archive_run_from_subdirectory", "testing/test_git.py::test_git_feature_branch_increments_major" ]
[]
MIT License
2,886
558
[ "src/setuptools_scm/file_finder_git.py" ]
cloudtools__stacker-646
0a5652a7580232a701b6abb984537b941a446ee0
2018-08-08 18:16:01
cd379d01f089c226e347c256abe75b90268ae144
diff --git a/stacker/lookups/handlers/file.py b/stacker/lookups/handlers/file.py index 2ea8893..a57af66 100644 --- a/stacker/lookups/handlers/file.py +++ b/stacker/lookups/handlers/file.py @@ -136,7 +136,7 @@ def _parameterize_string(raw): s_index = match.end() if not parts: - return raw + return GenericHelperFn(raw) parts.append(raw[s_index:]) return GenericHelperFn({u"Fn::Join": [u"", parts]}) @@ -152,7 +152,7 @@ def parameterized_codec(raw, b64): call Returns: - :class:`troposphere.GenericHelperFn`: output to be included in a + :class:`troposphere.AWSHelperFn`: output to be included in a CloudFormation template. """ diff --git a/stacker/providers/aws/default.py b/stacker/providers/aws/default.py index 1c47ecd..369d0b9 100644 --- a/stacker/providers/aws/default.py +++ b/stacker/providers/aws/default.py @@ -825,9 +825,17 @@ class Provider(BaseProvider): self.cloudformation, fqn, template, parameters, tags, 'UPDATE', service_role=self.service_role, **kwargs ) + old_parameters_as_dict = self.params_as_dict(old_parameters) + new_parameters_as_dict = self.params_as_dict( + [x + if x.get('ParameterValue') + else {'ParameterKey': x['ParameterKey'], + 'ParameterValue': old_parameters_as_dict[x['ParameterKey']]} + for x in parameters] + ) params_diff = diff_parameters( - self.params_as_dict(old_parameters), - self.params_as_dict(parameters)) + old_parameters_as_dict, + new_parameters_as_dict) action = "replacements" if self.replacements_only else "changes" full_changeset = changes
file lookup returning <type 'unicode'> where it previously returned <class 'troposphere.AWSHelperFn'> As of 1.4.0, the use of the `${file parameterized }` lookup no longer works with blueprints using variable type of `troposphere.AWSHelperFn`. This was working in previous versions - most recently 1.3.0. ### Error ``` File "/usr/local/lib/python2.7/site-packages/stacker/plan.py", line 93, in _run_once status = self.fn(self.stack, status=self.status) File "/usr/local/lib/python2.7/site-packages/stacker/actions/build.py", line 321, in _launch_stack stack.resolve(self.context, self.provider) File "/usr/local/lib/python2.7/site-packages/stacker/stack.py", line 196, in resolve self.blueprint.resolve_variables(self.variables) File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 452, in resolve_variables self.name File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 226, in resolve_variable value = validate_variable_type(var_name, var_type, value) File "/usr/local/lib/python2.7/site-packages/stacker/blueprints/base.py", line 147, in validate_variable_type "type: %s." % (var_name, var_type, type(value)) ValueError: Value for variable ExampleParameter must be of type <class 'troposphere.AWSHelperFn'>. Actual type: <type 'unicode'>. ``` ### System Information **Operating System:** Mac OS X 10.13.6 build 17G65 **Python Version:** 2.7.14 **Stacker Version:** 1.4.0 ### Files ``` ├── top-level-folder │ ├── blueprints │ │ ├── __init__.py │ │ └── example_blueprint.py │ ├── file-to-reference.json │ ├── example.env │ └── stacker-config.yaml ``` #### stacker-config.yaml ``` namespace: example stacker_bucket: "" sys_path: ./ stacks: example-stack: class_path: blueprints.example_blueprint.BlueprintClass enabled: true variables: ExampleParameter: ${file parameterized:file://file-to-reference.json} ``` #### blueprints/example_blueprint.py ```python from troposphere import AWSHelperFn from stacker.blueprints.base import Blueprint class BlueprintClass(Blueprint): VARIABLES = { 'ExampleParameter': { 'type': AWSHelperFn } } ```
cloudtools/stacker
diff --git a/stacker/tests/lookups/handlers/test_file.py b/stacker/tests/lookups/handlers/test_file.py index c2eb93f..312f71a 100644 --- a/stacker/tests/lookups/handlers/test_file.py +++ b/stacker/tests/lookups/handlers/test_file.py @@ -9,7 +9,7 @@ import mock import base64 import yaml import json -from troposphere import Base64, Join +from troposphere import Base64, GenericHelperFn, Join from stacker.lookups.handlers.file import (json_codec, handler, parameterized_codec, yaml_codec) @@ -46,12 +46,21 @@ class TestFileTranslator(unittest.TestCase): ) out = parameterized_codec(u'Test {{Interpolation}} Here', True) + self.assertEqual(Base64, out.__class__) self.assertTemplateEqual(expected, out) def test_parameterized_codec_plain(self): expected = Join(u'', [u'Test ', {u'Ref': u'Interpolation'}, u' Here']) out = parameterized_codec(u'Test {{Interpolation}} Here', False) + self.assertEqual(GenericHelperFn, out.__class__) + self.assertTemplateEqual(expected, out) + + def test_parameterized_codec_plain_no_interpolation(self): + expected = u'Test Without Interpolation Here' + + out = parameterized_codec(u'Test Without Interpolation Here', False) + self.assertEqual(GenericHelperFn, out.__class__) self.assertTemplateEqual(expected, out) def test_yaml_codec_raw(self):
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "moto", "testfixtures", "flake8", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
awacs==2.5.0 boto3==1.37.23 botocore==1.37.23 certifi==2025.1.31 cffi==1.17.1 cfn-flip==1.3.0 charset-normalizer==3.4.1 click==8.1.8 cryptography==44.0.2 exceptiongroup==1.2.2 flake8==7.2.0 formic2==1.0.3 future==1.0.0 gitdb2==2.0.6 GitPython==2.1.15 idna==3.10 iniconfig==2.1.0 Jinja2==3.1.6 jmespath==1.0.1 MarkupSafe==3.0.2 mccabe==0.7.0 mock==5.2.0 moto==5.1.2 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pycparser==2.22 pyflakes==3.3.2 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 responses==0.25.7 s3transfer==0.11.4 schematics==2.0.1 six==1.17.0 smmap==5.0.2 smmap2==3.0.1 -e git+https://github.com/cloudtools/stacker.git@0a5652a7580232a701b6abb984537b941a446ee0#egg=stacker testfixtures==8.3.0 tomli==2.2.1 troposphere==4.9.0 urllib3==1.26.20 Werkzeug==3.1.3 xmltodict==0.14.2
name: stacker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - awacs==2.5.0 - boto3==1.37.23 - botocore==1.37.23 - certifi==2025.1.31 - cffi==1.17.1 - cfn-flip==1.3.0 - charset-normalizer==3.4.1 - click==8.1.8 - cryptography==44.0.2 - exceptiongroup==1.2.2 - flake8==7.2.0 - formic2==1.0.3 - future==1.0.0 - gitdb2==2.0.6 - gitpython==2.1.15 - idna==3.10 - iniconfig==2.1.0 - jinja2==3.1.6 - jmespath==1.0.1 - markupsafe==3.0.2 - mccabe==0.7.0 - mock==5.2.0 - moto==5.1.2 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pycparser==2.22 - pyflakes==3.3.2 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - responses==0.25.7 - s3transfer==0.11.4 - schematics==2.0.1 - six==1.17.0 - smmap==5.0.2 - smmap2==3.0.1 - testfixtures==8.3.0 - tomli==2.2.1 - troposphere==4.9.0 - urllib3==1.26.20 - werkzeug==3.1.3 - xmltodict==0.14.2 prefix: /opt/conda/envs/stacker
[ "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_plain_no_interpolation" ]
[]
[ "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_file_loaded", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_json", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_json_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_parameterized_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_plain", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_yaml", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_handler_yaml_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_json_codec_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_json_codec_raw", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_b64", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_parameterized_codec_plain", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_unknown_codec", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_yaml_codec_parameterized", "stacker/tests/lookups/handlers/test_file.py::TestFileTranslator::test_yaml_codec_raw" ]
[]
BSD 2-Clause "Simplified" License
2,888
477
[ "stacker/lookups/handlers/file.py", "stacker/providers/aws/default.py" ]
HECBioSim__Longbow-111
c81fcaccfa7fb2dc147e40970ef806dc6d6b22a4
2018-08-09 10:27:25
c81fcaccfa7fb2dc147e40970ef806dc6d6b22a4
diff --git a/longbow/configuration.py b/longbow/configuration.py index bd12c87..2426df1 100644 --- a/longbow/configuration.py +++ b/longbow/configuration.py @@ -93,29 +93,30 @@ JOBTEMPLATE = { "host": "", "localworkdir": "", "lsf-cluster": "", - "modules": "", "maxtime": "24:00", "memory": "", + "modules": "", + "mpiprocs": "", "polling-frequency": "300", "port": "22", "queue": "", "recoveryfile": "", "remoteworkdir": "", - "resource": "", "replicates": "1", "replicate-naming": "rep", + "resource": "", "scheduler": "", "scripts": "", + "sge-peflag": "mpi", + "sge-peoverride": "false", "slurm-gres": "", "staging-frequency": "300", "stdout": "", "stderr": "", - "sge-peflag": "mpi", - "sge-peoverride": "false", "subfile": "", - "user": "", "upload-exclude": "", - "upload-include": "" + "upload-include": "", + "user": "" } @@ -505,6 +506,7 @@ def _processconfigsresource(parameters, jobdata, hostsections): # Initialise jobs = {} + # Process resource/s for job/s. for job in jobdata: diff --git a/longbow/entrypoints.py b/longbow/entrypoints.py index 140d583..8fc1bf0 100644 --- a/longbow/entrypoints.py +++ b/longbow/entrypoints.py @@ -415,8 +415,7 @@ def recovery(jobs, recoveryfile): _, _, jobparams = configuration.loadconfigs(jobfile) - # Copy to jobs so when exceptions are raised the structure is - # available. + # Copy to jobs so when exceptions are raised the structure is available. for param in jobparams: jobs[param] = jobparams[param] @@ -454,8 +453,7 @@ def update(jobs, updatefile): _, _, jobparams = configuration.loadconfigs(jobfile) - # Copy to jobs so when exceptions are raised the structure is - # available. + # Copy to jobs so when exceptions are raised the structure is available. for param in jobparams: jobs[param] = jobparams[param] diff --git a/longbow/schedulers/pbs.py b/longbow/schedulers/pbs.py index 4449614..daaffca 100644 --- a/longbow/schedulers/pbs.py +++ b/longbow/schedulers/pbs.py @@ -108,30 +108,23 @@ def prepare(job): jobfile.write("#PBS " + job["accountflag"] + " " + job["account"] + "\n") + processes = job["cores"] cpn = job["corespernode"] + mpiprocs = job["mpiprocs"] - cores = job["cores"] + # If not undersubscribing then. + if mpiprocs == "" and processes < cpn: - # Load levelling override. In cases where # of cores is less than - # corespernode, user is likely to be undersubscribing. - if int(cores) < int(cpn): + mpiprocs = processes - cpn = cores + elif mpiprocs == "": - # Calculate the number of nodes. - nodes = float(cores) / float(cpn) - - # Makes sure nodes is rounded up to the next highest integer. - nodes = str(int(math.ceil(nodes))) + mpiprocs = cpn - # Number of cpus per node (most machines will charge for all available cpus - # per node whether you are using them or not) - ncpus = cpn - - # Number of mpi processes per node. - mpiprocs = cpn + # Calculate the number of nodes. + nodes = str(int(math.ceil(float(processes) / float(mpiprocs)))) - tmp = "select=" + nodes + ":ncpus=" + ncpus + ":mpiprocs=" + mpiprocs + tmp = "select=" + nodes + ":ncpus=" + cpn + ":mpiprocs=" + mpiprocs # If user has specified memory append the flag (not all machines support # this). @@ -203,7 +196,7 @@ def prepare(job): # CRAY's use aprun which has slightly different requirements to mpirun. if mpirun == "aprun": - mpirun = mpirun + " -n " + cores + " -N " + mpiprocs + mpirun = mpirun + " -n " + processes + " -N " + mpiprocs # Single jobs only need one run command. if int(job["replicates"]) == 1: diff --git a/longbow/scheduling.py b/longbow/scheduling.py index 4153bff..385af73 100644 --- a/longbow/scheduling.py +++ b/longbow/scheduling.py @@ -329,8 +329,7 @@ def prepare(jobs): LOG.info("For job '%s' user has supplied their own job submit " "script - skipping creation.", item) - job["upload-include"] = (job["upload-include"] + ", " + - job["subfile"]) + job["upload-include"] = job["upload-include"] + ", " + job["subfile"] except AttributeError:
PBS and NAMD SMP On ARCHER, NAMD jobs with SMP have intermittent difficulties with the ncpus and/or mpiprocs directive to "-l". This should be investigated, further. It appears to stem from the corespernode needing to be set at 1 which also sets ncpus to 1.There are several possibilities here: 1. A return to defaulting to not issuing ncpus or mpiprocs with the "-l" command and allowing users to specify if they are necessary or not as whether these are needed or not varies machine to machine. 2. Another consideration is to see if there is actually something that is missing with these NAMD jobs that would let Longbow correctly assign ncpus ie -d to aprun. 3. Another solution is to have corespernode and mpiprocs as seperate parameters such that mpiprocs defaults to corespernode unless mpiprocs states otherwise. This should provide a better way to calculate ncpus from corespernode and mpiprocs (most users won't need to worry about it, just those using NAMD or those that wish to undersubscribe nodes).
HECBioSim/Longbow
diff --git a/tests/standards/pbs_submitfiles/case11.txt b/tests/standards/pbs_submitfiles/case11.txt new file mode 100644 index 0000000..d8c2843 --- /dev/null +++ b/tests/standards/pbs_submitfiles/case11.txt @@ -0,0 +1,13 @@ +#!/bin/bash --login +#PBS -N testjob +#PBS -q debug +#PBS -l select=2:ncpus=24:mpiprocs=1 +#PBS -l walltime=24:00:00 + +export PBS_O_WORKDIR=$(readlink -f $PBS_O_WORKDIR) +cd $PBS_O_WORKDIR +export OMP_NUM_THREADS=1 + +module load namd + +aprun -n 2 -N 1 namd2 +ppn 23 +pemap 1-23 +commap 0 bench.in > bench.log diff --git a/tests/standards/pbs_submitfiles/case3.txt b/tests/standards/pbs_submitfiles/case3.txt index 686c7e8..fdac9e4 100644 --- a/tests/standards/pbs_submitfiles/case3.txt +++ b/tests/standards/pbs_submitfiles/case3.txt @@ -1,7 +1,7 @@ #!/bin/bash --login #PBS -N testjob #PBS -q debug -#PBS -l select=1:ncpus=16:mpiprocs=16 +#PBS -l select=1:ncpus=24:mpiprocs=16 #PBS -l walltime=24:00:00 export PBS_O_WORKDIR=$(readlink -f $PBS_O_WORKDIR) diff --git a/tests/unit/configuration/test_processconfigsresource.py b/tests/unit/configuration/test_processconfigsresource.py index db0f1fc..cda1424 100644 --- a/tests/unit/configuration/test_processconfigsresource.py +++ b/tests/unit/configuration/test_processconfigsresource.py @@ -119,6 +119,7 @@ def test_processconfigsresource1(): "modules": "", "maxtime": "24:00", "memory": "", + "mpiprocs": "", "nochecks": False, "scripts": "", "slurm-gres": "", @@ -232,6 +233,7 @@ def test_processconfigsresource2(): "modules": "", "maxtime": "24:00", "memory": "", + "mpiprocs": "", "nochecks": False, "scripts": "", "slurm-gres": "", @@ -345,6 +347,7 @@ def test_processconfigsresource3(): "modules": "", "maxtime": "24:00", "memory": "", + "mpiprocs": "", "nochecks": False, "scripts": "", "slurm-gres": "", @@ -457,6 +460,7 @@ def test_processconfigsresource4(): "modules": "", "maxtime": "24:00", "memory": "", + "mpiprocs": "", "nochecks": False, "scripts": "", "slurm-gres": "", diff --git a/tests/unit/schedulers_pbs/test_pbs_prepare.py b/tests/unit/schedulers_pbs/test_pbs_prepare.py index b8b04f9..c3e390a 100644 --- a/tests/unit/schedulers_pbs/test_pbs_prepare.py +++ b/tests/unit/schedulers_pbs/test_pbs_prepare.py @@ -58,6 +58,7 @@ def test_prepare_case1(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -96,6 +97,7 @@ def test_prepare_case2(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "5", "stdout": "", @@ -132,6 +134,7 @@ def test_prepare_case3(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -169,6 +172,7 @@ def test_prepare_case4(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -206,6 +210,7 @@ def test_prepare_case5(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -243,6 +248,7 @@ def test_prepare_case6(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -280,6 +286,7 @@ def test_prepare_case7(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -317,6 +324,7 @@ def test_prepare_case8(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -354,6 +362,7 @@ def test_prepare_case9(): "maxtime": "24:00", "memory": "8", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "", @@ -390,6 +399,7 @@ def test_prepare_case10(): "maxtime": "24:00", "memory": "", "modules": "amber", + "mpiprocs": "", "queue": "debug", "replicates": "1", "stdout": "test.log", @@ -406,3 +416,41 @@ def test_prepare_case10(): os.path.join( os.getcwd(), "tests/standards/pbs_submitfiles/case10.txt"), "rb").read() + + +def test_prepare_case11(): + + """ + Test SMP type + """ + + job = { + "account": "", + "cluster": "cluster1", + "cores": "2", + "corespernode": "24", + "executableargs": ("namd2 +ppn 23 +pemap 1-23 +commap 0 " + + "bench.in > bench.log"), + "handler": "aprun", + "email-address": "", + "email-flags": "", + "jobname": "testjob", + "localworkdir": "/tmp", + "maxtime": "24:00", + "memory": "", + "modules": "namd", + "mpiprocs": "1", + "queue": "debug", + "replicates": "1", + "stdout": "", + "stderr": "", + "scripts": "", + "upload-include": "file1, file2" + } + + prepare(job) + + assert open("/tmp/submit.pbs", "rb").read() == open( + os.path.join( + os.getcwd(), + "tests/standards/pbs_submitfiles/case11.txt"), "rb").read()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 4 }
.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/HECBioSim/Longbow.git@c81fcaccfa7fb2dc147e40970ef806dc6d6b22a4#egg=Longbow packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: Longbow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/Longbow
[ "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case3", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case11" ]
[]
[ "tests/unit/configuration/test_processconfigsresource.py::test_processconfigsresource1", "tests/unit/configuration/test_processconfigsresource.py::test_processconfigsresource2", "tests/unit/configuration/test_processconfigsresource.py::test_processconfigsresource3", "tests/unit/configuration/test_processconfigsresource.py::test_processconfigsresource4", "tests/unit/configuration/test_processconfigsresource.py::test_processconfigsresource5", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case1", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case2", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case4", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case5", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case6", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case7", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case8", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case9", "tests/unit/schedulers_pbs/test_pbs_prepare.py::test_prepare_case10" ]
[]
BSD 3-Clause License
2,892
1,374
[ "longbow/configuration.py", "longbow/entrypoints.py", "longbow/schedulers/pbs.py", "longbow/scheduling.py" ]
Backblaze__B2_Command_Line_Tool-488
4154652165dd475d79de606abd70b6debc4596d4
2018-08-09 15:22:12
6d1ff3c30dc9c14d6999da7161483b5fbbf7a48b
diff --git a/b2/api.py b/b2/api.py index 017f5ba..a1400e1 100644 --- a/b2/api.py +++ b/b2/api.py @@ -205,20 +205,27 @@ class B2Api(object): def get_bucket_by_name(self, bucket_name): """ - Returns the bucket_id for the given bucket_name. + Returns the Bucket for the given bucket_name. - If we don't already know it from the cache, try fetching it from - the B2 service. + :param bucket_name: The name of the bucket to return. + :return: a Bucket object + :raises NonExistentBucket: if the bucket does not exist in the account """ - # If we can get it from the stored info, do that. + # Give a useful warning if the current application key does not + # allow access to the named bucket. self.check_bucket_restrictions(bucket_name) + + # First, try the cache. id_ = self.cache.get_bucket_id_or_none_from_bucket_name(bucket_name) if id_ is not None: return Bucket(self, id_, name=bucket_name) - for bucket in self.list_buckets(): - if bucket.name == bucket_name: - return bucket + # Second, ask the service + for bucket in self.list_buckets(bucket_name=bucket_name): + assert bucket.name == bucket_name + return bucket + + # There is no such bucket. raise NonExistentBucket(bucket_name) def delete_bucket(self, bucket): @@ -244,25 +251,14 @@ class B2Api(object): :param bucket_name: Optional: the name of the one bucket to return. :return: A list of Bucket objects. """ - account_id = self.account_info.get_account_id() + # Give a useful warning if the current application key does not + # allow access to the named bucket. self.check_bucket_restrictions(bucket_name) - # TEMPORARY work around until we fix the API endpoint bug that things requests - # with a bucket name are not authorized. When it's fixed, well just pass the - # bucket name (or None) to the raw API. - if bucket_name is None: - bucket_id = None - else: - allowed = self.account_info.get_allowed() - if allowed['bucketId'] is not None: - # We just checked that if there is a bucket restriction we have a bucket name - # and it matches. So if there's a restriction we know that's the bucket we're - # looking for. - bucket_id = allowed['bucketId'] - else: - bucket_id = self.get_bucket_by_name(bucket_name).id_ + account_id = self.account_info.get_account_id() + self.check_bucket_restrictions(bucket_name) - response = self.session.list_buckets(account_id, bucket_id=bucket_id) + response = self.session.list_buckets(account_id, bucket_name=bucket_name) buckets = BucketFactory.from_api_response(self, response) if bucket_name is not None: diff --git a/b2/raw_simulator.py b/b2/raw_simulator.py index 9731370..0fcb999 100644 --- a/b2/raw_simulator.py +++ b/b2/raw_simulator.py @@ -767,18 +767,40 @@ class RawSimulator(AbstractRawApi): self.file_id_to_bucket_id[response['fileId']] = bucket_id return response - def list_buckets(self, api_url, account_auth_token, account_id, bucket_id=None): - self._assert_account_auth(api_url, account_auth_token, account_id, 'listBuckets', bucket_id) + def list_buckets( + self, api_url, account_auth_token, account_id, bucket_id=None, bucket_name=None + ): + # First, map the bucket name to a bucket_id, so that we can check auth. + if bucket_name is None: + bucket_id_for_auth = bucket_id + else: + bucket_id_for_auth = self._get_bucket_id_or_none_for_bucket_name(bucket_name) + self._assert_account_auth( + api_url, account_auth_token, account_id, 'listBuckets', bucket_id_for_auth + ) + + # Do the query sorted_buckets = [ - self.bucket_name_to_bucket[bucket_name] - for bucket_name in sorted(six.iterkeys(self.bucket_name_to_bucket)) + self.bucket_name_to_bucket[name] + for name in sorted(six.iterkeys(self.bucket_name_to_bucket)) ] bucket_list = [ bucket.bucket_dict() - for bucket in sorted_buckets if bucket_id is None or bucket.bucket_id == bucket_id + for bucket in sorted_buckets if self._bucket_matches(bucket, bucket_id, bucket_name) ] return dict(buckets=bucket_list) + def _get_bucket_id_or_none_for_bucket_name(self, bucket_name): + for bucket in six.itervalues(self.bucket_name_to_bucket): + if bucket.bucket_name == bucket_name: + return bucket.bucket_id + + def _bucket_matches(self, bucket, bucket_id, bucket_name): + return ( + (bucket_id is None or bucket.bucket_id == bucket_id) and + (bucket_name is None or bucket.bucket_name == bucket_name) + ) + def list_file_names( self, api_url, account_auth, bucket_id, start_file_name=None, max_file_count=None ):
b2.api.B2Api.get_bucket_by_name does not work with bucket-scoped application keys I am using Duplicity 0.7.17 and b2 1.3.2. duplicity is executed using ``` duplicity \ --verbosity debug \ /backup \ "b2://$B2_APP_KEY_ID:$B2_APP_KEY@$B2_BUCKET_NAME" ``` Where `$B2_APP_KEY_ID` and `$B2_APP_KEY` are URL-encoded strings which were output from a call to: ``` b2 create-key \ --bucket "$B2_BUCKET_NAME" \ "$B2_KEY_NAME" \ listFiles,readFiles,writeFiles,deleteFiles,listBuckets ``` Duplicity fails with the following traceback: ``` Traceback (innermost last): File "/usr/local/bin/duplicity", line 1555, in <module> with_tempdir(main) File "/usr/local/bin/duplicity", line 1541, in with_tempdir fn() File "/usr/local/bin/duplicity", line 1380, in main action = commandline.ProcessCommandLine(sys.argv[1:]) File "/usr/local/lib/python2.7/dist-packages/duplicity/commandline.py", line 1135, in ProcessCommandLine backup, local_pathname = set_backend(args[0], args[1]) File "/usr/local/lib/python2.7/dist-packages/duplicity/commandline.py", line 1010, in set_backend globals.backend = backend.get_backend(bend) File "/usr/local/lib/python2.7/dist-packages/duplicity/backend.py", line 223, in get_backend obj = get_backend_object(url_string) File "/usr/local/lib/python2.7/dist-packages/duplicity/backend.py", line 209, in get_backend_object return factory(pu) File "/usr/local/lib/python2.7/dist-packages/duplicity/backends/b2backend.py", line 87, in __init__ self.bucket = self.service.get_bucket_by_name(bucket_name) File "/usr/local/lib/python2.7/dist-packages/b2/api.py", line 222, in get_bucket_by_name for bucket in self.list_buckets(): File "/usr/local/lib/python2.7/dist-packages/logfury/v0_1/trace_call.py", line 84, in wrapper return function(*wrapee_args, **wrapee_kwargs) File "/usr/local/lib/python2.7/dist-packages/b2/api.py", line 251, in list_buckets self.check_bucket_restrictions(bucket_name) File "/usr/local/lib/python2.7/dist-packages/logfury/v0_1/trace_call.py", line 84, in wrapper return function(*wrapee_args, **wrapee_kwargs) File "/usr/local/lib/python2.7/dist-packages/b2/api.py", line 375, in check_bucket_restrictions raise RestrictedBucket(allowed_bucket_name) RestrictedBucket: Application key is restricted to bucket: pc-backup ``` Internally<sup>[[1]](https://bazaar.launchpad.net/~duplicity-team/duplicity/0.8-series/view/head:/duplicity/backends/b2backend.py#L88)</sup>, Duplicity uses `b2.api.B2Api.get_bucket_by_name`, passing in the name of the bucket. This method calls `b2.api.B2Api.list_buckets` without passing the bucket name, so we get the permission error indicated above. This looks related to changes in #474.
Backblaze/B2_Command_Line_Tool
diff --git a/test/test_api.py b/test/test_api.py index adcdb45..f72c336 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -53,6 +53,16 @@ class TestApi(TestBase): [b.name for b in self.api.list_buckets(bucket_name=bucket1.name)], ) + def test_get_bucket_by_name_with_bucket_restriction(self): + self._authorize_account() + bucket1 = self.api.create_bucket('bucket1', 'allPrivate') + key = self.api.create_key(['listBuckets'], 'key1', bucket_id=bucket1.id_) + self.api.authorize_account('production', key['applicationKeyId'], key['applicationKey']) + self.assertEqual( + bucket1.id_, + self.api.get_bucket_by_name('bucket1').id_, + ) + def test_list_buckets_with_restriction_and_wrong_name(self): self._authorize_account() bucket1 = self.api.create_bucket('bucket1', 'allPrivate') @@ -72,4 +82,4 @@ class TestApi(TestBase): self.api.list_buckets() def _authorize_account(self): - self.api.authorize_account('production', self.account_id, self.master_key) \ No newline at end of file + self.api.authorize_account('production', self.account_id, self.master_key)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt", "requirements-test.txt", "requirements-setup.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
arrow==0.12.0 attrs==22.2.0 -e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@4154652165dd475d79de606abd70b6debc4596d4#egg=b2 certifi==2021.5.30 charset-normalizer==2.0.12 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 logfury==1.0.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyflakes==3.0.1 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 requests==2.27.1 six==1.17.0 tomli==1.2.3 tqdm==4.64.1 typing_extensions==4.1.1 urllib3==1.26.20 yapf==0.32.0 zipp==3.6.0
name: B2_Command_Line_Tool channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - arrow==0.12.0 - attrs==22.2.0 - charset-normalizer==2.0.12 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - logfury==1.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyflakes==3.0.1 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - tqdm==4.64.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - yapf==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/B2_Command_Line_Tool
[ "test/test_api.py::TestApi::test_get_bucket_by_name_with_bucket_restriction" ]
[]
[ "test/test_api.py::TestApi::test_list_buckets", "test/test_api.py::TestApi::test_list_buckets_with_name", "test/test_api.py::TestApi::test_list_buckets_with_restriction", "test/test_api.py::TestApi::test_list_buckets_with_restriction_and_no_name", "test/test_api.py::TestApi::test_list_buckets_with_restriction_and_wrong_name" ]
[]
MIT License
2,894
1,261
[ "b2/api.py", "b2/raw_simulator.py" ]
scrapy__scrapy-3371
c8f3d07e86dd41074971b5423fb932c2eda6db1e
2018-08-09 18:10:12
886513c3751b92e42dcc8cb180d4c15a5a11ccaf
diff --git a/scrapy/contracts/__init__.py b/scrapy/contracts/__init__.py index 5eaee3d11..8315d21d2 100644 --- a/scrapy/contracts/__init__.py +++ b/scrapy/contracts/__init__.py @@ -84,7 +84,7 @@ class ContractsManager(object): def eb_wrapper(failure): case = _create_testcase(method, 'errback') - exc_info = failure.value, failure.type, failure.getTracebackObject() + exc_info = failure.type, failure.value, failure.getTracebackObject() results.addError(case, exc_info) request.callback = cb_wrapper
AttributeError from contract errback When running a contract with a URL that returns non-200 response, I get the following: ``` 2018-08-09 14:40:23 [scrapy.core.scraper] ERROR: Spider error processing <GET https://www.bureauxlocaux.com/annonce/a-louer-bureaux-a-louer-a-nantes--1289-358662> (referer: None) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/usr/local/lib/python3.6/site-packages/scrapy/contracts/__init__.py", line 89, in eb_wrapper results.addError(case, exc_info) File "/usr/local/lib/python3.6/unittest/runner.py", line 67, in addError super(TextTestResult, self).addError(test, err) File "/usr/local/lib/python3.6/unittest/result.py", line 17, in inner return method(self, *args, **kw) File "/usr/local/lib/python3.6/unittest/result.py", line 115, in addError self.errors.append((test, self._exc_info_to_string(err, test))) File "/usr/local/lib/python3.6/unittest/result.py", line 186, in _exc_info_to_string exctype, value, tb, limit=length, capture_locals=self.tb_locals) File "/usr/local/lib/python3.6/traceback.py", line 470, in __init__ exc_value.__cause__.__traceback__, AttributeError: 'getset_descriptor' object has no attribute '__traceback__' ``` Here is how `exc_info` looks like: ``` (HttpError('Ignoring non-200 response',), <class 'scrapy.spidermiddlewares.httperror.HttpError'>, <traceback object at 0x7f4bdca1d948>) ```
scrapy/scrapy
diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 1cea2afb7..b07cbee1e 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -1,7 +1,9 @@ from unittest import TextTestResult +from twisted.python import failure from twisted.trial import unittest +from scrapy.spidermiddlewares.httperror import HttpError from scrapy.spiders import Spider from scrapy.http import Request from scrapy.item import Item, Field @@ -185,3 +187,18 @@ class ContractsManagerTest(unittest.TestCase): self.results) request.callback(response) self.should_fail() + + def test_errback(self): + spider = TestSpider() + response = ResponseMock() + + try: + raise HttpError(response, 'Ignoring non-200 response') + except HttpError: + failure_mock = failure.Failure() + + request = self.conman.from_method(spider.returns_request, self.results) + request.errback(failure_mock) + + self.assertFalse(self.results.failures) + self.assertTrue(self.results.errors)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev" ], "python": "3.9", "reqs_path": [ "requirements-py3.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 Automat==24.8.1 cffi==1.17.1 constantly==23.10.4 coverage==7.8.0 cryptography==44.0.2 cssselect==1.3.0 exceptiongroup==1.2.2 execnet==2.1.1 hyperlink==21.0.0 idna==3.10 incremental==24.7.2 iniconfig==2.1.0 jmespath==1.0.1 lxml==5.3.1 packaging==24.2 parsel==1.10.0 pluggy==1.5.0 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyDispatcher==2.0.7 pyOpenSSL==25.0.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 queuelib==1.7.0 -e git+https://github.com/scrapy/scrapy.git@c8f3d07e86dd41074971b5423fb932c2eda6db1e#egg=Scrapy service-identity==24.2.0 six==1.17.0 tomli==2.2.1 Twisted==24.11.0 typing_extensions==4.13.0 w3lib==2.3.1 zope.interface==7.2
name: scrapy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - automat==24.8.1 - cffi==1.17.1 - constantly==23.10.4 - coverage==7.8.0 - cryptography==44.0.2 - cssselect==1.3.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - hyperlink==21.0.0 - idna==3.10 - incremental==24.7.2 - iniconfig==2.1.0 - jmespath==1.0.1 - lxml==5.3.1 - packaging==24.2 - parsel==1.10.0 - pluggy==1.5.0 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydispatcher==2.0.7 - pyopenssl==25.0.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - queuelib==1.7.0 - service-identity==24.2.0 - six==1.17.0 - tomli==2.2.1 - twisted==24.11.0 - typing-extensions==4.13.0 - w3lib==2.3.1 - zope-interface==7.2 prefix: /opt/conda/envs/scrapy
[ "tests/test_contracts.py::ContractsManagerTest::test_errback" ]
[]
[ "tests/test_contracts.py::ContractsManagerTest::test_contracts", "tests/test_contracts.py::ContractsManagerTest::test_returns", "tests/test_contracts.py::ContractsManagerTest::test_scrapes" ]
[]
BSD 3-Clause "New" or "Revised" License
2,895
160
[ "scrapy/contracts/__init__.py" ]
pennmem__cmlreaders-195
ba6db8e7208903dea9573ebdbbde0a3bef3a8d4f
2018-08-10 19:52:42
06f314e3c0ceb982fe72f94e7a636ab1fff06c29
diff --git a/cmlreaders/readers/eeg.py b/cmlreaders/readers/eeg.py index dd9d03b..2a82a33 100644 --- a/cmlreaders/readers/eeg.py +++ b/cmlreaders/readers/eeg.py @@ -42,6 +42,8 @@ class EEGMetaReader(BaseCMLReader): df = pd.read_json(self.file_path, orient='index') sources_info = {} for k in df: + if any(df[k].apply(lambda x: isinstance(x, dict))): + continue v = df[k].unique() sources_info[k] = v[0] if len(v) == 1 else v sources_info['path'] = self.file_path
error reading some sources.json files I'm running into errors when some sources.json files are being processed. The error is: `TypeError: unhashable type: 'dict'` Here's an example, using code from `_read_sources_json`. ``` file_path = '/protocols/r1/subjects/R1270J/experiments/TH1/sessions/0/ephys/current_processed/sources.json' df = pd.read_json(file_path, orient='index') sources_info = {} for k in df: v = df[k].unique() sources_info[k] = v[0] if len(v) == 1 else v ``` The contents of that json file are formatted a little differently than others, I think. I'm finding about 8 TH subjects who have this issue. Not sure about other datasets. ``` { "R1270J_TH1_0_13Feb17_0058": { "0": { "data_format": "int16", "n_samples": 2663545, "sample_rate": 1000, "source_file": "170212-1658/np1-001.ns2", "start_time_ms": 1486947511412, "start_time_str": "13Feb17_0058" }, "1": { "data_format": "int16", "n_samples": 2662535, "sample_rate": 1000, "source_file": "170212-1658/np2-001.ns2", "start_time_ms": 1486947512417, "start_time_str": "13Feb17_0058" }, "data_format": "int16", "n_samples": 2662535, "sample_rate": 1000, "source_file": "np1-001.ns2", "start_time_ms": 1486947511412, "start_time_str": "13Feb17_0058" } ```
pennmem/cmlreaders
diff --git a/cmlreaders/test/data/multiNSx_sources.json b/cmlreaders/test/data/multiNSx_sources.json new file mode 100644 index 0000000..70a64e7 --- /dev/null +++ b/cmlreaders/test/data/multiNSx_sources.json @@ -0,0 +1,26 @@ +{ + "R1191J_TH1_0_25Jun16_1758": { + "0": { + "data_format": "int16", + "n_samples": 5256196, + "sample_rate": 1000, + "source_file": "160625-1358/np1-001.ns2", + "start_time_ms": 1466877518277, + "start_time_str": "25Jun16_1758" + }, + "1": { + "data_format": "int16", + "n_samples": 5256192, + "sample_rate": 1000, + "source_file": "160625-1358/np2-001.ns2", + "start_time_ms": 1466877519275, + "start_time_str": "25Jun16_1758" + }, + "data_format": "int16", + "n_samples": 5256192, + "sample_rate": 1000, + "source_file": "np1-001.ns2", + "start_time_ms": 1466877518277, + "start_time_str": "25Jun16_1758" + } +} \ No newline at end of file diff --git a/cmlreaders/test/test_eeg.py b/cmlreaders/test/test_eeg.py index 1695dd2..3ccfd4a 100644 --- a/cmlreaders/test/test_eeg.py +++ b/cmlreaders/test/test_eeg.py @@ -41,6 +41,7 @@ def events(): class TestEEGMetaReader: @pytest.mark.parametrize("subject,filename,data_format,n_samples,sample_rate", [ ("R1389J", "sources.json", "int16", 1641165, 1000), + ("R1191J", "multiNSx_sources.json", "int16", 5256192, 1000), ("TJ001", "TJ001_pyFR_params.txt", "int16", None, 400.0), ]) def test_load(self, subject, filename, data_format, n_samples, sample_rate):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 cached-property==1.5.2 certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/pennmem/cmlreaders.git@ba6db8e7208903dea9573ebdbbde0a3bef3a8d4f#egg=cmlreaders codecov==2.1.13 coverage==6.2 cycler==0.11.0 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 flake8==3.9.2 h5py==3.1.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 ipython-genutils==0.2.0 Jinja2==3.0.3 jsonschema==3.2.0 jupyter-client==7.1.2 jupyter-core==4.9.2 jupyterlab-pygments==0.1.2 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.3.4 mccabe==0.6.1 mistune==0.8.4 mne==0.23.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nbsphinx==0.8.8 nest-asyncio==1.6.0 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.1 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.7.0 pyflakes==2.3.1 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 scipy==1.5.4 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 zipp==3.6.0
name: cmlreaders channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cached-property==1.5.2 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cycler==0.11.0 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - flake8==3.9.2 - h5py==3.1.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - ipython-genutils==0.2.0 - jinja2==3.0.3 - jsonschema==3.2.0 - jupyter-client==7.1.2 - jupyter-core==4.9.2 - jupyterlab-pygments==0.1.2 - kiwisolver==1.3.1 - markupsafe==2.0.1 - matplotlib==3.3.4 - mccabe==0.6.1 - mistune==0.8.4 - mne==0.23.4 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbsphinx==0.8.8 - nest-asyncio==1.6.0 - numpy==1.19.5 - packaging==21.3 - pandas==1.1.5 - pandocfilters==1.5.1 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.7.0 - pyflakes==2.3.1 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - scipy==1.5.4 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/cmlreaders
[ "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[R1191J-multiNSx_sources.json-int16-5256192-1000]" ]
[ "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_split_eeg_reader_missing_contacts", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1345D-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1363T-FR1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader_rhino[R1392N-PAL1-0]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_reader", "cmlreaders/test/test_eeg.py::TestFileReaders::test_ramulator_hdf5_rereference", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1298E-FR1-87-CH88]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[R1387E-FR1-13-CH14]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader[TJ039-pyFR-14-CH15]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_read_whole_session[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1161E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_reader_with_events[R1387E]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1384J-pairs-False-43-LS12-LS1]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-pairs-True-43-LPOG23-LPOG31]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1111M-contacts-True-43-LPOG44]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_rereference[R1286J-contacts-True-43-LJ16]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1384J-ind.region-insula-10-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1288P-ind.region-lateralorbitofrontal-5-200]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_filter_channels[R1111M-ind.region-middletemporal-18-100]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-True]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[RamulatorHDF5Reader-False]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects0-experiments0]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects1-experiments1]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects2-experiments2]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_multisession[subjects3-experiments3]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_channel_discrepancies[R1387E-catFR5-0-120-125]" ]
[ "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[R1389J-sources.json-int16-1641165-1000]", "cmlreaders/test/test_eeg.py::TestEEGMetaReader::test_load[TJ001-TJ001_pyFR_params.txt-int16-None-400.0]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[True]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_include_contact[False]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/contacts.json-contacts]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[/cmlreaders/cmlreaders/test/data/pairs.json-pairs]", "cmlreaders/test/test_eeg.py::TestBaseEEGReader::test_scheme_type[-None]", "cmlreaders/test/test_eeg.py::TestFileReaders::test_npy_reader", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[TJ001-TJ001_events.mat-expected_basenames0]", "cmlreaders/test/test_eeg.py::TestEEGReader::test_eeg_absolute[R1389J-task_events.json-expected_basenames1]", "cmlreaders/test/test_eeg.py::TestRereference::test_rereference[SplitEEGReader-True]", "cmlreaders/test/test_eeg.py::TestLoadEEG::test_load_with_empty_events" ]
[]
null
2,902
176
[ "cmlreaders/readers/eeg.py" ]
dwavesystems__dimod-259
4ebac589cfcddcfcef4b4e5160a07c5f67d999f6
2018-08-13 20:03:57
2f6e129f4894ae07d16aa290c35d7e7859138cc8
diff --git a/dimod/embedding/transforms.py b/dimod/embedding/transforms.py index 491c3a4a..b72dbda6 100644 --- a/dimod/embedding/transforms.py +++ b/dimod/embedding/transforms.py @@ -416,13 +416,15 @@ def unembed_response(target_response, embedding, source_bqm, chain_break_method= Sample(sample={'x2': 0, 'x1': 0, 'z': 1}, energy=3.0) """ - if any(v not in embedding for v in source_bqm): - raise ValueError("given bqm does not match the embedding") if chain_break_method is None: chain_break_method = majority_vote - variables, chains = zip(*embedding.items()) + variables = list(source_bqm) + try: + chains = [embedding[v] for v in variables] + except KeyError: + raise ValueError("given bqm does not match the embedding") if target_response.label_to_idx is None: chain_idxs = [list(chain) for chain in chains]
Unembedding fails for bqms that are a subset of the source graph **Description** Unembedding fails when the embedding has more variables than the BQM. **To Reproduce** ``` import numpy as np import dimod response = dimod.Response(np.rec.array([([-1, 1, -1, 1, -1, 1, -1, 1], -1.4, 1), ([-1, 1, -1, -1, -1, 1, -1, -1], -1.4, 1), ([ 1, -1, -1, -1, 1, -1, -1, -1], -1.6, 1), ([ 1, -1, 1, 1, 1, -1, 1, 1], -1.6, 1), ([-1, 1, -1, 1, -1, 1, -1, 1], -1.4, 1), ([ 1, -1, -1, -1, 1, -1, -1, -1], -1.6, 1), ([-1, 1, 1, 1, -1, 1, 1, 1], -1.4, 1), ([-1, 1, 1, 1, -1, 1, 1, 1], -1.4, 1), ([ 1, -1, 1, -1, 1, -1, 1, -1], -1.6, 1), ([ 1, -1, -1, -1, 1, -1, -1, -1], -1.6, 1)], dtype=[('sample', 'i1', (8,)), ('energy', '<f8'), ('num_occurrences', '<i8')]), [0, 1, 2, 3, 4, 5, 6, 7], {}, 'SPIN') embedding = {0: {0, 4}, 1: {1, 5}, 2: {2, 6}, 3: {3, 7}} bqm = dimod.BinaryQuadraticModel({0: 0.1, 1: 0.2}, {(0, 1): 1.5}, 0.0, dimod.SPIN) dimod.unembed_response(response, embedding, source_bqm=bqm) ``` Traceback: ``` KeyError Traceback (most recent call last) <ipython-input-6-d819b61114e6> in <module>() 16 bqm = dimod.BinaryQuadraticModel({0: 0.1, 1: 0.2}, {(0, 1): 1.5}, 0.0, dimod.SPIN) 17 ---> 18 dimod.unembed_response(response, embedding, source_bqm=bqm) ~/projects/ocean/system/venv37/lib/python3.7/site-packages/dimod/embedding/transforms.py in unembed_response(target_response, embedding, source_bqm, chain_break_method) 434 unembedded, idxs = chain_break_method(record.sample, chain_idxs) 435 --> 436 lin, (i, j, quad), off = source_bqm.to_numpy_vectors(variable_order=variables) 437 energies = unembedded.dot(lin) + (unembedded[:, i]*unembedded[:, j]).dot(quad) + off 438 ~/projects/ocean/system/venv37/lib/python3.7/site-packages/dimod/binary_quadratic_model.py in to_numpy_vectors(self, variable_order, dtype, index_dtype, sort_indices) 2171 labels = {v: idx for idx, v in enumerate(variable_order)} 2172 -> 2173 lin = np.array([linear[v] for v in variable_order], dtype=dtype) 2174 2175 if quadratic: ~/projects/ocean/system/venv37/lib/python3.7/site-packages/dimod/binary_quadratic_model.py in <listcomp>(.0) 2171 labels = {v: idx for idx, v in enumerate(variable_order)} 2172 -> 2173 lin = np.array([linear[v] for v in variable_order], dtype=dtype) 2174 2175 if quadratic: KeyError: 2 ``` **Environment:** - OS: Ubuntu 16.04.5 LTS - Python version: 3.7.0
dwavesystems/dimod
diff --git a/tests/test_embedding_transforms.py b/tests/test_embedding_transforms.py index 2470acd5..f022020d 100644 --- a/tests/test_embedding_transforms.py +++ b/tests/test_embedding_transforms.py @@ -184,6 +184,24 @@ class TestUnembedResponse(unittest.TestCase): for sample, energy in response.data(['sample', 'energy']): self.assertEqual(bqm.energy(sample), energy) + def test_embedding_superset(self): + # source graph in the embedding is a superset of the bqm + response = dimod.Response(np.rec.array([([-1, 1, -1, 1, -1, 1, -1, 1], -1.4, 1), + ([-1, 1, -1, -1, -1, 1, -1, -1], -1.4, 1), + ([+1, -1, -1, -1, 1, -1, -1, -1], -1.6, 1), + ([+1, -1, -1, -1, 1, -1, -1, -1], -1.6, 1)], + dtype=[('sample', 'i1', (8,)), ('energy', '<f8'), ('num_occurrences', '<i8')]), + [0, 1, 2, 3, 4, 5, 6, 7], {}, 'SPIN') + embedding = {0: {0, 4}, 1: {1, 5}, 2: {2, 6}, 3: {3, 7}} + bqm = dimod.OrderedBinaryQuadraticModel.from_ising([.1, .2], {(0, 1): 1.5}, 0.0) + + unembedded = dimod.unembed_response(response, embedding, source_bqm=bqm) + + arr = np.rec.array([([-1, 1], -1.4, 1), ([-1, 1], -1.4, 1), ([+1, -1], -1.6, 1), ([+1, -1], -1.6, 1)], + dtype=[('sample', 'i1', (2,)), ('energy', '<f8'), ('num_occurrences', '<i8')]) + + np.testing.assert_array_equal(arr, unembedded.record) + class TestEmbedBQM(unittest.TestCase): def test_embed_bqm_empty(self):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 decorator==5.1.1 -e git+https://github.com/dwavesystems/dimod.git@4ebac589cfcddcfcef4b4e5160a07c5f67d999f6#egg=dimod idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 jsonschema==2.6.0 mock==2.0.0 networkx==2.0 numpy==1.15.0 packaging==21.3 pandas==0.22.0 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pymongo==3.7.1 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 six==1.11.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: dimod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonschema==2.6.0 - mock==2.0.0 - networkx==2.0 - numpy==1.15.0 - packaging==21.3 - pandas==0.22.0 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pymongo==3.7.1 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - six==1.11.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/dimod
[ "tests/test_embedding_transforms.py::TestUnembedResponse::test_embedding_superset" ]
[]
[ "tests/test_embedding_transforms.py::TestUnembedResponse::test_discard", "tests/test_embedding_transforms.py::TestUnembedResponse::test_discard_with_response", "tests/test_embedding_transforms.py::TestUnembedResponse::test_energies_discard", "tests/test_embedding_transforms.py::TestUnembedResponse::test_energies_functional", "tests/test_embedding_transforms.py::TestUnembedResponse::test_majority_vote", "tests/test_embedding_transforms.py::TestUnembedResponse::test_majority_vote_with_response", "tests/test_embedding_transforms.py::TestUnembedResponse::test_unembed_response_with_discard_matrix_typical", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_BINARY", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_NAE3SAT_to_square", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_empty", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_identity", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_only_offset", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_subclass_propagation", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_bad_chain", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_components_empty", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_embedding_not_in_adj", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_h_embedding_mismatch", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_j_index_too_large", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_nonadj", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_typical", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_qubo", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embedding_with_extra_chains" ]
[]
Apache License 2.0
2,916
260
[ "dimod/embedding/transforms.py" ]
spacetx__slicedimage-26
a4bcd1715016ca1411d70cdd728ed53be411a341
2018-08-14 05:31:46
a4bcd1715016ca1411d70cdd728ed53be411a341
codecov-io: # [Codecov](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=h1) Report > Merging [#26](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=desc) into [master](https://codecov.io/gh/spacetx/slicedimage/commit/a4bcd1715016ca1411d70cdd728ed53be411a341?src=pr&el=desc) will **increase** coverage by `1.8%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/spacetx/slicedimage/pull/26/graphs/tree.svg?token=h4lI8HE0K6&width=650&height=150&src=pr)](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #26 +/- ## ========================================= + Coverage 74.84% 76.64% +1.8% ========================================= Files 18 18 Lines 469 471 +2 ========================================= + Hits 351 361 +10 + Misses 118 110 -8 ``` | [Impacted Files](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [slicedimage/io.py](https://codecov.io/gh/spacetx/slicedimage/pull/26/diff?src=pr&el=tree#diff-c2xpY2VkaW1hZ2UvaW8ucHk=) | `92.63% <100%> (+4.33%)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=footer). Last update [a4bcd17...6628851](https://codecov.io/gh/spacetx/slicedimage/pull/26?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
diff --git a/slicedimage/io.py b/slicedimage/io.py index f930798..afe39c6 100644 --- a/slicedimage/io.py +++ b/slicedimage/io.py @@ -9,7 +9,7 @@ import tempfile from packaging import version from six.moves import urllib -from slicedimage.urlpath import pathsplit +from slicedimage.urlpath import pathjoin, pathsplit from .backends import DiskBackend, HttpBackend from ._collection import Collection from ._formats import ImageFormat @@ -58,26 +58,35 @@ def resolve_path_or_url(path_or_url, allow_caching=True): raise +def _resolve_absolute_url(absolute_url, allow_caching): + """ + Given a string that is an absolute URL, return a tuple consisting of: a + :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of + the object. + """ + splitted = pathsplit(absolute_url) + backend = infer_backend(splitted[0], allow_caching) + return backend, splitted[1], splitted[0] + + def resolve_url(name_or_url, baseurl=None, allow_caching=True): """ Given a string that can either be a name or a fully qualified url, return a tuple consisting of: a :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of the object. - If the string is a name and not a fully qualified url, then baseurl must be set. + If the string is a name and not a fully qualified url, then baseurl must be set. If the string + is a fully qualified url, then baseurl is ignored. """ try: # assume it's a fully qualified url. - splitted = pathsplit(name_or_url) - backend = infer_backend(splitted[0], allow_caching) - return backend, splitted[1], splitted[0] + return _resolve_absolute_url(name_or_url, allow_caching) except ValueError: if baseurl is None: # oh, we have no baseurl. punt. raise - # it's not a fully qualified url. - backend = infer_backend(baseurl, allow_caching) - return backend, name_or_url, baseurl + absolute_url = pathjoin(baseurl, name_or_url) + return _resolve_absolute_url(absolute_url, allow_caching) class Reader(object):
slicedimage relative paths in hybridization.json are relative to experiment.json For example, in the following file structure: ``` experiment.json fov_001/ hybridization.json/ file_0.tiff ``` The file path to `file_0.tiff` in `hybridization.json` needs to be `fov_001/file_0.tiff` _not_ `file_0.tiff`, which is counter-intuitive. The below code reproduces this issue -- it loads, but contains the odd file paths suggested above. ``` experiment = Experiment() experiment.read('http://czi.starfish.data.public.s3.amazonaws.com/20180813/MERFISH/experiment.json') ```
spacetx/slicedimage
diff --git a/tests/io/test_resolve_url.py b/tests/io/test_resolve_url.py new file mode 100644 index 0000000..c39152f --- /dev/null +++ b/tests/io/test_resolve_url.py @@ -0,0 +1,65 @@ +import os +import sys +import tempfile +import unittest +import uuid + + +pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) # noqa +sys.path.insert(0, pkg_root) # noqa + + +from slicedimage.io import resolve_path_or_url, resolve_url + + +class TestResolvePathOrUrl(unittest.TestCase): + def test_valid_local_path(self): + with tempfile.NamedTemporaryFile() as tfn: + abspath = os.path.realpath(tfn.name) + _, name, baseurl = resolve_path_or_url(abspath) + self.assertEqual(name, os.path.basename(abspath)) + self.assertEqual("file://{}".format(os.path.dirname(abspath)), baseurl) + + cwd = os.getcwd() + try: + os.chdir(os.path.dirname(abspath)) + _, name, baseurl = resolve_path_or_url(os.path.basename(abspath)) + self.assertEqual(name, os.path.basename(abspath)) + self.assertEqual("file://{}".format(os.path.dirname(abspath)), baseurl) + finally: + os.chdir(cwd) + + def test_invalid_local_path(self): + with self.assertRaises(ValueError): + resolve_path_or_url(str(uuid.uuid4())) + + def test_url(self): + _, name, baseurl = resolve_path_or_url("https://github.com/abc/def") + self.assertEqual(name, "def") + self.assertEqual(baseurl, "https://github.com/abc") + + +class TestResolveUrl(unittest.TestCase): + def test_fully_qualified_url(self): + _, name, baseurl = resolve_url("https://github.com/abc/def") + self.assertEqual(name, "def") + self.assertEqual(baseurl, "https://github.com/abc") + + # even with a baseurl, this should work. + _, name, baseurl = resolve_url("https://github.com/abc/def", "https://github.io") + self.assertEqual(name, "def") + self.assertEqual(baseurl, "https://github.com/abc") + + def test_relative_url(self): + _, name, baseurl = resolve_url("def", "https://github.com/abc") + self.assertEqual(name, "def") + self.assertEqual(baseurl, "https://github.com/abc") + + # even with a path separator in the relative path, it should work. + _, name, baseurl = resolve_url("abc/def", "https://github.com/") + self.assertEqual(name, "def") + self.assertEqual(baseurl, "https://github.com/abc") + + +if __name__ == "__main__": + unittest.main()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 cycler==0.11.0 decorator==4.4.2 enum34==1.1.10 idna==3.10 imageio==2.15.0 importlib-metadata==4.8.3 iniconfig==1.1.1 kiwisolver==1.3.1 matplotlib==3.3.4 networkx==2.5.1 numpy==1.19.5 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 PyWavelets==1.1.1 requests==2.27.1 scikit-image==0.17.2 scipy==1.5.4 six==1.17.0 -e git+https://github.com/spacetx/slicedimage.git@a4bcd1715016ca1411d70cdd728ed53be411a341#egg=slicedimage tifffile==2020.9.3 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: slicedimage channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - cycler==0.11.0 - decorator==4.4.2 - enum34==1.1.10 - idna==3.10 - imageio==2.15.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - kiwisolver==1.3.1 - matplotlib==3.3.4 - networkx==2.5.1 - numpy==1.19.5 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pywavelets==1.1.1 - requests==2.27.1 - scikit-image==0.17.2 - scipy==1.5.4 - six==1.17.0 - tifffile==2020.9.3 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/slicedimage
[ "tests/io/test_resolve_url.py::TestResolveUrl::test_relative_url" ]
[]
[ "tests/io/test_resolve_url.py::TestResolvePathOrUrl::test_invalid_local_path", "tests/io/test_resolve_url.py::TestResolvePathOrUrl::test_url", "tests/io/test_resolve_url.py::TestResolvePathOrUrl::test_valid_local_path", "tests/io/test_resolve_url.py::TestResolveUrl::test_fully_qualified_url" ]
[]
MIT License
2,917
569
[ "slicedimage/io.py" ]
stitchfix__nodebook-18
6ddc1a7f5e47a80060365bfb1b9012b928f68970
2018-08-14 18:14:32
46211e90955f3388a22e2a2132bb895814260f9a
diff --git a/nodebook/pickledict.py b/nodebook/pickledict.py index 01740f4..33a32e3 100644 --- a/nodebook/pickledict.py +++ b/nodebook/pickledict.py @@ -66,7 +66,6 @@ class PickleDict(DictMixin): persist_path: if provided, perform serialization to/from disk to this path """ self.persist_path = persist_path - self.encodings = {} self.dump = partial(msgpack.dump, default=msgpack_serialize) self.load = partial(msgpack.load, ext_hook=msgpack_deserialize) self.dict = {} @@ -96,25 +95,21 @@ class PickleDict(DictMixin): if self.persist_path is not None: path = self.dict[key] with open(path, 'rb') as f: - value = self.load(f, encoding=self.encodings[key]) + value = self.load(f, raw=False) else: f = StringIO(self.dict[key]) - value = self.load(f, encoding=self.encodings[key]) + value = self.load(f, raw=False) return value def __setitem__(self, key, value): - encoding = None - if isinstance(value, six.string_types): - encoding = 'utf-8' - self.encodings[key] = encoding if self.persist_path is not None: path = os.path.join(self.persist_path, '%s.pak' % key) with open(path, 'wb') as f: - self.dump(value, f, encoding=encoding) + self.dump(value, f, strict_types=True, use_bin_type=True) self.dict[key] = path else: f = StringIO() - self.dump(value, f, encoding=encoding) + self.dump(value, f, strict_types=True, use_bin_type=True) serialized = f.getvalue() self.dict[key] = serialized diff --git a/setup.py b/setup.py index d54a7f5..eb22642 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ import sys setup( name='nodebook', - version='0.3.0', + version='0.3.1', author='Kevin Zielnicki', author_email='[email protected]', license='Stitch Fix 2018',
In python3, strings in dictionaries are de-serialized as bytes Eg, `foo = {'key':42}` is deserialized as `{b'key':42}`
stitchfix/nodebook
diff --git a/tests/test_pickledict.py b/tests/test_pickledict.py index 30ac34b..de2cc45 100644 --- a/tests/test_pickledict.py +++ b/tests/test_pickledict.py @@ -25,10 +25,33 @@ class TestPickleDict(object): mydict['test_string'] = 'foo' assert mydict['test_string'] == 'foo' + d = {'foo':'bar'} + mydict['test_string_dict'] = d + assert mydict['test_string_dict'] == d + def test_bytes(self, mydict): mydict['test_bytes'] = b'foo' assert mydict['test_bytes'] == b'foo' + d = {b'foo':b'bar'} + mydict['test_bytes_dict'] = d + assert mydict['test_bytes_dict'] == d + + def test_list(self, mydict): + l = [1,2,3] + mydict['test_list'] = l + assert mydict['test_list'] == l + + def test_tuple(self, mydict): + t = (1,2,3) + mydict['test_tuple'] = t + assert mydict['test_tuple'] == t + + def test_set(self, mydict): + s = {1,2,3} + mydict['test_set'] = s + assert mydict['test_set'] == s + def test_df(self, mydict): df = pd.DataFrame({'a': [0, 1, 2], 'b': ['foo', 'bar', 'baz']}) mydict['test_df'] = df
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 asttokens==3.0.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 click==8.1.8 cloudpickle==3.1.1 comm==0.2.2 debugpy==1.8.13 decorator==5.2.1 defusedxml==0.7.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work executing==2.2.0 fastjsonschema==2.21.1 fqdn==1.5.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 idna==3.10 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work ipykernel==6.29.5 ipython==8.18.1 ipywidgets==8.1.5 isoduration==20.11.0 jedi==0.19.2 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter==1.1.1 jupyter-console==6.6.3 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.3.6 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==3.0.13 MarkupSafe==3.0.2 matplotlib-inline==0.1.7 mistune==3.1.3 msgpack-python==0.5.6 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nest-asyncio==1.6.0 -e git+https://github.com/stitchfix/nodebook.git@6ddc1a7f5e47a80060365bfb1b9012b928f68970#egg=nodebook notebook==7.3.3 notebook_shim==0.2.4 numpy==2.0.2 overrides==7.7.0 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pandocfilters==1.5.1 parso==0.8.4 pexpect==4.9.0 platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work prometheus_client==0.21.1 prompt_toolkit==3.0.50 psutil==7.0.0 ptyprocess==0.7.0 pure_eval==0.2.3 pycparser==2.22 Pygments==2.19.1 pytest @ file:///croot/pytest_1738938843180/work pytest-runner==6.0.1 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 Send2Trash==1.8.3 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 stack-data==0.6.3 terminado==0.18.1 tinycss2==1.4.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 wcwidth==0.2.13 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==4.0.13 zipp==3.21.0
name: nodebook channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - asttokens==3.0.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - click==8.1.8 - cloudpickle==3.1.1 - comm==0.2.2 - debugpy==1.8.13 - decorator==5.2.1 - defusedxml==0.7.1 - executing==2.2.0 - fastjsonschema==2.21.1 - fqdn==1.5.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - idna==3.10 - importlib-metadata==8.6.1 - ipykernel==6.29.5 - ipython==8.18.1 - ipywidgets==8.1.5 - isoduration==20.11.0 - jedi==0.19.2 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter==1.1.1 - jupyter-client==8.6.3 - jupyter-console==6.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.3.6 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==3.0.13 - markupsafe==3.0.2 - matplotlib-inline==0.1.7 - mistune==3.1.3 - msgpack-python==0.5.6 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nest-asyncio==1.6.0 - notebook==7.3.3 - notebook-shim==0.2.4 - numpy==2.0.2 - overrides==7.7.0 - pandas==2.2.3 - pandocfilters==1.5.1 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.3.7 - prometheus-client==0.21.1 - prompt-toolkit==3.0.50 - psutil==7.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.3 - pycparser==2.22 - pygments==2.19.1 - pytest-runner==6.0.1 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - send2trash==1.8.3 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - stack-data==0.6.3 - terminado==0.18.1 - tinycss2==1.4.0 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - wcwidth==0.2.13 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==4.0.13 - zipp==3.21.0 prefix: /opt/conda/envs/nodebook
[ "tests/test_pickledict.py::TestPickleDict::test_string[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_string[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_tuple[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_tuple[mode_disk]" ]
[]
[ "tests/test_pickledict.py::TestPickleDict::test_int[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_int[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_bytes[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_list[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_list[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_set[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_set[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_df[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_func[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_closure[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_closure[mode_disk]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_memory]", "tests/test_pickledict.py::TestPickleDict::test_immutability[mode_disk]" ]
[]
Apache License 2.0
2,920
559
[ "nodebook/pickledict.py", "setup.py" ]
linkedin__shiv-52
6d00b754852f4f3e79d494d7577a029ecb72c1a1
2018-08-15 21:32:17
6d00b754852f4f3e79d494d7577a029ecb72c1a1
coveralls: ## Pull Request Test Coverage Report for [Build 120](https://coveralls.io/builds/18505798) * **0** of **0** changed or added relevant lines in **0** files are covered. * **10** unchanged lines in **1** file lost coverage. * Overall coverage decreased (**-1.2%**) to **73.93%** --- | Files with Coverage Reduction | New Missed Lines | % | | :-----|--------------|--: | | [.tox/py36/lib/python3.6/site-packages/shiv/bootstrap/__init__.py](https://coveralls.io/builds/18505798/source?filename=.tox%2Fpy36%2Flib%2Fpython3.6%2Fsite-packages%2Fshiv%2Fbootstrap%2F__init__.py#L103) | 10 | 51.56% | <!-- | **Total:** | **10** | | --> | Totals | [![Coverage Status](https://coveralls.io/builds/18505798/badge)](https://coveralls.io/builds/18505798) | | :-- | --: | | Change from base [Build 116](https://coveralls.io/builds/18505654): | -1.2% | | Covered Lines: | 190 | | Relevant Lines: | 257 | --- ##### 💛 - [Coveralls](https://coveralls.io)
diff --git a/src/shiv/bootstrap/__init__.py b/src/shiv/bootstrap/__init__.py index 82169bf..02488ba 100644 --- a/src/shiv/bootstrap/__init__.py +++ b/src/shiv/bootstrap/__init__.py @@ -83,6 +83,12 @@ def extract_site_packages(archive, target_path): shutil.move(str(target_path_tmp), str(target_path)) +def _first_sitedir_index(): + for index, part in enumerate(sys.path): + if Path(part).stem == 'site-packages': + return index + + def bootstrap(): """Actually bootstrap our shiv environment.""" @@ -99,18 +105,18 @@ def bootstrap(): if not site_packages.exists() or env.force_extract: extract_site_packages(archive, site_packages.parent) - preserved = sys.path[1:] + # get sys.path's length + length = len(sys.path) - # truncate the sys.path so our package will be at the start, - # and take precedence over anything else (eg: dist-packages) - sys.path = sys.path[0:1] + # Find the first instance of an existing site-packages on sys.path + index = _first_sitedir_index() or length # append site-packages using the stdlib blessed way of extending path # so as to handle .pth files correctly site.addsitedir(site_packages) - # restore the previous sys.path entries after our package - sys.path.extend(preserved) + # reorder to place our site-packages before any others found + sys.path = sys.path[:index] + sys.path[length:] + sys.path[index:length] # do entry point import and call if env.entry_point is not None and env.interpreter is None:
The change to sys.path potentially overrides standard library modules. The change in #48 makes sure that shiv packed content (packages) has the precedence over the vended Python distribution packages or things installed into system Python site-packages. Fair enough. We want to run what we packed into the shiv. However, it does have a potentially buggy behavior. Example: * an old deprecated 3rd party package such as *uuid* or *argparse* is pulled in transitively * these packages are unmaintained and did not get any changes (uuid since Python 2.5, for example) * the standard library modules have been maintained and added new APIs (uuid did) * since shiv's site-packages are stored on the sys.path **before** the standard library path, an obsolete 3rd party backward-compatibility package (but not **forward** compatible) will override the corresponding standard library module * if any other package uses the new APIs from the affected package (e.g., new uuid APIs), the application will break because the old 3rd party package does not have these functions/methods. I believe this requires changes to what was done in #48 to insert *shiv* site-packages *before* any other site-packages paths, but *after* the standard library path.
linkedin/shiv
diff --git a/test/test_bootstrap.py b/test/test_bootstrap.py index 5ece54f..1f77034 100644 --- a/test/test_bootstrap.py +++ b/test/test_bootstrap.py @@ -12,7 +12,7 @@ import pytest from unittest import mock -from shiv.bootstrap import import_string, current_zipfile, cache_path +from shiv.bootstrap import import_string, current_zipfile, cache_path, _first_sitedir_index from shiv.bootstrap.environment import Environment @@ -61,6 +61,13 @@ class TestBootstrap: assert cache_path(mock_zip, Path.cwd(), uuid) == Path.cwd() / f"test_{uuid}" + def test_first_sitedir_index(self): + with mock.patch.object(sys, 'path', ['site-packages', 'dir', 'dir', 'dir']): + assert _first_sitedir_index() == 0 + + with mock.patch.object(sys, 'path', []): + assert _first_sitedir_index() is None + class TestEnvironment: def test_overrides(self):
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "mypy", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 click==6.7 coverage==6.2 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work mypy==0.971 mypy-extensions==1.0.0 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-cov==4.0.0 -e git+https://github.com/linkedin/shiv.git@6d00b754852f4f3e79d494d7577a029ecb72c1a1#egg=shiv toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 typed-ast==1.5.5 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: shiv channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - click==6.7 - coverage==6.2 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - mccabe==0.7.0 - mypy==0.971 - mypy-extensions==1.0.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pytest-cov==4.0.0 - tomli==1.2.3 - typed-ast==1.5.5 prefix: /opt/conda/envs/shiv
[ "test/test_bootstrap.py::TestBootstrap::test_various_imports", "test/test_bootstrap.py::TestBootstrap::test_is_zipfile", "test/test_bootstrap.py::TestBootstrap::test_argv0_is_not_zipfile", "test/test_bootstrap.py::TestBootstrap::test_cache_path", "test/test_bootstrap.py::TestBootstrap::test_first_sitedir_index", "test/test_bootstrap.py::TestEnvironment::test_overrides", "test/test_bootstrap.py::TestEnvironment::test_serialize", "test/test_builder.py::TestBuilder::test_file_prefix[/usr/bin/python-#!/usr/bin/python\\n]", "test/test_builder.py::TestBuilder::test_file_prefix[/usr/bin/env", "test/test_builder.py::TestBuilder::test_file_prefix[/some/other/path/python", "test/test_builder.py::TestBuilder::test_binprm_error", "test/test_builder.py::TestBuilder::test_create_archive", "test/test_builder.py::TestBuilder::test_archive_permissions", "test/test_cli.py::TestCLI::test_no_args", "test/test_cli.py::TestCLI::test_no_outfile", "test/test_cli.py::TestCLI::test_blacklisted_args[-t]", "test/test_cli.py::TestCLI::test_blacklisted_args[--target]", "test/test_cli.py::TestCLI::test_blacklisted_args[--editable]", "test/test_cli.py::TestCLI::test_blacklisted_args[-d]", "test/test_cli.py::TestCLI::test_blacklisted_args[--download]", "test/test_cli.py::TestCLI::test_blacklisted_args[--user]", "test/test_cli.py::TestCLI::test_blacklisted_args[--root]", "test/test_cli.py::TestCLI::test_blacklisted_args[--prefix]", "test/test_cli.py::TestCLI::test_hello_world[.]", "test/test_cli.py::TestCLI::test_hello_world[absolute-path]", "test/test_pip.py::test_clean_pip_env" ]
[]
[]
[]
BSD 2-Clause "Simplified" License
2,928
414
[ "src/shiv/bootstrap/__init__.py" ]
dwavesystems__dimod-263
53a6efa00f23cd87774579536d589433601adca7
2018-08-15 22:09:36
2f6e129f4894ae07d16aa290c35d7e7859138cc8
diff --git a/dimod/binary_quadratic_model.py b/dimod/binary_quadratic_model.py index 31450ad8..995c36cd 100644 --- a/dimod/binary_quadratic_model.py +++ b/dimod/binary_quadratic_model.py @@ -1391,7 +1391,7 @@ class BinaryQuadraticModel(Sized, Container, Iterable): # conversions ################################################################################################## - def to_coo(self, fp=None): + def to_coo(self, fp=None, vartype_header=False): """Serialize the binary quadratic model to a COOrdinate_ format encoding. .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO) @@ -1403,6 +1403,10 @@ class BinaryQuadraticModel(Sized, Container, Iterable): (i, j, bias), where :math:`i=j` for linear biases. If not provided, returns a string. + vartype_header (bool, optional, default=False): + If true, the binary quadratic model's variable type as prepended to the + string or file as a header. + .. _file object: https://docs.python.org/3/glossary.html#term-file-object .. note:: Variables must use index lables (numeric lables). Binary quadratic @@ -1417,6 +1421,15 @@ class BinaryQuadraticModel(Sized, Container, Iterable): 0 1 0.50000 1 1 -1.50000 + The Coordinate format with a header + + .. code-block:: none + + # vartype=SPIN + 0 0 0.50000 + 0 1 0.50000 + 1 1 -1.50000 + This is an example of writing a binary quadratic model to a COOrdinate-format file. @@ -1436,12 +1449,12 @@ class BinaryQuadraticModel(Sized, Container, Iterable): import dimod.io.coo as coo if fp is None: - return coo.dumps(self) + return coo.dumps(self, vartype_header) else: - coo.dump(self, fp) + coo.dump(self, fp, vartype_header) @classmethod - def from_coo(cls, obj, vartype): + def from_coo(cls, obj, vartype=None): """Deserialize a binary quadratic model from a COOrdinate_ format encoding. .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO) @@ -1453,12 +1466,15 @@ class BinaryQuadraticModel(Sized, Container, Iterable): is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j` for linear biases. - vartype (:class:`.Vartype`/str/set): + vartype (:class:`.Vartype`/str/set, optional): Variable type for the binary quadratic model. Accepted input values: * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}`` * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}`` + If not provided, the vartype must be specified with a header in the + file. + .. _file object: https://docs.python.org/3/glossary.html#term-file-object .. note:: Variables must use index lables (numeric lables). Binary quadratic @@ -1466,10 +1482,19 @@ class BinaryQuadraticModel(Sized, Container, Iterable): zero. Examples: - This is an example of a binary quadratic model encoded in COOrdinate format. + An example of a binary quadratic model encoded in COOrdinate format. + + .. code-block:: none + + 0 0 0.50000 + 0 1 0.50000 + 1 1 -1.50000 + + The Coordinate format with a header .. code-block:: none + # vartype=SPIN 0 0 0.50000 0 1 0.50000 1 1 -1.50000 @@ -1490,9 +1515,9 @@ class BinaryQuadraticModel(Sized, Container, Iterable): import dimod.io.coo as coo if isinstance(obj, str): - return coo.loads(obj, cls.empty(vartype)) + return coo.loads(obj, cls=cls, vartype=vartype) - return coo.load(obj, cls.empty(vartype)) + return coo.load(obj, cls=cls, vartype=vartype) def to_serializable(self, use_bytes=False): """Convert the binary quadratic model to a serializable object. diff --git a/dimod/io/coo.py b/dimod/io/coo.py index 870ffc13..74060bd3 100644 --- a/dimod/io/coo.py +++ b/dimod/io/coo.py @@ -18,7 +18,7 @@ import re from dimod.binary_quadratic_model import BinaryQuadraticModel -_LINE_REGEX = r'^\s*(\d+)\s+(\d+)\s+([+-]?([0-9]*[.])?[0-9]+)\s*$' +_LINE_REGEX = r'^\s*(\d+)\s+(\d+)\s+([+-]?(?:[0-9]*[.]):?[0-9]+)\s*$' """ Each line should look like @@ -27,58 +27,70 @@ Each line should look like where 0, 1 are the variable lables and 2.0 is the bias. """ +_VARTYPE_HEADER_REGEX = r'^[ \t\f]*#.*?vartype[:=][ \t]*([-_.a-zA-Z0-9]+)' +""" +The header should be in the first line and look like + +# vartype=SPIN + +""" -def dumps(bqm): + +def dumps(bqm, vartype_header=False): """Dump a binary quadratic model to a string in COOrdinate format.""" - return '\n'.join(_iter_triplets(bqm)) + return '\n'.join(_iter_triplets(bqm, vartype_header)) -def dump(bqm, fp): +def dump(bqm, fp, vartype_header=False): """Dump a binary quadratic model to a string in COOrdinate format.""" - for triplet in _iter_triplets(bqm): + for triplet in _iter_triplets(bqm, vartype_header): fp.write('%s\n' % triplet) -def loads(s, bqm): +def loads(s, cls=BinaryQuadraticModel, vartype=None): """Load a COOrdinate formatted binary quadratic model from a string.""" - pattern = re.compile(_LINE_REGEX) - - for line in s.split('\n'): - match = pattern.search(line) + return load(s.split('\n'), cls=cls, vartype=vartype) - if match is not None: - u, v, bias = int(match.group(1)), int(match.group(2)), float(match.group(3)) - if u == v: - bqm.add_variable(u, bias) - else: - bqm.add_interaction(u, v, bias) - return bqm - - -def load(fp, bqm): +def load(fp, cls=BinaryQuadraticModel, vartype=None): """Load a COOrdinate formatted binary quadratic model from a file.""" pattern = re.compile(_LINE_REGEX) + vartype_pattern = re.compile(_VARTYPE_HEADER_REGEX) + triplets = [] for line in fp: - match = pattern.search(line) + triplets.extend(pattern.findall(line)) + + vt = vartype_pattern.findall(line) + if vt: + if vartype is None: + vartype = vt[0] + elif vartype is not vt[0]: + raise ValueError("vartypes from headers and/or inputs do not match") - if match is not None: - u, v, bias = int(match.group(1)), int(match.group(2)), float(match.group(3)) - if u == v: - bqm.add_variable(u, bias) - else: - bqm.add_interaction(u, v, bias) + if vartype is None: + raise ValueError("vartype must be provided either as a header or as an argument") + + bqm = cls.empty(vartype) + + for u, v, bias in triplets: + if u == v: + bqm.add_variable(int(u), float(bias)) + else: + bqm.add_interaction(int(u), int(v), float(bias)) return bqm -def _iter_triplets(bqm): +def _iter_triplets(bqm, vartype_header): if not isinstance(bqm, BinaryQuadraticModel): raise TypeError("expected input to be a BinaryQuadraticModel") if not all(isinstance(v, int) and v >= 0 for v in bqm.linear): raise ValueError("only positive index-labeled binary quadratic models can be dumped to COOrdinate format") + if vartype_header: + yield '# vartype=%s' % bqm.vartype.name + # developer note: we could (for some threshold sparseness) sort the neighborhoods, # but this is simple and probably sufficient
Support metadata in COO (like vartype) **Application** Currently, (de-)serialization of BQMs is partial and with loss of information - vartype is not stored/loaded. It would be nice to have a complete (de-)serialization of BQM to COO format, like we already have for JSON and BSON. E.g.: ``` bqm = BinaryQuadraticModel.from_coo(fp) bqm.to_coo(fp) ``` **Proposed Solution** Support `vartype` via `p` or `c` in COO.
dwavesystems/dimod
diff --git a/tests/test_io_coo.py b/tests/test_io_coo.py index dc38ca36..bc119f6f 100644 --- a/tests/test_io_coo.py +++ b/tests/test_io_coo.py @@ -40,17 +40,29 @@ class TestCOO(unittest.TestCase): contents = "0 0 1.000000\n0 1 2.000000\n2 3 0.400000" self.assertEqual(s, contents) + def test_dumps_sortable_SPIN_with_header(self): + bqm = dimod.BinaryQuadraticModel.from_ising({0: 1.}, {(0, 1): 2, (2, 3): .4}) + s = coo.dumps(bqm, vartype_header=True) + contents = "# vartype=SPIN\n0 0 1.000000\n0 1 2.000000\n2 3 0.400000" + self.assertEqual(s, contents) + + def test_dumps_sortable_BINARY_with_header(self): + bqm = dimod.BinaryQuadraticModel.from_qubo({(0, 0): 1., (0, 1): 2, (2, 3): .4}) + s = coo.dumps(bqm, vartype_header=True) + contents = "# vartype=BINARY\n0 0 1.000000\n0 1 2.000000\n2 3 0.400000" + self.assertEqual(s, contents) + def test_load(self): filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'coo_qubo.qubo') with open(filepath, 'r') as fp: - bqm = coo.load(fp, dimod.BinaryQuadraticModel.empty(dimod.BINARY)) + bqm = coo.load(fp, dimod.BinaryQuadraticModel, dimod.BINARY) self.assertEqual(bqm, dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1, (1, 1): -1, (2, 2): -1, (3, 3): -1})) def test_loads(self): contents = "0 0 1.000000\n0 1 2.000000\n2 3 0.400000" - bqm = coo.loads(contents, dimod.BinaryQuadraticModel.empty(dimod.SPIN)) + bqm = coo.loads(contents, dimod.BinaryQuadraticModel, dimod.SPIN) self.assertEqual(bqm, dimod.BinaryQuadraticModel.from_ising({0: 1.}, {(0, 1): 2, (2, 3): .4})) def test_functional_file_empty_BINARY(self): @@ -64,7 +76,7 @@ class TestCOO(unittest.TestCase): coo.dump(bqm, fp=file) with open(filename, 'r') as file: - new_bqm = coo.load(file, dimod.BinaryQuadraticModel.empty(dimod.BINARY)) + new_bqm = coo.load(file, dimod.BinaryQuadraticModel, dimod.BINARY) shutil.rmtree(tmpdir) @@ -81,7 +93,7 @@ class TestCOO(unittest.TestCase): coo.dump(bqm, fp=file) with open(filename, 'r') as file: - new_bqm = coo.load(file, dimod.BinaryQuadraticModel.empty(dimod.SPIN)) + new_bqm = coo.load(file, dimod.BinaryQuadraticModel, dimod.SPIN) shutil.rmtree(tmpdir) @@ -98,7 +110,7 @@ class TestCOO(unittest.TestCase): coo.dump(bqm, fp=file) with open(filename, 'r') as file: - new_bqm = coo.load(file, dimod.BinaryQuadraticModel.empty(dimod.BINARY)) + new_bqm = coo.load(file, dimod.BinaryQuadraticModel, dimod.BINARY) shutil.rmtree(tmpdir) @@ -115,7 +127,7 @@ class TestCOO(unittest.TestCase): coo.dump(bqm, fp=file) with open(filename, 'r') as file: - new_bqm = coo.load(file, dimod.BinaryQuadraticModel.empty(dimod.SPIN)) + new_bqm = coo.load(file, dimod.BinaryQuadraticModel, dimod.SPIN) shutil.rmtree(tmpdir) @@ -126,7 +138,7 @@ class TestCOO(unittest.TestCase): bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY) s = coo.dumps(bqm) - new_bqm = coo.loads(s, dimod.BinaryQuadraticModel.empty(dimod.BINARY)) + new_bqm = coo.loads(s, dimod.BinaryQuadraticModel, dimod.BINARY) self.assertEqual(bqm, new_bqm) @@ -135,7 +147,7 @@ class TestCOO(unittest.TestCase): bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN) s = coo.dumps(bqm) - new_bqm = coo.loads(s, dimod.BinaryQuadraticModel.empty(dimod.SPIN)) + new_bqm = coo.loads(s, dimod.BinaryQuadraticModel, dimod.SPIN) self.assertEqual(bqm, new_bqm) @@ -144,7 +156,7 @@ class TestCOO(unittest.TestCase): bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.BINARY) s = coo.dumps(bqm) - new_bqm = coo.loads(s, dimod.BinaryQuadraticModel.empty(dimod.BINARY)) + new_bqm = coo.loads(s, dimod.BinaryQuadraticModel, dimod.BINARY) self.assertEqual(bqm, new_bqm) @@ -153,6 +165,28 @@ class TestCOO(unittest.TestCase): bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.SPIN) s = coo.dumps(bqm) - new_bqm = coo.loads(s, dimod.BinaryQuadraticModel.empty(dimod.SPIN)) + new_bqm = coo.loads(s, dimod.BinaryQuadraticModel, dimod.SPIN) self.assertEqual(bqm, new_bqm) + + def test_functional_SPIN_vartypeheader(self): + bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.SPIN) + + s = coo.dumps(bqm, vartype_header=True) + new_bqm = coo.loads(s, dimod.BinaryQuadraticModel) + + self.assertEqual(bqm, new_bqm) + + def test_no_vartype(self): + bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.SPIN) + + s = coo.dumps(bqm) + with self.assertRaises(ValueError): + coo.loads(s, dimod.BinaryQuadraticModel) + + def test_conflicting_vartype(self): + bqm = dimod.BinaryQuadraticModel({0: 1.}, {(0, 1): 2, (2, 3): .4}, 0.0, dimod.SPIN) + + s = coo.dumps(bqm, vartype_header=True) + with self.assertRaises(ValueError): + coo.loads(s, dimod.BinaryQuadraticModel, dimod.BINARY)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 decorator==5.1.1 -e git+https://github.com/dwavesystems/dimod.git@53a6efa00f23cd87774579536d589433601adca7#egg=dimod idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 jsonschema==2.6.0 mock==2.0.0 networkx==2.0 numpy==1.15.0 packaging==21.3 pandas==0.22.0 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pymongo==3.7.1 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 six==1.11.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: dimod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonschema==2.6.0 - mock==2.0.0 - networkx==2.0 - numpy==1.15.0 - packaging==21.3 - pandas==0.22.0 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pymongo==3.7.1 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - six==1.11.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/dimod
[ "tests/test_io_coo.py::TestCOO::test_conflicting_vartype", "tests/test_io_coo.py::TestCOO::test_dumps_sortable_BINARY_with_header", "tests/test_io_coo.py::TestCOO::test_dumps_sortable_SPIN_with_header", "tests/test_io_coo.py::TestCOO::test_functional_SPIN_vartypeheader", "tests/test_io_coo.py::TestCOO::test_functional_file_BINARY", "tests/test_io_coo.py::TestCOO::test_functional_file_SPIN", "tests/test_io_coo.py::TestCOO::test_functional_file_empty_BINARY", "tests/test_io_coo.py::TestCOO::test_functional_file_empty_SPIN", "tests/test_io_coo.py::TestCOO::test_functional_string_BINARY", "tests/test_io_coo.py::TestCOO::test_functional_string_SPIN", "tests/test_io_coo.py::TestCOO::test_functional_string_empty_BINARY", "tests/test_io_coo.py::TestCOO::test_functional_string_empty_SPIN", "tests/test_io_coo.py::TestCOO::test_load", "tests/test_io_coo.py::TestCOO::test_loads", "tests/test_io_coo.py::TestCOO::test_no_vartype" ]
[]
[ "tests/test_io_coo.py::TestCOO::test_dumps_empty_BINARY", "tests/test_io_coo.py::TestCOO::test_dumps_empty_SPIN", "tests/test_io_coo.py::TestCOO::test_dumps_sortable_SPIN" ]
[]
Apache License 2.0
2,929
2,268
[ "dimod/binary_quadratic_model.py", "dimod/io/coo.py" ]
google__importlab-13
17edb0b8aae61e7dc2089fbafbd78504d975c221
2018-08-16 21:22:53
676d17cd41ac68de6ebb48fb71780ad6110c4ae3
diff --git a/importlab/import_finder.py b/importlab/import_finder.py index 35e11ff..47687d3 100644 --- a/importlab/import_finder.py +++ b/importlab/import_finder.py @@ -64,7 +64,10 @@ def _resolve_import_2(name): path = None for part in parts[i:]: try: - spec = imp.find_module(part, path) + if path: + spec = imp.find_module(part, [path]) + else: + spec = imp.find_module(part) except ImportError: return None path = spec[1] diff --git a/importlab/resolve.py b/importlab/resolve.py index c4c1a9c..23314bc 100644 --- a/importlab/resolve.py +++ b/importlab/resolve.py @@ -183,8 +183,8 @@ class Resolver: short_filename = os.path.dirname(filename) files.append((short_name, short_filename)) - for fs in self.fs_path: - for module_name, path in files: + for module_name, path in files: + for fs in self.fs_path: f = self._find_file(fs, path) if not f: continue @@ -214,6 +214,10 @@ class Resolver: pyfile = prefix + '.py' if os.path.exists(pyfile): return System(pyfile, mod_name) + elif not ext: + pyfile = os.path.join(prefix, "__init__.py") + if os.path.exists(pyfile): + return System(pyfile, mod_name) return System(item.source, mod_name) raise ImportException(name)
Importlab running under Python 3.6 and analyzing Python 2.7 can't find networkx Steps I took: sudo apt-get install python-pip pip install networkx # puts networkx in ~/.local/lib/python2.7/site-packages/ virtualenv --python=python3.6 .venv3 source .venv3/bin/activate pip install importlab echo "import networkx" > foo.py importlab -V2.7 foo.py --tree `foo.py` shows up as the only file in the tree. On the other hand, if I install importlab under Python 2.7 and analyze Python 3.5 code (I didn't try 3.6 because pip3 is 3.5 on my machine), the last command (correctly) causes a bunch of networkx files to be printed as part of the tree.
google/importlab
diff --git a/tests/test_resolve.py b/tests/test_resolve.py index 0d00214..df9e8a0 100644 --- a/tests/test_resolve.py +++ b/tests/test_resolve.py @@ -176,6 +176,18 @@ class TestResolver(unittest.TestCase): self.assertTrue(isinstance(f, resolve.System)) self.assertEqual(f.module_name, "foo.bar") + def testResolveSystemPackageDir(self): + with utils.Tempdir() as d: + py_file = d.create_file("foo/__init__.py") + imp = parsepy.ImportStatement("foo", + source=d["foo"], + is_from=True) + r = self.make_resolver("x.py", "x") + f = r.resolve_import(imp) + self.assertTrue(isinstance(f, resolve.System)) + self.assertEqual(f.module_name, "foo") + self.assertEqual(f.path, d["foo/__init__.py"]) + def testGetPyFromPycSource(self): # Override a source pyc file with the corresponding py file if it exists # in the native filesystem.
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 decorator==4.4.2 -e git+https://github.com/google/importlab.git@17edb0b8aae61e7dc2089fbafbd78504d975c221#egg=importlab importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work networkx==2.5.1 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: importlab channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - decorator==4.4.2 - networkx==2.5.1 - six==1.17.0 prefix: /opt/conda/envs/importlab
[ "tests/test_resolve.py::TestResolver::testResolveSystemPackageDir" ]
[]
[ "tests/test_resolve.py::TestResolver::testFallBackToSource", "tests/test_resolve.py::TestResolver::testGetPyFromPycSource", "tests/test_resolve.py::TestResolver::testOverrideSource", "tests/test_resolve.py::TestResolver::testPycSourceWithoutPy", "tests/test_resolve.py::TestResolver::testResolveBuiltin", "tests/test_resolve.py::TestResolver::testResolveInitFile", "tests/test_resolve.py::TestResolver::testResolveInitFileRelative", "tests/test_resolve.py::TestResolver::testResolveModuleFromFile", "tests/test_resolve.py::TestResolver::testResolvePackageFile", "tests/test_resolve.py::TestResolver::testResolveParentPackageFile", "tests/test_resolve.py::TestResolver::testResolveParentPackageFileWithModule", "tests/test_resolve.py::TestResolver::testResolvePyiFile", "tests/test_resolve.py::TestResolver::testResolveRelativeFromInitFileWithModule", "tests/test_resolve.py::TestResolver::testResolveRelativeInNonPackage", "tests/test_resolve.py::TestResolver::testResolveSamePackageFile", "tests/test_resolve.py::TestResolver::testResolveSiblingPackageFile", "tests/test_resolve.py::TestResolver::testResolveStarImport", "tests/test_resolve.py::TestResolver::testResolveStarImportBuiltin", "tests/test_resolve.py::TestResolver::testResolveStarImportSystem", "tests/test_resolve.py::TestResolver::testResolveSymbolFromFile", "tests/test_resolve.py::TestResolver::testResolveSystemInitFile", "tests/test_resolve.py::TestResolver::testResolveSystemRelative", "tests/test_resolve.py::TestResolver::testResolveSystemSymbol", "tests/test_resolve.py::TestResolver::testResolveSystemSymbolNameClash", "tests/test_resolve.py::TestResolver::testResolveTopLevel", "tests/test_resolve.py::TestResolver::testResolveWithFilesystem", "tests/test_resolve.py::TestResolverUtils::testGetAbsoluteName", "tests/test_resolve.py::TestResolverUtils::testInferModuleName" ]
[]
Apache License 2.0
2,933
397
[ "importlab/import_finder.py", "importlab/resolve.py" ]
DOV-Vlaanderen__pydov-79
68d5a639fa77fb9b03a89ca11a3dc49b1c823b27
2018-08-17 10:31:02
68d5a639fa77fb9b03a89ca11a3dc49b1c823b27
diff --git a/pydov/types/abstract.py b/pydov/types/abstract.py index e0398f9..b5217b0 100644 --- a/pydov/types/abstract.py +++ b/pydov/types/abstract.py @@ -520,8 +520,7 @@ class AbstractDovType(AbstractCommon): """ fields = self.get_field_names(return_fields) - ownfields = self.get_field_names(include_subtypes=False, - return_fields=return_fields) + ownfields = self.get_field_names(include_subtypes=False) subfields = [f for f in fields if f not in ownfields] if len(subfields) > 0:
Cannot use fields from a subtype as return fields. * PyDOV version: master * Python version: 3.6 * Operating System: Windows 10 ### Description Specifying a field from a subtype as return field gives an error if the resulting dataframe is non-empty. ### What I Did ``` import pydov.search.boring from owslib.fes import PropertyIsEqualTo bs = pydov.search.boring.BoringSearch() bs.search(query=query, return_fields=('pkey_boring',)) pkey_boring 0 https://www.dov.vlaanderen.be/data/boring/2004... bs.search(query=query, return_fields=('pkey_boring', 'boormethode')) Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Projecten\PyDov\pydov_git\pydov\search\boring.py", line 114, in search columns=Boring.get_field_names(return_fields)) File "C:\Users\rhbav33\python_virtualenvs\3.6_dev\lib\site-packages\pandas\core\frame.py", line 364, in __init__ data = list(data) File "C:\Projecten\PyDov\pydov_git\pydov\types\abstract.py", line 467, in to_df_array result = item.get_df_array(return_fields) File "C:\Projecten\PyDov\pydov_git\pydov\types\abstract.py", line 524, in get_df_array return_fields=return_fields) File "C:\Projecten\PyDov\pydov_git\pydov\types\abstract.py", line 386, in get_field_names raise InvalidFieldError("Unknown return field: '%s'" % rf) pydov.util.errors.InvalidFieldError: Unknown return field: 'boormethode' ```
DOV-Vlaanderen/pydov
diff --git a/tests/test_search_boring.py b/tests/test_search_boring.py index 8da9d97..d31f72a 100644 --- a/tests/test_search_boring.py +++ b/tests/test_search_boring.py @@ -365,6 +365,36 @@ class TestBoringSearch(AbstractTestSearch): assert list(df) == ['pkey_boring', 'boornummer', 'diepte_boring_tot', 'datum_aanvang'] + def test_search_returnfields_subtype(self, mp_remote_wfs_feature, + boringsearch): + """Test the search method with the query parameter and a selection of + return fields, including fields from a subtype. + + Test whether the output dataframe contains only the selected return + fields. + + Parameters + ---------- + mp_remote_wfs_feature : pytest.fixture + Monkeypatch the call to get WFS features. + boringsearch : pytest.fixture returning pydov.search.BoringSearch + An instance of BoringSearch to perform search operations on the DOV + type 'Boring'. + + """ + query = PropertyIsEqualTo(propertyname='boornummer', + literal='GEO-04/169-BNo-B1') + + df = boringsearch.search(query=query, + return_fields=('pkey_boring', 'boornummer', + 'diepte_methode_van', + 'diepte_methode_tot')) + + assert type(df) is DataFrame + + assert list(df) == ['pkey_boring', 'boornummer', 'diepte_methode_van', + 'diepte_methode_tot'] + def test_search_returnfields_order(self, mp_remote_wfs_feature, boringsearch): """Test the search method with the query parameter and a selection of diff --git a/tests/test_search_grondwaterfilter.py b/tests/test_search_grondwaterfilter.py index 5916163..d6c4ff7 100644 --- a/tests/test_search_grondwaterfilter.py +++ b/tests/test_search_grondwaterfilter.py @@ -380,6 +380,37 @@ class TestGrondwaterFilterSearch(AbstractTestSearch): assert list(df) == ['pkey_filter', 'gw_id', 'filternummer'] + def test_search_returnfields_subtype(self, mp_remote_wfs_feature, + grondwaterfiltersearch): + """Test the search method with the query parameter and a selection of + return fields, including fields from a subtype. + + Test whether the output dataframe contains only the selected return + fields. + + Parameters + ---------- + mp_remote_wfs_feature : pytest.fixture + Monkeypatch the call to get WFS features. + grondwaterfiltersearch : pytest.fixture returning + pydov.search.GrondwaterFilterSearch + An instance of GrondwaterFilterSearch to perform search operations + on the DOV type 'GrondwaterFilter'. + + """ + query = PropertyIsEqualTo(propertyname='filterfiche', + literal='https://www.dov.vlaanderen.be/' + 'data/filter/2003-004471') + + df = grondwaterfiltersearch.search( + query=query, return_fields=('pkey_filter', 'gw_id', + 'filternummer', 'peil_mtaw')) + + assert type(df) is DataFrame + + assert list(df) == ['pkey_filter', 'gw_id', 'filternummer', + 'peil_mtaw'] + def test_search_returnfields_order(self, mp_remote_wfs_feature, grondwaterfiltersearch): """Test the search method with the query parameter and a selection of
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-runner", "coverage", "Sphinx", "sphinx_rtd_theme", "numpydoc" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 dataclasses==0.8 docutils==0.18.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 lxml==5.3.1 MarkupSafe==2.0.1 numpy==1.19.5 numpydoc==1.1.0 OWSLib==0.31.0 packaging==21.3 pandas==1.1.5 pluggy==1.0.0 py==1.11.0 -e git+https://github.com/DOV-Vlaanderen/pydov.git@68d5a639fa77fb9b03a89ca11a3dc49b1c823b27#egg=pydov Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-runner==5.3.2 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: pydov channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - coverage==6.2 - dataclasses==0.8 - docutils==0.18.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - lxml==5.3.1 - markupsafe==2.0.1 - numpy==1.19.5 - numpydoc==1.1.0 - owslib==0.31.0 - packaging==21.3 - pandas==1.1.5 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-runner==5.3.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/pydov
[ "tests/test_search_boring.py::TestBoringSearch::test_search_returnfields_subtype" ]
[ "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_returnfields_subtype" ]
[ "tests/test_search_boring.py::TestBoringSearch::test_get_fields", "tests/test_search_boring.py::TestBoringSearch::test_search_both_location_query", "tests/test_search_boring.py::TestBoringSearch::test_search", "tests/test_search_boring.py::TestBoringSearch::test_search_returnfields", "tests/test_search_boring.py::TestBoringSearch::test_search_returnfields_order", "tests/test_search_boring.py::TestBoringSearch::test_search_wrongreturnfields", "tests/test_search_boring.py::TestBoringSearch::test_search_wrongreturnfieldstype", "tests/test_search_boring.py::TestBoringSearch::test_search_query_wrongfield", "tests/test_search_boring.py::TestBoringSearch::test_search_query_wrongfield_returnfield", "tests/test_search_boring.py::TestBoringSearch::test_search_extrareturnfields", "tests/test_search_boring.py::TestBoringSearch::test_search_xmlresolving", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_get_fields", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_both_location_query", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_returnfields", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_returnfields_order", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_wrongreturnfields", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_wrongreturnfieldstype", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_query_wrongfield", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_query_wrongfield_returnfield", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_extrareturnfields", "tests/test_search_grondwaterfilter.py::TestGrondwaterFilterSearch::test_search_xmlresolving" ]
[]
MIT License
2,935
163
[ "pydov/types/abstract.py" ]
conan-io__conan-3365
f966d516452380918437888811bc833c804dac39
2018-08-17 11:17:54
05d9ca8119dad8ebd45d49df64716cd7d92a51e5
CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/conan-io/conan?pullRequest=3365) <br/>Thank you for your submission, we really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/conan-io/conan?pullRequest=3365) before we can accept your contribution.<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/conan-io/conan?pullRequest=3365) it.</sub> danimtb: Hi @sigiesec Thanks a lot for this PR. Could you please fix the test with right spelling too? https://github.com/conan-io/conan/blob/f966d516452380918437888811bc833c804dac39/conans/test/model/version_ranges_test.py#L245 https://github.com/conan-io/conan/blob/f966d516452380918437888811bc833c804dac39/conans/test/model/version_ranges_test.py#L247 Many thanks!! sigiesec: @memshared Sorry I missed those tests. I did not find them by grepping because they said "override" rather than "overriden". I changed this to "overridden" now.
diff --git a/conans/client/graph/graph_builder.py b/conans/client/graph/graph_builder.py index a802a879b..c3e671d0e 100644 --- a/conans/client/graph/graph_builder.py +++ b/conans/client/graph/graph_builder.py @@ -140,7 +140,7 @@ class DepsGraphBuilder(object): def _config_node(self, node, down_reqs, down_ref, down_options): """ update settings and option in the current ConanFile, computing actual - requirement values, cause they can be overriden by downstream requires + requirement values, cause they can be overridden by downstream requires param settings: dict of settings values => {"os": "windows"} """ try: diff --git a/conans/client/rest/rest_client_common.py b/conans/client/rest/rest_client_common.py index e9b38a7dc..ecfa18bdd 100644 --- a/conans/client/rest/rest_client_common.py +++ b/conans/client/rest/rest_client_common.py @@ -212,16 +212,6 @@ class RestCommonMethods(object): url = self._recipe_url(conan_reference) + "/remove_files" return self._post_json(url, payload) - @handle_return_deserializer() - def _remove_package_files(self, package_reference, files): - """ Remove package files """ - self.check_credentials() - payload = {"files": [filename.replace("\\", "/") for filename in files]} - url = "%s/conans/%s/packages/%s/remove_files" % (self.remote_api_url, - "/".join(package_reference.conan), - package_reference.package_id) - return self._post_json(url, payload) - def _post_json(self, url, payload): response = self.requester.post(url, auth=self.auth, diff --git a/conans/client/rest/rest_client_v1.py b/conans/client/rest/rest_client_v1.py index c419b04fb..768472291 100644 --- a/conans/client/rest/rest_client_v1.py +++ b/conans/client/rest/rest_client_v1.py @@ -276,7 +276,9 @@ class RestV1Methods(RestCommonMethods): self._output.writeln("") self._upload_files(urls, files_to_upload, self._output, retry, retry_wait) if deleted: - self._remove_package_files(package_reference, deleted) + raise Exception("This shouldn't be happening, deleted files " + "in local package present in remote: %s.\n Please, report it at " + "https://github.com/conan-io/conan/issues " % str(deleted)) logger.debug("====> Time rest client upload_package: %f" % (time.time() - t1)) return files_to_upload or deleted diff --git a/conans/client/rest/uploader_downloader.py b/conans/client/rest/uploader_downloader.py index b52a9aac6..cff66cbfa 100644 --- a/conans/client/rest/uploader_downloader.py +++ b/conans/client/rest/uploader_downloader.py @@ -115,7 +115,7 @@ class Downloader(object): self.requester = requester self.verify = verify - def download(self, url, file_path=None, auth=None, retry=1, retry_wait=0, overwrite=False, + def download(self, url, file_path=None, auth=None, retry=3, retry_wait=0, overwrite=False, headers=None): if file_path and not os.path.isabs(file_path): @@ -130,10 +130,19 @@ class Downloader(object): # the dest folder before raise ConanException("Error, the file to download already exists: '%s'" % file_path) + return call_with_retry(self.output, retry, retry_wait, self._download_file, url, auth, + headers, file_path) + + def _download_file(self, url, auth, headers, file_path): t1 = time.time() - ret = bytearray() - response = call_with_retry(self.output, retry, retry_wait, self._download_file, url, auth, headers) - if not response.ok: # Do not retry if not found or whatever controlled error + + try: + response = self.requester.get(url, stream=True, verify=self.verify, auth=auth, + headers=headers) + except Exception as exc: + raise ConanException("Error downloading file %s: '%s'" % (url, exception_message_safe(exc))) + + if not response.ok: if response.status_code == 404: raise NotFoundException("Not found: %s" % url) elif response.status_code == 401: @@ -141,61 +150,10 @@ class Downloader(object): raise ConanException("Error %d downloading file %s" % (response.status_code, url)) try: - total_length = response.headers.get('content-length') - - if total_length is None: # no content length header - if not file_path: - ret += response.content - else: - total_length = len(response.content) - progress = human_readable_progress(total_length, total_length) - print_progress(self.output, 50, progress) - save_append(file_path, response.content) - else: - total_length = int(total_length) - encoding = response.headers.get('content-encoding') - gzip = (encoding == "gzip") - # chunked can be a problem: https://www.greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4 - # It will not send content-length or should be ignored - - def download_chunks(file_handler=None, ret_buffer=None): - """Write to a buffer or to a file handler""" - chunk_size = 1024 if not file_path else 1024 * 100 - download_size = 0 - last_progress = None - for data in response.iter_content(chunk_size=chunk_size): - download_size += len(data) - if ret_buffer is not None: - ret_buffer.extend(data) - if file_handler is not None: - file_handler.write(to_file_bytes(data)) - - units = progress_units(download_size, total_length) - progress = human_readable_progress(download_size, total_length) - if last_progress != units: # Avoid screen refresh if nothing has change - if self.output: - print_progress(self.output, units, progress) - last_progress = units - return download_size - - if file_path: - mkdir(os.path.dirname(file_path)) - with open(file_path, 'wb') as handle: - dl_size = download_chunks(file_handler=handle) - else: - dl_size = download_chunks(ret_buffer=ret) - - if dl_size != total_length and not gzip: - raise ConanException("Transfer interrupted before " - "complete: %s < %s" % (dl_size, total_length)) - + data = self._download_data(response, file_path) duration = time.time() - t1 log_download(url, duration) - - if not file_path: - return bytes(ret) - else: - return + return data except Exception as e: logger.debug(e.__class__) logger.debug(traceback.format_exc()) @@ -203,14 +161,62 @@ class Downloader(object): raise ConanConnectionError("Download failed, check server, possibly try again\n%s" % str(e)) - def _download_file(self, url, auth, headers): - try: - response = self.requester.get(url, stream=True, verify=self.verify, auth=auth, - headers=headers) - except Exception as exc: - raise ConanException("Error downloading file %s: '%s'" % (url, exception_message_safe(exc))) + def _download_data(self, response, file_path): + ret = bytearray() + total_length = response.headers.get('content-length') - return response + if total_length is None: # no content length header + if not file_path: + ret += response.content + else: + total_length = len(response.content) + progress = human_readable_progress(total_length, total_length) + print_progress(self.output, 50, progress) + save_append(file_path, response.content) + else: + total_length = int(total_length) + encoding = response.headers.get('content-encoding') + gzip = (encoding == "gzip") + # chunked can be a problem: https://www.greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4 + # It will not send content-length or should be ignored + + def download_chunks(file_handler=None, ret_buffer=None): + """Write to a buffer or to a file handler""" + chunk_size = 1024 if not file_path else 1024 * 100 + download_size = 0 + last_progress = None + for data in response.iter_content(chunk_size): + download_size += len(data) + if ret_buffer is not None: + ret_buffer.extend(data) + if file_handler is not None: + file_handler.write(to_file_bytes(data)) + + units = progress_units(download_size, total_length) + progress = human_readable_progress(download_size, total_length) + if last_progress != units: # Avoid screen refresh if nothing has change + if self.output: + print_progress(self.output, units, progress) + last_progress = units + return download_size + + if file_path: + mkdir(os.path.dirname(file_path)) + with open(file_path, 'wb') as handle: + dl_size = download_chunks(file_handler=handle) + else: + dl_size = download_chunks(ret_buffer=ret) + + response.close() + + if dl_size != total_length and not gzip: + raise ConanException("Transfer interrupted before " + "complete: %s < %s" % (dl_size, total_length)) + + if not file_path: + return bytes(ret) + else: + return def progress_units(progress, total): diff --git a/conans/model/requires.py b/conans/model/requires.py index ab8d03095..535771892 100644 --- a/conans/model/requires.py +++ b/conans/model/requires.py @@ -120,7 +120,7 @@ class Requirements(OrderedDict): # update dependency other_ref = other_req.conan_reference if other_ref and other_ref != req.conan_reference: - output.info("%s requirement %s overriden by %s to %s " + output.info("%s requirement %s overridden by %s to %s " % (own_ref, req.conan_reference, down_ref or "your conanfile", other_ref)) req.conan_reference = other_ref
"overridden" is misspelled as "overriden" This affects a few places, but most notably user messages output by conan.
conan-io/conan
diff --git a/conans/test/functional/client_certs_test.py b/conans/test/functional/client_certs_test.py index a571e2ecf..377e860b4 100644 --- a/conans/test/functional/client_certs_test.py +++ b/conans/test/functional/client_certs_test.py @@ -2,7 +2,7 @@ import os import unittest from conans import tools -from conans.test.utils.tools import TestClient, TestServer +from conans.test.utils.tools import TestClient class ClientCertsTest(unittest.TestCase): diff --git a/conans/test/functional/download_retries_test.py b/conans/test/functional/download_retries_test.py new file mode 100644 index 000000000..58c2f91fc --- /dev/null +++ b/conans/test/functional/download_retries_test.py @@ -0,0 +1,59 @@ +import unittest + +from conans.paths import CONANFILE +from conans.test.utils.tools import TestClient, TestServer + + +class DownloadRetriesTest(unittest.TestCase): + + def test_recipe_download_retry(self): + test_server = TestServer() + client = TestClient(servers={"default": test_server}, + users={"default": [("lasote", "mypass")]}) + + conanfile = '''from conans import ConanFile +class MyConanfile(ConanFile): + pass +''' + client.save({CONANFILE: conanfile}) + client.run("create . Pkg/0.1@lasote/stable") + client.run("upload '*' -c --all") + + class Response(object): + ok = None + status_code = None + charset = None + headers = {} + + def __init__(self, ok, status_code): + self.ok = ok + self.status_code = status_code + + @property + def content(self): + if not self.ok: + raise Exception("Bad boy") + else: + return b'{"conanfile.py": "path/to/fake/file"}' + + text = content + + class BuggyRequester(object): + + def __init__(self, *args, **kwargs): + pass + + def get(self, *args, **kwargs): + if "path/to/fake/file" not in args[0]: + return Response(True, 200) + else: + return Response(False, 200) + + # The buggy requester will cause a failure only downloading files, not in regular requests + client = TestClient(servers={"default": test_server}, + users={"default": [("lasote", "mypass")]}, + requester_class=BuggyRequester) + error = client.run("install Pkg/0.1@lasote/stable", ignore_error=True) + self.assertTrue(error) + self.assertEquals(str(client.out).count("Waiting 0 seconds to retry..."), 2) + self.assertEquals(str(client.out).count("ERROR: Error 200 downloading"), 3) diff --git a/conans/test/functional/require_override_test.py b/conans/test/functional/require_override_test.py index 1a7b209e4..fa7c259cf 100644 --- a/conans/test/functional/require_override_test.py +++ b/conans/test/functional/require_override_test.py @@ -75,5 +75,5 @@ class RequireOverrideTest(unittest.TestCase): "libC/1.0@user/channel", ("libA/1.0@user/channel", "override")]) self.client.run("create . user/channel") - self.assertIn("libA/2.0@user/channel overriden by project/1.0@user/channel", + self.assertIn("libA/2.0@user/channel overridden by project/1.0@user/channel", self.client.out) diff --git a/conans/test/model/transitive_reqs_test.py b/conans/test/model/transitive_reqs_test.py index b902dab53..7b0f08c53 100644 --- a/conans/test/model/transitive_reqs_test.py +++ b/conans/test/model/transitive_reqs_test.py @@ -465,7 +465,7 @@ class ChatConan(ConanFile): self.retriever.conan(bye_ref, bye_content2) deps_graph = self.root(chat_content) - self.assertIn("Hello/1.2@user/testing requirement Say/0.1@user/testing overriden by " + self.assertIn("Hello/1.2@user/testing requirement Say/0.1@user/testing overridden by " "your conanfile to Say/0.2@user/testing", self.output) self.assertNotIn("Conflict", self.output) self.assertEqual(4, len(deps_graph.nodes)) @@ -1539,7 +1539,7 @@ class LibDConan(ConanFile): with self.assertRaisesRegexp(ConanException, "Conflict in LibB/0.1@user/testing"): self.root(self.consumer_content) - self.assertIn("LibB/0.1@user/testing requirement LibA/0.1@user/testing overriden by " + self.assertIn("LibB/0.1@user/testing requirement LibA/0.1@user/testing overridden by " "LibD/0.1@user/testing to LibA/0.2@user/testing", str(self.output)) self.assertEqual(1, str(self.output).count("LibA requirements()")) self.assertEqual(1, str(self.output).count("LibA configure()")) diff --git a/conans/test/model/version_ranges_test.py b/conans/test/model/version_ranges_test.py index 2c4838c19..e42560f05 100644 --- a/conans/test/model/version_ranges_test.py +++ b/conans/test/model/version_ranges_test.py @@ -242,9 +242,9 @@ class ChatConan(ConanFile): chat = _get_nodes(deps_graph, "Chat")[0] edges = {Edge(hello, say), Edge(chat, hello)} if override is not None: - self.assertIn("override", self.output) + self.assertIn("overridden", self.output) else: - self.assertNotIn("override", self.output) + self.assertNotIn("overridden", self.output) if override is False: edges = {Edge(hello, say), Edge(chat, say), Edge(chat, hello)} diff --git a/conans/test/utils/tools.py b/conans/test/utils/tools.py index 7c882db0d..f4ea46fcd 100644 --- a/conans/test/utils/tools.py +++ b/conans/test/utils/tools.py @@ -69,6 +69,9 @@ class TestingResponse(object): def __init__(self, test_response): self.test_response = test_response + def close(self): + pass # Compatibility with close() method of a requests when stream=True + @property def headers(self): return self.test_response.headers
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 5 }
1.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc pkg-config" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==1.6.6 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@f966d516452380918437888811bc833c804dac39#egg=conan coverage==4.2 deprecation==2.0.7 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 node-semver==0.2.0 nose==1.3.7 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 Pygments==2.14.0 PyJWT==1.7.1 pylint==1.8.4 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.13 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==1.6.6 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - coverage==4.2 - deprecation==2.0.7 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - node-semver==0.2.0 - nose==1.3.7 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==1.8.4 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.13 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_solved", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_requirements" ]
[ "conans/test/functional/download_retries_test.py::DownloadRetriesTest::test_recipe_download_retry", "conans/test/functional/require_override_test.py::RequireOverrideTest::test_override" ]
[ "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic_option", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic_transitive_option", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_conditional", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_conditional_diamond", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_dep_requires_clear", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_error", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_options_solved", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_no_conflict", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_no_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_propagate_indirect_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_remove_build_requires", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_remove_two_build_requires", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_simple_override", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_diamond_private", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_pattern_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_private", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels_wrong_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_version_requires2_change", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_version_requires_change", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_avoid_duplicate_expansion", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_requirements_direct", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_basic", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config_remove", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config_remove2", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_errors", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_new_configure", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_transitive_two_levels_options", "conans/test/model/version_ranges_test.py::VersionRangesTest::test_local_basic", "conans/test/model/version_ranges_test.py::VersionRangesTest::test_remote_basic" ]
[]
MIT License
2,936
2,513
[ "conans/client/graph/graph_builder.py", "conans/client/rest/rest_client_common.py", "conans/client/rest/rest_client_v1.py", "conans/client/rest/uploader_downloader.py", "conans/model/requires.py" ]
EdinburghGenomics__pyclarity-lims-43
1a9f7d14e5597f7607ab85171432c7791d523d08
2018-08-17 21:33:16
a03be6eda34f0d8adaf776d2286198a34e40ecf5
diff --git a/pyclarity_lims/entities.py b/pyclarity_lims/entities.py index 9d22d8d..80bfaa1 100644 --- a/pyclarity_lims/entities.py +++ b/pyclarity_lims/entities.py @@ -200,6 +200,9 @@ class Note(Entity): class File(Entity): """File attached to a project or a sample.""" + _URI = 'files' + _PREFIX = 'file' + attached_to = StringDescriptor('attached-to') """The uri of the Entity this file is attached to""" content_location = StringDescriptor('content-location') @@ -379,7 +382,7 @@ class Process(Entity): _CREATION_PREFIX = 'prx' type = EntityDescriptor('type', Processtype) - """The :py:class:`type <pyclarity_lims.entities.ProcessType>` of the process""" + """The :py:class:`type <pyclarity_lims.entities.Processtype>` of the process""" date_run = StringDescriptor('date-run') """The date at which the process was finished in format Year-Month-Day i.e. 2016-12-05.""" technician = EntityDescriptor('technician', Researcher) @@ -407,7 +410,10 @@ class Process(Entity): """ udf = UdfDictionaryDescriptor() - """Dictionary of UDFs associated with the process.""" + """Dictionary of UDFs associated with the process. + + Note that the UDFs cannot be modify in Process. Use :py:class:`Step details <pyclarity_lims.entities.StepDetails>` + to modify UDFs instead. You can access them with process.step.details.udf""" udt = UdtDictionaryDescriptor() """Dictionary of UDTs associated with the process.""" files = EntityListDescriptor(nsmap('file:file'), File) @@ -420,13 +426,17 @@ class Process(Entity): def outputs_per_input(self, inart, ResultFile=False, SharedResultFile=False, Analyte=False): """Getting all the output artifacts related to a particular input artifact - :param inart: input artifact id use to select the output + :param inart: input artifact id or artifact entity use to select the output :param ResultFile: boolean specifying to only return ResultFiles. :param SharedResultFile: boolean specifying to only return SharedResultFiles. :param Analyte: boolean specifying to only return Analytes. :return: output artifact corresponding to the input artifact provided """ - inouts = [io for io in self.input_output_maps if io[0]['limsid'] == inart] + if isinstance(Artifact, inart): + inouts = [io for io in self.input_output_maps if io[0]['uri'] == inart] + else: + inouts = [io for io in self.input_output_maps if io[0]['limsid'] == inart] + if ResultFile: inouts = [io for io in inouts if io[1]['output-type'] == 'ResultFile'] elif SharedResultFile: @@ -490,15 +500,38 @@ class Process(Entity): else: return [Artifact(self.lims, id=id) for id in ids if id is not None] - def shared_result_files(self): - """Retrieve all resultfiles of output-generation-type PerAllInputs.""" - artifacts = self.all_outputs(unique=True) - return [a for a in artifacts if a.output_type == 'SharedResultFile'] + def _output_files(self, resfile, output_generation_type): + if output_generation_type: + artifacts = [ + io[1]['uri'] for io in self.input_output_maps + if io[1] is not None + and io[1]['output-type'] == resfile + and io[1]['output-generation-type'] == output_generation_type + ] + else: + artifacts = [ + io[1]['uri'] for io in self.input_output_maps + if io[1] is not None and io[1]['output-type'] == resfile + ] + return list(set(artifacts)) - def result_files(self): - """Retrieve all resultfiles of output-generation-type perInput.""" - artifacts = self.all_outputs(unique=True) - return [a for a in artifacts if a.output_type == 'ResultFile'] + def shared_result_files(self, output_generation_type=None): + """Retrieve all output artifacts where output-type is SharedResultFile. + + :param output_generation_type: string specifying the output-generation-type (PerAllInputs or PerInput) + :return: list of output artifacts. + + """ + return self._output_files('SharedResultFile', output_generation_type) + + def result_files(self, output_generation_type=None): + """Retrieve all output artifacts where output-type is ResultFile. + + :param output_generation_type: string specifying the output-generation-type (PerAllInputs or PerInput) + :return: list of output artifacts. + + """ + return self._output_files('ResultFile', output_generation_type) def analytes(self): """Retrieving the output Analytes of the process, if existing. diff --git a/pyclarity_lims/lims.py b/pyclarity_lims/lims.py index 532b315..ee33165 100644 --- a/pyclarity_lims/lims.py +++ b/pyclarity_lims/lims.py @@ -231,7 +231,7 @@ class Lims(object): start_index=start_index) return self._get_instances(Udfconfig, add_info=add_info, nb_pages=nb_pages, params=params) - def get_reagent_types(self, name=None, start_index=None, nb_pages=-1): + def get_reagent_types(self, name=None, start_index=None, nb_pages=-1, add_info=False): """ Get a list of reagent types, filtered by keyword arguments. @@ -239,10 +239,12 @@ class Lims(object): :param start_index: first element to retrieve; start at first element if None. :param nb_pages: number of page to iterate over. The page size is 500 by default unless configured otherwise in your LIMS. 0 or negative numbers returns all pages. + :param add_info: Change the return type to a tuple where the first element is normal return and + the second is a dict of additional information provided in the query. + """ - params = self._get_params(name=name, - start_index=start_index) - return self._get_instances(ReagentType, nb_pages=nb_pages, params=params) + params = self._get_params(name=name, start_index=start_index) + return self._get_instances(ReagentType, nb_pages=nb_pages, add_info=add_info, params=params) def get_labs(self, name=None, last_modified=None, udf=dict(), udtname=None, udt=dict(), start_index=None, nb_pages=-1, add_info=False): @@ -508,18 +510,6 @@ class Lims(object): params = self._get_params(displayname=displayname) return self._get_instances(Processtype, add_info=add_info, params=params) - def get_reagent_types(self, name=None, add_info=False): - """ - Get a list of reagent types with the specified name. - - :param name: The name the reagent type - :param add_info: Change the return type to a tuple where the first element is normal return and - the second is a dict of additional information provided in the query. - - """ - params = self._get_params(name=name) - return self._get_instances(ReagentType, add_info=add_info, params=params) - def get_protocols(self, name=None, add_info=False): """ Get a list of existing protocols on the system.
Lims.get_reagent_types is defined twice Which one do we want?
EdinburghGenomics/pyclarity-lims
diff --git a/tests/test_entities.py b/tests/test_entities.py index f7835fc..27f5e9b 100644 --- a/tests/test_entities.py +++ b/tests/test_entities.py @@ -2,7 +2,7 @@ from sys import version_info from unittest import TestCase from xml.etree import ElementTree from pyclarity_lims.entities import ProtocolStep, StepActions, Researcher, Artifact, \ - Step, StepPlacements, Container, Stage, ReagentKit, ReagentLot, Sample, Project + Step, StepPlacements, Container, Stage, ReagentKit, ReagentLot, Sample, Project, Process from pyclarity_lims.lims import Lims from tests import NamedMock, elements_equal if version_info[0] == 2: @@ -163,6 +163,43 @@ generic_sample_creation_xml = """ </smp:samplecreation> """ +generic_process_xml = """ +<prc:process xmlns:udf="http://genologics.com/ri/userdefined" xmlns:file="http://genologics.com/ri/file" xmlns:prc="http://genologics.com/ri/process" uri="{url}/api/v2/processes/p2" limsid="p2"> +<type uri="{url}/api/v2/processtypes/pt1">Step Name 5.0</type> +<date-run>2018-06-12</date-run> +<technician uri="{url}/api/v2/researchers/1"> +<first-name>Bob</first-name> +<last-name>Marley</last-name> +</technician> +<input-output-map> +<input post-process-uri="{url}/api/v2/artifacts/a1" uri="{url}/api/v2/artifacts/a1" limsid="a1"> +<parent-process uri="{url}/api/v2/processes/p1" limsid="p1"/> +</input> +<output uri="{url}/api/v2/artifacts/ao1" output-generation-type="PerAllInputs" output-type="ResultFile" limsid="ao1"/> +</input-output-map> +<input-output-map> +<input post-process-uri="{url}/api/v2/artifacts/a2" uri="{url}/api/v2/artifacts/a2" limsid="a2"> +<parent-process uri="{url}/api/v2/processes/p1" limsid="p1"/> +</input> +<output uri="{url}/api/v2/artifacts/ao1" output-generation-type="PerAllInputs" output-type="ResultFile" limsid="ao1"/> +</input-output-map> +<input-output-map> +<input post-process-uri="{url}/api/v2/artifacts/a1" uri="{url}/api/v2/artifacts/a1" limsid="a1"> +<parent-process uri="{url}/api/v2/processes/p1" limsid="p1"/> +</input> +<output uri="{url}/api/v2/artifacts/ao2" output-generation-type="PerInput" output-type="ResultFile" limsid="ao2"/> +</input-output-map> +<input-output-map> +<input post-process-uri="{url}/api/v2/artifacts/a2" uri="{url}/api/v2/artifacts/a2" limsid="a2"> +<parent-process uri="{url}/api/v2/processes/p1" limsid="p1"/> +</input> +<output uri="{url}/api/v2/artifacts/ao3" output-generation-type="PerInput" output-type="ResultFile" limsid="ao3"/> +</input-output-map> +<udf:field type="Numeric" name="Count">15</udf:field> +<process-parameter name="parameter1"/> +</prc:process> +""" + class TestEntities(TestCase): dummy_xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> @@ -430,3 +467,14 @@ class TestSample(TestEntities): </location> </smp:samplecreation>''' assert elements_equal(ElementTree.fromstring(patch_post.call_args_list[0][1]['data']), ElementTree.fromstring(data)) + + +class TestProcess(TestEntities): + process_xml = generic_process_xml.format(url=url) + + def test_result_files(self): + p = Process(uri=self.lims.get_uri('processes', 'p2'), lims=self.lims) + with patch('requests.Session.get', return_value=Mock(content=self.process_xml, status_code=200)): + assert len(p.result_files()) == 3 + assert len(p.result_files(output_generation_type='PerAllInputs')) == 1 + assert len(p.result_files(output_generation_type='PerInput')) == 2
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 -e git+https://github.com/EdinburghGenomics/pyclarity-lims.git@1a9f7d14e5597f7607ab85171432c7791d523d08#egg=pyclarity_lims pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: pyclarity-lims channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/pyclarity-lims
[ "tests/test_entities.py::TestProcess::test_result_files" ]
[]
[ "tests/test_entities.py::TestStepActions::test_escalation", "tests/test_entities.py::TestStepActions::test_next_actions", "tests/test_entities.py::TestStepPlacements::test_get_placements_list", "tests/test_entities.py::TestStepPlacements::test_set_placements_list", "tests/test_entities.py::TestStepPlacements::test_set_placements_list_fail", "tests/test_entities.py::TestStep::test_advance", "tests/test_entities.py::TestStep::test_create", "tests/test_entities.py::TestStep::test_create2", "tests/test_entities.py::TestStep::test_parse_entity", "tests/test_entities.py::TestStep::test_trigger_program", "tests/test_entities.py::TestArtifacts::test_input_artifact_list", "tests/test_entities.py::TestArtifacts::test_workflow_stages_and_statuses", "tests/test_entities.py::TestReagentKits::test_create_entity", "tests/test_entities.py::TestReagentKits::test_parse_entity", "tests/test_entities.py::TestReagentLots::test_create_entity", "tests/test_entities.py::TestReagentLots::test_parse_entity", "tests/test_entities.py::TestSample::test_create_entity" ]
[]
MIT License
2,939
1,820
[ "pyclarity_lims/entities.py", "pyclarity_lims/lims.py" ]
Azure__WALinuxAgent-1304
dd3daa66040258a22b994d8f139a0d9c9bab3e6a
2018-08-18 00:09:55
6e9b985c1d7d564253a1c344bab01b45093103cd
diff --git a/azurelinuxagent/common/errorstate.py b/azurelinuxagent/common/errorstate.py index 38aaa1f9..052db075 100644 --- a/azurelinuxagent/common/errorstate.py +++ b/azurelinuxagent/common/errorstate.py @@ -31,3 +31,15 @@ class ErrorState(object): return True return False + + @property + def fail_time(self): + if self.timestamp is None: + return 'unknown' + + delta = round((datetime.utcnow() - self.timestamp).seconds / 60.0, 2) + if delta < 60: + return '{0} min'.format(delta) + + delta_hr = round(delta / 60.0, 2) + return '{0} hr'.format(delta_hr) diff --git a/azurelinuxagent/common/event.py b/azurelinuxagent/common/event.py index 71723d45..4852bb37 100644 --- a/azurelinuxagent/common/event.py +++ b/azurelinuxagent/common/event.py @@ -58,6 +58,7 @@ class WALAEventOperation: HeartBeat = "HeartBeat" HostPlugin = "HostPlugin" HostPluginHeartbeat = "HostPluginHeartbeat" + HostPluginHeartbeatExtended = "HostPluginHeartbeatExtended" HttpErrors = "HttpErrors" ImdsHeartbeat = "ImdsHeartbeat" Install = "Install" diff --git a/azurelinuxagent/ga/monitor.py b/azurelinuxagent/ga/monitor.py index e28d7321..c1215806 100644 --- a/azurelinuxagent/ga/monitor.py +++ b/azurelinuxagent/ga/monitor.py @@ -336,6 +336,15 @@ class MonitorHandler(object): self.health_service.report_host_plugin_heartbeat(is_healthy) + if not is_healthy: + add_event( + name=AGENT_NAME, + version=CURRENT_VERSION, + op=WALAEventOperation.HostPluginHeartbeatExtended, + is_success=False, + message='{0} since successful heartbeat'.format(self.host_plugin_errorstate.fail_time), + log_event=False) + except Exception as e: msg = "Exception sending host plugin heartbeat: {0}".format(ustr(e)) add_event(
InitializeHostPlugin This event is useful, but we should also have an extended version, like we do for ReportStatus. There is a good location for this in the [monitor thread](https://github.com/Azure/WALinuxAgent/blob/master/azurelinuxagent/ga/monitor.py#L335)
Azure/WALinuxAgent
diff --git a/tests/common/test_errorstate.py b/tests/common/test_errorstate.py index 7513fe59..a0a7761d 100644 --- a/tests/common/test_errorstate.py +++ b/tests/common/test_errorstate.py @@ -12,6 +12,7 @@ class TestErrorState(unittest.TestCase): test_subject = ErrorState(timedelta(seconds=10000)) self.assertFalse(test_subject.is_triggered()) self.assertEqual(0, test_subject.count) + self.assertEqual('unknown', test_subject.fail_time) def test_errorstate01(self): """ @@ -21,6 +22,7 @@ class TestErrorState(unittest.TestCase): test_subject = ErrorState(timedelta(seconds=0)) self.assertFalse(test_subject.is_triggered()) self.assertEqual(0, test_subject.count) + self.assertEqual('unknown', test_subject.fail_time) def test_errorstate02(self): """ @@ -30,9 +32,9 @@ class TestErrorState(unittest.TestCase): test_subject = ErrorState(timedelta(seconds=0)) test_subject.incr() - self.assertTrue(test_subject.is_triggered()) self.assertEqual(1, test_subject.count) + self.assertEqual('0.0 min', test_subject.fail_time) @patch('azurelinuxagent.common.errorstate.datetime') def test_errorstate03(self, mock_time): @@ -52,6 +54,7 @@ class TestErrorState(unittest.TestCase): mock_time.utcnow = Mock(return_value=datetime.utcnow() + timedelta(minutes=30)) test_subject.incr() self.assertTrue(test_subject.is_triggered()) + self.assertEqual('29.0 min', test_subject.fail_time) def test_errorstate04(self): """ @@ -67,3 +70,35 @@ class TestErrorState(unittest.TestCase): test_subject.reset() self.assertTrue(test_subject.timestamp is None) + + def test_errorstate05(self): + """ + Test the fail_time for various scenarios + """ + + test_subject = ErrorState(timedelta(minutes=15)) + self.assertEqual('unknown', test_subject.fail_time) + + test_subject.incr() + self.assertEqual('0.0 min', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=60) + self.assertEqual('1.0 min', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=73) + self.assertEqual('1.22 min', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=120) + self.assertEqual('2.0 min', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=60 * 59) + self.assertEqual('59.0 min', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=60 * 60) + self.assertEqual('1.0 hr', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=60 * 95) + self.assertEqual('1.58 hr', test_subject.fail_time) + + test_subject.timestamp = datetime.utcnow() - timedelta(seconds=60 * 60 * 3) + self.assertEqual('3.0 hr', test_subject.fail_time) diff --git a/tests/ga/test_monitor.py b/tests/ga/test_monitor.py index 5d53b1e7..4bcc1da4 100644 --- a/tests/ga/test_monitor.py +++ b/tests/ga/test_monitor.py @@ -201,4 +201,18 @@ class TestMonitor(AgentTestCase): monitor_handler.last_host_plugin_heartbeat = datetime.datetime.utcnow() - timedelta(hours=1) monitor_handler.send_host_plugin_heartbeat() self.assertEqual(1, patch_report_heartbeat.call_count) + self.assertEqual(0, args[5].call_count) + monitor_handler.stop() + + @patch('azurelinuxagent.common.errorstate.ErrorState.is_triggered', return_value=True) + @patch("azurelinuxagent.common.protocol.healthservice.HealthService.report_host_plugin_heartbeat") + def test_failed_heartbeat_creates_telemetry(self, patch_report_heartbeat, _, *args): + monitor_handler = get_monitor_handler() + monitor_handler.init_protocols() + monitor_handler.last_host_plugin_heartbeat = datetime.datetime.utcnow() - timedelta(hours=1) + monitor_handler.send_host_plugin_heartbeat() + self.assertEqual(1, patch_report_heartbeat.call_count) + self.assertEqual(1, args[5].call_count) + self.assertEqual('HostPluginHeartbeatExtended', args[5].call_args[1]['op']) + self.assertEqual(False, args[5].call_args[1]['is_success']) monitor_handler.stop()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 3 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pyasn1", "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyasn1==0.5.1 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work -e git+https://github.com/Azure/WALinuxAgent.git@dd3daa66040258a22b994d8f139a0d9c9bab3e6a#egg=WALinuxAgent zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: WALinuxAgent channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - pyasn1==0.5.1 prefix: /opt/conda/envs/WALinuxAgent
[ "tests/common/test_errorstate.py::TestErrorState::test_errorstate00", "tests/common/test_errorstate.py::TestErrorState::test_errorstate01", "tests/common/test_errorstate.py::TestErrorState::test_errorstate02", "tests/common/test_errorstate.py::TestErrorState::test_errorstate03", "tests/common/test_errorstate.py::TestErrorState::test_errorstate05", "tests/ga/test_monitor.py::TestMonitor::test_failed_heartbeat_creates_telemetry" ]
[]
[ "tests/common/test_errorstate.py::TestErrorState::test_errorstate04", "tests/ga/test_monitor.py::TestMonitor::test_add_sysinfo", "tests/ga/test_monitor.py::TestMonitor::test_heartbeat_creates_signal", "tests/ga/test_monitor.py::TestMonitor::test_heartbeat_timings_no_updates_within_window", "tests/ga/test_monitor.py::TestMonitor::test_heartbeat_timings_updates_after_window", "tests/ga/test_monitor.py::TestMonitor::test_heartbeats", "tests/ga/test_monitor.py::TestMonitor::test_parse_xml_event" ]
[]
Apache License 2.0
2,941
559
[ "azurelinuxagent/common/errorstate.py", "azurelinuxagent/common/event.py", "azurelinuxagent/ga/monitor.py" ]
sciunto-org__python-bibtexparser-213
37bd93927d1380f040d391dc132eaf04fbe279af
2018-08-20 13:58:54
f4a2d8b00ae7775cbbc1758e791081d93c4fb7c1
coveralls: [![Coverage Status](https://coveralls.io/builds/18570156/badge)](https://coveralls.io/builds/18570156) Coverage decreased (-0.2%) to 97.43% when pulling **a2a628a32acff1b75da9a10ab0f475c81dc53a4f on omangin:fix/163** into **3344a1aa8e3059a8283aa96c99a68f272d686d9d on sciunto-org:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/18570156/badge)](https://coveralls.io/builds/18570156) Coverage decreased (-0.2%) to 97.43% when pulling **a2a628a32acff1b75da9a10ab0f475c81dc53a4f on omangin:fix/163** into **3344a1aa8e3059a8283aa96c99a68f272d686d9d on sciunto-org:master**.
diff --git a/bibtexparser/bibtexexpression.py b/bibtexparser/bibtexexpression.py index ac679e4..e15bb21 100644 --- a/bibtexparser/bibtexexpression.py +++ b/bibtexparser/bibtexexpression.py @@ -34,36 +34,35 @@ def add_logger_parse_action(expr, log_func): # Parse action helpers # Helpers for returning values from the parsed tokens. Shaped as pyparsing's -# parse actions. In pyparsing wording: -# s, l, t, stand for string, location, token +# parse actions. See pyparsing documentation for the arguments. -def first_token(s, l, t): +def first_token(string_, location, token): # TODO Handle this case correctly! - assert(len(t) == 1) - return t[0] + assert(len(token) == 1) + return token[0] -def remove_trailing_newlines(s, l, t): - if t[0]: - return t[0].rstrip('\n') +def remove_trailing_newlines(string_, location, token): + if token[0]: + return token[0].rstrip('\n') -def remove_braces(s, l, t): - if len(t[0]) < 1: +def remove_braces(string_, location, token): + if len(token[0]) < 1: return '' else: - start = 1 if t[0][0] == '{' else 0 - end = -1 if t[0][-1] == '}' else None - return t[0][start:end] + start = 1 if token[0][0] == '{' else 0 + end = -1 if token[0][-1] == '}' else None + return token[0][start:end] -def field_to_pair(s, l, t): +def field_to_pair(string_, location, token): """ Looks for parsed element named 'Field'. :returns: (name, value). """ - f = t.get('Field') + f = token.get('Field') return (f.get('FieldName'), strip_after_new_lines(f.get('Value'))) @@ -149,9 +148,28 @@ class BibtexExpression(object): entry_type.setParseAction(first_token) # Entry key: any character up to a ',' without leading and trailing - # spaces. - key = pp.SkipTo(',')('Key') # Exclude @',\#}{~% - key.setParseAction(lambda s, l, t: first_token(s, l, t).strip()) + # spaces. Also exclude spaces and prevent it from being empty. + key = pp.SkipTo(',')('Key') # TODO Maybe also exclude @',\#}{~% + + def citekeyParseAction(string_, location, token): + """Parse action for validating citekeys. + + It ensures citekey is not empty and has no space. + + :args: see pyparsing documentation. + """ + key = first_token(string_, location, token).strip() + if len(key) < 1: + raise self.ParseException( + string_, loc=location, msg="Empty citekeys are not allowed.") + for i, c in enumerate(key): + if c.isspace(): + raise self.ParseException( + string_, loc=(location + i), + msg="Whitespace not allowed in citekeys.") + return key + + key.setParseAction(citekeyParseAction) # Field name: word of letters, digits, dashes and underscores field_name = pp.Word(pp.alphanums + '_-().+')('FieldName')
Records with no ID parsed incorrectly Given the following record: > @misc{ author = {AMAP}, title = {Summary – The Greenland Ice Sheet in a Changing Climate: Snow, Water, Ice and Permafrost in the Arctic (SWIPA)}, publisher = {Arctic Monitoring and Assessment Programme (AMAP)}, pages = {22 pp.}, year = {2009}, type = {Generic}, } The parser sets ID as "author = {AMAP" and doesn't recognize the author field. Changing `re.split(',\s*\n|\n\s*,', record)` to `re.split('(?<={)\s*\n|,\s*\n|\n\s*,', record)` line 239 of bparser.py seems to fix the problem.
sciunto-org/python-bibtexparser
diff --git a/bibtexparser/tests/test_bibtexexpression.py b/bibtexparser/tests/test_bibtexexpression.py index 1306861..1bcab43 100644 --- a/bibtexparser/tests/test_bibtexexpression.py +++ b/bibtexparser/tests/test_bibtexexpression.py @@ -58,6 +58,26 @@ class TestBibtexExpression(unittest.TestCase): def test_entry_declaration_after_space(self): self.expr.entry.parseString(' @journal{key, name = {abcd}}') + def test_entry_declaration_no_key(self): + with self.assertRaises(self.expr.ParseException): + self.expr.entry.parseString('@misc{name = {abcd}}') + + def test_entry_declaration_no_key_new_line(self): + with self.assertRaises(self.expr.ParseException): + self.expr.entry.parseString('@misc{\n name = {abcd}}') + + def test_entry_declaration_no_key_comma(self): + with self.assertRaises(self.expr.ParseException): + self.expr.entry.parseString('@misc{, \nname = {abcd}}') + + def test_entry_declaration_no_key_keyvalue_without_space(self): + with self.assertRaises(self.expr.ParseException): + self.expr.entry.parseString('@misc{\nname=aaa}') + + def test_entry_declaration_key_with_whitespace(self): + with self.assertRaises(self.expr.ParseException): + self.expr.entry.parseString('@misc{ xx yy, \n name = aaa}') + def test_string_declaration_after_space(self): self.expr.string_def.parseString(' @string{ name = {abcd}}') diff --git a/bibtexparser/tests/test_bparser.py b/bibtexparser/tests/test_bparser.py index 479ac34..516411a 100644 --- a/bibtexparser/tests/test_bparser.py +++ b/bibtexparser/tests/test_bparser.py @@ -612,6 +612,13 @@ class TestBibtexParserList(unittest.TestCase): self.assertEqual(res_dict, expected_dict) self.assertEqual(bib.preambles, ["Blah blah"]) + def test_no_citekey_parsed_as_comment(self): + bib = BibTexParser('@BOOK{, title = "bla"}') + self.assertEqual(bib.entries, []) + self.assertEqual(bib.preambles, []) + self.assertEqual(bib.strings, {}) + self.assertEqual(bib.comments, ['@BOOK{, title = "bla"}']) + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "nose-cov", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/sciunto-org/python-bibtexparser.git@37bd93927d1380f040d391dc132eaf04fbe279af#egg=bibtexparser cov-core==1.15.0 coverage==7.8.0 exceptiongroup==1.2.2 future==1.0.0 iniconfig==2.1.0 linecache2==1.0.0 nose==1.3.7 nose-cov==1.6 packaging==24.2 pluggy==1.5.0 pyparsing==3.2.3 pytest==8.3.5 six==1.17.0 tomli==2.2.1 traceback2==1.4.0 unittest2==1.1.0
name: python-bibtexparser channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - cov-core==1.15.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - future==1.0.0 - iniconfig==2.1.0 - linecache2==1.0.0 - nose==1.3.7 - nose-cov==1.6 - packaging==24.2 - pluggy==1.5.0 - pyparsing==3.2.3 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 - traceback2==1.4.0 - unittest2==1.1.0 prefix: /opt/conda/envs/python-bibtexparser
[ "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_key_with_whitespace", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_no_key_comma", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_no_citekey_parsed_as_comment" ]
[ "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_braced", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_braced_unicode", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_braced_with_new_line", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_capital_key", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_capital_type", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_declaration_after_space", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_declaration_after_space_and_comment", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_after_space", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_minimal", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_quoted", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_quoted_with_new_line", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_quoted_with_unicode", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_annotation", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_comma_first", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_cust_latex", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_cust_order", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_cust_unicode", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_missing_coma", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_no_braces", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_protection_braces", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_special_characters", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_start_bom", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_article_start_with_whitespace", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_book", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_book_cust_latex", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_book_cust_unicode", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_comments_spaces_and_declarations", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_encoding", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_encoding_with_homogenize", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_features", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_features2", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_field_name_with_dash_underscore", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_nonstandard_ignored", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_nonstandard_not_ignored", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_oneline", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_string_definitions", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_string_is_interpolated", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_string_is_not_interpolated", "bibtexparser/tests/test_bparser.py::TestBibtexParserList::test_traps" ]
[ "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_no_key", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_no_key_keyvalue_without_space", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_entry_declaration_no_key_new_line", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_preamble_declaration_after_space", "bibtexparser/tests/test_bibtexexpression.py::TestBibtexExpression::test_string_declaration_after_space" ]
[]
MIT License
2,950
847
[ "bibtexparser/bibtexexpression.py" ]
python-pillow__Pillow-3310
1e56ed8c000bfffb198de097fb76c7252904059b
2018-08-21 10:55:50
78c8b1f341919a4f7e19e29056713d8f738c9c88
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 66b211cbf..6663ea5f1 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1396,8 +1396,9 @@ def _save(im, fp, filename): ifd = ImageFileDirectory_v2(prefix=prefix) - compression = im.encoderinfo.get('compression', - im.info.get('compression', 'raw')) + compression = im.encoderinfo.get('compression', im.info.get('compression')) + if compression is None: + compression = 'raw' libtiff = WRITE_LIBTIFF or compression != 'raw'
Libtiff encoder, argument 3 must be str, not None ### What did you do? ```python im = Image.fromarray(dataset[:]) format = 'tiff' im.save(f, format=format, compression=None) ``` ### What did you expect to happen? File to be saved. ### What actually happened? ``` File "../hdf5/base_hdf5.py", line 439, in upload_dataset im.save(f, format=format, compression=None) File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 1950, in save save_handler(self, fp, filename) File "/usr/local/lib/python3.7/site-packages/PIL/TiffImagePlugin.py", line 1533, in _save e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig) File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 469, in _getencoder return encoder(mode, *args + extra) TypeError: argument 3 must be str, not None ``` ### What versions of Pillow and Python are you using? Python 3.7, just installed Pillow today.
python-pillow/Pillow
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 77caa0b9d..855ec1e63 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -486,7 +486,7 @@ class TestFileLibTiff(LibTiffTestCase): pilim_load = Image.open(buffer_io) self.assert_image_similar(pilim, pilim_load, 0) - # save_bytesio() + save_bytesio() save_bytesio('raw') save_bytesio("packbits") save_bytesio("tiff_lzw")
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
5.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 babel==2.17.0 blessed==1.20.0 build==1.2.2.post1 certifi==2025.1.31 charset-normalizer==3.4.1 check-manifest==0.50 cov-core==1.15.0 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 docutils==0.21.2 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 jarn.viewdoc==2.7 Jinja2==3.1.6 MarkupSafe==3.0.2 olefile==0.47 packaging==24.2 -e git+https://github.com/python-pillow/Pillow.git@1e56ed8c000bfffb198de097fb76c7252904059b#egg=Pillow pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 Pygments==2.19.1 pyproject_hooks==1.2.0 pyroma==4.2 pytest==8.3.5 pytest-cov==6.0.0 pytz==2025.2 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 trove-classifiers==2025.3.19.19 urllib3==2.3.0 wcwidth==0.2.13 zipp==3.21.0
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - babel==2.17.0 - blessed==1.20.0 - build==1.2.2.post1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - check-manifest==0.50 - cov-core==1.15.0 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - docutils==0.21.2 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jarn-viewdoc==2.7 - jinja2==3.1.6 - markupsafe==3.0.2 - olefile==0.47 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyproject-hooks==1.2.0 - pyroma==4.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - trove-classifiers==2025.3.19.19 - urllib3==2.3.0 - wcwidth==0.2.13 - zipp==3.21.0 prefix: /opt/conda/envs/Pillow
[ "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_bytesio", "Tests/test_file_libtiff.py::TestFileLibTiff::test_save_tiff_with_jpegtables", "Tests/test_file_libtiff.py::TestFileLibTiff::test_write_metadata" ]
[]
[ "Tests/test_file_libtiff.py::TestFileLibTiff::test_12bit_rawmode", "Tests/test_file_libtiff.py::TestFileLibTiff::test_16bit_RGBa_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_4bit", "Tests/test_file_libtiff.py::TestFileLibTiff::test__next", "Tests/test_file_libtiff.py::TestFileLibTiff::test_additional_metadata", "Tests/test_file_libtiff.py::TestFileLibTiff::test_adobe_deflate_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_big_endian", "Tests/test_file_libtiff.py::TestFileLibTiff::test_blur", "Tests/test_file_libtiff.py::TestFileLibTiff::test_cmyk_save", "Tests/test_file_libtiff.py::TestFileLibTiff::test_compressions", "Tests/test_file_libtiff.py::TestFileLibTiff::test_crashing_metadata", "Tests/test_file_libtiff.py::TestFileLibTiff::test_fd_duplication", "Tests/test_file_libtiff.py::TestFileLibTiff::test_fp_leak", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g3_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_eq_png", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_fillorder_eq_png", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_large", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_string_info", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff_bytesio", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_tiff_file", "Tests/test_file_libtiff.py::TestFileLibTiff::test_g4_write", "Tests/test_file_libtiff.py::TestFileLibTiff::test_gimp_tiff", "Tests/test_file_libtiff.py::TestFileLibTiff::test_gray_semibyte_per_pixel", "Tests/test_file_libtiff.py::TestFileLibTiff::test_little_endian", "Tests/test_file_libtiff.py::TestFileLibTiff::test_lzw", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage_compression", "Tests/test_file_libtiff.py::TestFileLibTiff::test_multipage_nframes", "Tests/test_file_libtiff.py::TestFileLibTiff::test_page_number_x_0", "Tests/test_file_libtiff.py::TestFileLibTiff::test_read_icc", "Tests/test_file_libtiff.py::TestFileLibTiff::test_sampleformat" ]
[]
MIT-CMU License
2,957
181
[ "src/PIL/TiffImagePlugin.py" ]
Duke-GCB__DukeDSClient-207
b8274d3185ec78ca47a772c1fb644ba319dedd80
2018-08-21 13:35:20
b8274d3185ec78ca47a772c1fb644ba319dedd80
diff --git a/ddsc/core/upload.py b/ddsc/core/upload.py index d702e0d..cb46c47 100644 --- a/ddsc/core/upload.py +++ b/ddsc/core/upload.py @@ -103,7 +103,7 @@ class ProjectUpload(object): """ msg = 'URL to view project' project_id = self.local_project.remote_id - url = '{}: https://{}/portal/#/project/{}'.format(msg, self.config.get_portal_url_base(), project_id) + url = '{}: https://{}/#/project/{}'.format(msg, self.config.get_portal_url_base(), project_id) return url
URL to view project returns 404 Issue due to changes in DukeDS portal url changes. Similar to https://github.com/Duke-GCB/D4S2/issues/175
Duke-GCB/DukeDSClient
diff --git a/ddsc/core/tests/test_upload.py b/ddsc/core/tests/test_upload.py index f638873..1237ed1 100644 --- a/ddsc/core/tests/test_upload.py +++ b/ddsc/core/tests/test_upload.py @@ -3,7 +3,7 @@ from unittest import TestCase from ddsc.core.upload import ProjectUpload, LocalOnlyCounter from ddsc.core.localstore import LocalFile from ddsc.core.remotestore import ProjectNameOrId -from mock import MagicMock, patch +from mock import MagicMock, patch, Mock class TestUploadCommand(TestCase): @@ -44,3 +44,14 @@ class TestLocalOnlyCounter(TestCase): f.size = 200 counter.visit_file(f, None) self.assertEqual(3, counter.total_items()) + + +class TestProjectUpload(TestCase): + @patch("ddsc.core.upload.RemoteStore") + @patch("ddsc.core.upload.LocalProject") + def test_get_url_msg(self, mock_local_project, mock_remote_store): + project_upload = ProjectUpload(config=Mock(), project_name_or_id=Mock(), folders=Mock(), + follow_symlinks=False, file_upload_post_processor=None) + project_upload.local_project = Mock(remote_id='123') + project_upload.config.get_portal_url_base.return_value = '127.0.0.1' + self.assertEqual(project_upload.get_url_msg(), 'URL to view project: https://127.0.0.1/#/project/123')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "mock", "flake8", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/Duke-GCB/DukeDSClient.git@b8274d3185ec78ca47a772c1fb644ba319dedd80#egg=DukeDSClient exceptiongroup==1.2.2 flake8==7.2.0 future==0.16.0 iniconfig==2.1.0 mccabe==0.7.0 mock==5.2.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 pytest==8.3.5 pytz==2025.2 PyYAML==3.12 requests==2.13.0 six==1.10.0 tomli==2.2.1
name: DukeDSClient channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - flake8==7.2.0 - future==0.16.0 - iniconfig==2.1.0 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pytest==8.3.5 - pytz==2025.2 - pyyaml==3.12 - requests==2.13.0 - six==1.10.0 - tomli==2.2.1 prefix: /opt/conda/envs/DukeDSClient
[ "ddsc/core/tests/test_upload.py::TestProjectUpload::test_get_url_msg" ]
[]
[ "ddsc/core/tests/test_upload.py::TestUploadCommand::test_nothing_to_do", "ddsc/core/tests/test_upload.py::TestUploadCommand::test_two_files_to_upload", "ddsc/core/tests/test_upload.py::TestLocalOnlyCounter::test_total_items" ]
[]
MIT License
2,958
154
[ "ddsc/core/upload.py" ]
zamzterz__Flask-pyoidc-28
e4e2d4ffa36b0689b5d1c42cb612e1bdfb4cc638
2018-08-21 18:07:58
e4e2d4ffa36b0689b5d1c42cb612e1bdfb4cc638
diff --git a/src/flask_pyoidc/flask_pyoidc.py b/src/flask_pyoidc/flask_pyoidc.py index 89d05d9..e03b18d 100644 --- a/src/flask_pyoidc/flask_pyoidc.py +++ b/src/flask_pyoidc/flask_pyoidc.py @@ -74,11 +74,10 @@ class OIDCAuthentication(object): OIDC identity provider. """ - def __init__(self, flask_app, client_registration_info=None, + def __init__(self, app=None, client_registration_info=None, issuer=None, provider_configuration_info=None, userinfo_endpoint_method='POST', extra_request_args=None): - self.app = flask_app self.userinfo_endpoint_method = userinfo_endpoint_method self.extra_request_args = extra_request_args or {} @@ -102,21 +101,23 @@ class OIDCAuthentication(object): self.client_registration_info = client_registration_info or {} + self.logout_view = None + self._error_view = None + if app: + self.init_app(app) + + def init_app(self, app): # setup redirect_uri as a flask route - self.app.add_url_rule('/redirect_uri', 'redirect_uri', self._handle_authentication_response) + app.add_url_rule('/redirect_uri', 'redirect_uri', self._handle_authentication_response) # dynamically add the Flask redirect uri to the client info - with self.app.app_context(): - self.client_registration_info['redirect_uris'] \ - = url_for('redirect_uri') + with app.app_context(): + self.client_registration_info['redirect_uris'] = url_for('redirect_uri') # if non-discovery client add the provided info from the constructor - if client_registration_info and 'client_id' in client_registration_info: + if 'client_id' in self.client_registration_info: # static client info provided - self.client.store_registration_info(RegistrationRequest(**client_registration_info)) - - self.logout_view = None - self._error_view = None + self.client.store_registration_info(RegistrationRequest(**self.client_registration_info)) def _authenticate(self, interactive=True): if 'client_id' not in self.client_registration_info: @@ -124,7 +125,7 @@ class OIDCAuthentication(object): # do dynamic registration if self.logout_view: # handle support for logout - with self.app.app_context(): + with current_app.app_context(): post_logout_redirect_uri = url_for(self.logout_view.__name__, _external=True) logger.debug('built post_logout_redirect_uri=%s', post_logout_redirect_uri) self.client_registration_info['post_logout_redirect_uris'] = [post_logout_redirect_uri]
Add init_app feature It's customary for extensions to allow initialization of an app _after_ construction: For example, if an `app.config` contains the appropriate client information, this would be a desierable API: ```python3 from flask_pyoidc import OIDCAuthentication auth = OIDCAuthentication() def create_app(): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) auth.init_app(app) # alternatively # auth.init_app(app, client_info=app.config["CLIENT_INFO"]) return app ``` As it stands, this requires the `app` to be global -- a huge testability no-no.
zamzterz/Flask-pyoidc
diff --git a/tests/test_flask_pyoidc.py b/tests/test_flask_pyoidc.py index b7ce050..80161c8 100644 --- a/tests/test_flask_pyoidc.py +++ b/tests/test_flask_pyoidc.py @@ -50,14 +50,19 @@ class TestOIDCAuthentication(object): self.app = Flask(__name__) self.app.config.update({'SERVER_NAME': 'localhost', 'SECRET_KEY': 'test_key'}) + def get_instance(self, kwargs): + authn = OIDCAuthentication(**kwargs) + authn.init_app(self.app) + return authn + @responses.activate def test_store_internal_redirect_uri_on_static_client_reg(self): responses.add(responses.GET, ISSUER + '/.well-known/openid-configuration', body=json.dumps(dict(issuer=ISSUER, token_endpoint=ISSUER + '/token')), content_type='application/json') - authn = OIDCAuthentication(self.app, issuer=ISSUER, - client_registration_info=dict(client_id='abc', client_secret='foo')) + authn = self.get_instance(dict(issuer=ISSUER, + client_registration_info=dict(client_id='abc', client_secret='foo'))) assert len(authn.client.registration_response['redirect_uris']) == 1 assert authn.client.registration_response['redirect_uris'][0] == 'http://localhost/redirect_uri' @@ -69,9 +74,9 @@ class TestOIDCAuthentication(object): state = 'state' nonce = 'nonce' sub = 'foobar' - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER, 'token_endpoint': '/token'}, - client_registration_info={'client_id': 'foo'}, - userinfo_endpoint_method=method) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER, 'token_endpoint': '/token'}, + client_registration_info={'client_id': 'foo'}, + userinfo_endpoint_method=method)) authn.client.do_access_token_request = MagicMock( return_value=AccessTokenResponse(**{'id_token': IdToken(**{'sub': sub, 'nonce': nonce}), 'access_token': 'access_token'}) @@ -87,9 +92,9 @@ class TestOIDCAuthentication(object): def test_no_userinfo_request_is_done_if_no_userinfo_endpoint_method_is_specified(self): state = 'state' - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo'}, - userinfo_endpoint_method=None) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo'}, + userinfo_endpoint_method=None)) userinfo_request_mock = MagicMock() authn.client.do_user_info_request = userinfo_request_mock authn._do_userinfo_request(state, None) @@ -97,9 +102,9 @@ class TestOIDCAuthentication(object): def test_authenticatate_with_extra_request_parameters(self): extra_params = {"foo": "bar", "abc": "xyz"} - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo'}, - extra_request_args=extra_params) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo'}, + extra_request_args=extra_params)) with self.app.test_request_context('/'): a = authn._authenticate() @@ -107,8 +112,8 @@ class TestOIDCAuthentication(object): assert set(extra_params.items()).issubset(set(request_params.items())) def test_reauthenticate_if_no_session(self): - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo'}) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo'})) client_mock = MagicMock() callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 @@ -119,8 +124,9 @@ class TestOIDCAuthentication(object): assert not callback_mock.called def test_reauthenticate_silent_if_refresh_expired(self): - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo', 'session_refresh_interval_seconds': 1}) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo', + 'session_refresh_interval_seconds': 1})) client_mock = MagicMock() callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 @@ -133,9 +139,9 @@ class TestOIDCAuthentication(object): assert not callback_mock.called def test_dont_reauthenticate_silent_if_authentication_not_expired(self): - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo', - 'session_refresh_interval_seconds': 999}) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo', + 'session_refresh_interval_seconds': 999})) client_mock = MagicMock() callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 @@ -164,11 +170,11 @@ class TestOIDCAuthentication(object): responses.add(responses.POST, userinfo_endpoint, body=json.dumps(userinfo_response), content_type='application/json') - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER, - 'token_endpoint': token_endpoint, - 'userinfo_endpoint': userinfo_endpoint}, - client_registration_info={'client_id': 'foo', 'client_secret': 'foo'}) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER, + 'token_endpoint': token_endpoint, + 'userinfo_endpoint': userinfo_endpoint}, + client_registration_info={'client_id': 'foo', 'client_secret': 'foo'})) self.app.config.update({'SESSION_PERMANENT': True}) with self.app.test_request_context('/redirect_uri?state=test&code=test'): @@ -182,11 +188,11 @@ class TestOIDCAuthentication(object): def test_logout(self): end_session_endpoint = 'https://provider.example.com/end_session' post_logout_uri = 'https://client.example.com/post_logout' - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER, - 'end_session_endpoint': end_session_endpoint}, - client_registration_info={'client_id': 'foo', - 'post_logout_redirect_uris': [post_logout_uri]}) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER, + 'end_session_endpoint': end_session_endpoint}, + client_registration_info={'client_id': 'foo', + 'post_logout_redirect_uris': [post_logout_uri]})) id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'}) with self.app.test_request_context('/logout'): flask.session['access_token'] = 'abcde' @@ -206,10 +212,10 @@ class TestOIDCAuthentication(object): def test_logout_handles_provider_without_end_session_endpoint(self): post_logout_uri = 'https://client.example.com/post_logout' - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER}, - client_registration_info={'client_id': 'foo', - 'post_logout_redirect_uris': [post_logout_uri]}) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER}, + client_registration_info={'client_id': 'foo', + 'post_logout_redirect_uris': [post_logout_uri]})) id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'}) with self.app.test_request_context('/logout'): flask.session['access_token'] = 'abcde' @@ -224,11 +230,11 @@ class TestOIDCAuthentication(object): def test_oidc_logout_redirects_to_provider(self): end_session_endpoint = 'https://provider.example.com/end_session' post_logout_uri = 'https://client.example.com/post_logout' - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER, - 'end_session_endpoint': end_session_endpoint}, - client_registration_info={'client_id': 'foo', - 'post_logout_redirect_uris': [post_logout_uri]}) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER, + 'end_session_endpoint': end_session_endpoint}, + client_registration_info={'client_id': 'foo', + 'post_logout_redirect_uris': [post_logout_uri]})) callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'}) @@ -241,11 +247,11 @@ class TestOIDCAuthentication(object): def test_oidc_logout_handles_redirects_from_provider(self): end_session_endpoint = 'https://provider.example.com/end_session' post_logout_uri = 'https://client.example.com/post_logout' - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER, - 'end_session_endpoint': end_session_endpoint}, - client_registration_info={'client_id': 'foo', - 'post_logout_redirect_uris': [post_logout_uri]}) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER, + 'end_session_endpoint': end_session_endpoint}, + client_registration_info={'client_id': 'foo', + 'post_logout_redirect_uris': [post_logout_uri]})) callback_mock = MagicMock() callback_mock.__name__ = 'test_callback' # required for Python 2 state = 'end_session_123' @@ -258,8 +264,8 @@ class TestOIDCAuthentication(object): def test_authentication_error_reponse_calls_to_error_view_if_set(self): state = 'test_tate' error_response = {'error': 'invalid_request', 'error_description': 'test error'} - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info=dict(client_id='abc', client_secret='foo')) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info=dict(client_id='abc', client_secret='foo'))) error_view_mock = MagicMock() authn._error_view = error_view_mock with self.app.test_request_context('/redirect_uri?{error}&state={state}'.format( @@ -271,8 +277,8 @@ class TestOIDCAuthentication(object): def test_authentication_error_reponse_returns_default_error_if_no_error_view_set(self): state = 'test_tate' error_response = {'error': 'invalid_request', 'error_description': 'test error'} - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER}, - client_registration_info=dict(client_id='abc', client_secret='foo')) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER}, + client_registration_info=dict(client_id='abc', client_secret='foo'))) with self.app.test_request_context('/redirect_uri?{error}&state={state}'.format( error=urlencode(error_response), state=state)): flask.session['state'] = state @@ -287,9 +293,9 @@ class TestOIDCAuthentication(object): body=json.dumps(error_response), content_type='application/json') - authn = OIDCAuthentication(self.app, - provider_configuration_info={'issuer': ISSUER, 'token_endpoint': token_endpoint}, - client_registration_info=dict(client_id='abc', client_secret='foo')) + authn = self.get_instance(dict( + provider_configuration_info={'issuer': ISSUER, 'token_endpoint': token_endpoint}, + client_registration_info=dict(client_id='abc', client_secret='foo'))) error_view_mock = MagicMock() authn._error_view = error_view_mock state = 'test_tate' @@ -306,9 +312,9 @@ class TestOIDCAuthentication(object): body=json.dumps(error_response), content_type='application/json') - authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER, - 'token_endpoint': token_endpoint}, - client_registration_info=dict(client_id='abc', client_secret='foo')) + authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER, + 'token_endpoint': token_endpoint}, + client_registration_info=dict(client_id='abc', client_secret='foo'))) state = 'test_tate' with self.app.test_request_context('/redirect_uri?code=foo&state=' + state): flask.session['state'] = state
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tests/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Beaker==1.13.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 click==8.0.4 cookies==2.2.1 cryptography==40.0.2 dataclasses==0.8 defusedxml==0.7.1 Flask==2.0.3 -e git+https://github.com/zamzterz/Flask-pyoidc.git@e4e2d4ffa36b0689b5d1c42cb612e1bdfb4cc638#egg=Flask_pyoidc future==1.0.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 Mako==1.1.6 MarkupSafe==2.0.1 mock==5.2.0 oic==0.11.0.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycparser==2.21 pycryptodomex==3.21.0 pyjwkest==1.4.2 pyOpenSSL==23.2.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 responses==0.5.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 Werkzeug==2.0.3 zipp==3.6.0
name: Flask-pyoidc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - beaker==1.13.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - click==8.0.4 - cookies==2.2.1 - cryptography==40.0.2 - dataclasses==0.8 - defusedxml==0.7.1 - flask==2.0.3 - future==1.0.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - mako==1.1.6 - markupsafe==2.0.1 - mock==5.2.0 - oic==0.11.0.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pycryptodomex==3.21.0 - pyjwkest==1.4.2 - pyopenssl==23.2.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - responses==0.5.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/Flask-pyoidc
[ "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_store_internal_redirect_uri_on_static_client_reg", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_configurable_userinfo_endpoint_method_is_used[GET]", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_configurable_userinfo_endpoint_method_is_used[POST]", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_no_userinfo_request_is_done_if_no_userinfo_endpoint_method_is_specified", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authenticatate_with_extra_request_parameters", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_if_no_session", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_silent_if_refresh_expired", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_dont_reauthenticate_silent_if_authentication_not_expired", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_session_expiration_set_to_id_token_exp", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_provider_without_end_session_endpoint", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_oidc_logout_redirects_to_provider", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_oidc_logout_handles_redirects_from_provider", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_reponse_calls_to_error_view_if_set", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_reponse_returns_default_error_if_no_error_view_set", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_reponse_calls_to_error_view_if_set", "tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_reponse_returns_default_error_if_no_error_view_set" ]
[]
[ "tests/test_flask_pyoidc.py::Test_Session::test_unauthenticated_session", "tests/test_flask_pyoidc.py::Test_Session::test_authenticated_session", "tests/test_flask_pyoidc.py::Test_Session::test_should_not_refresh_if_not_supported", "tests/test_flask_pyoidc.py::Test_Session::test_should_not_refresh_if_authenticated_within_refresh_interval", "tests/test_flask_pyoidc.py::Test_Session::test_should_refresh_if_supported_and_necessary" ]
[]
Apache License 2.0
2,960
628
[ "src/flask_pyoidc/flask_pyoidc.py" ]
Backblaze__B2_Command_Line_Tool-499
f0822f0207097d36b06e30a987b8210470f92930
2018-08-21 20:34:55
6d1ff3c30dc9c14d6999da7161483b5fbbf7a48b
diff --git a/b2/account_info/abstract.py b/b2/account_info/abstract.py index 3b1f77f..44bbdbd 100644 --- a/b2/account_info/abstract.py +++ b/b2/account_info/abstract.py @@ -88,6 +88,10 @@ class AbstractAccountInfo(object): def get_account_id(self): """ returns account_id or raises MissingAccountData exception """ + @abstractmethod + def get_account_id_or_app_key_id(self): + """ returns the account id or key id used to authenticate """ + @abstractmethod def get_account_auth_token(self): """ returns account_auth_token or raises MissingAccountData exception """ @@ -133,6 +137,7 @@ class AbstractAccountInfo(object): application_key, realm, allowed=None, + account_id_or_app_key_id=None, ): """ Stores the results of b2_authorize_account. @@ -157,6 +162,7 @@ class AbstractAccountInfo(object): application_key, realm, allowed, + account_id_or_app_key_id, ) @classmethod @@ -176,8 +182,16 @@ class AbstractAccountInfo(object): @abstractmethod def _set_auth_data( - self, account_id, auth_token, api_url, download_url, minimum_part_size, application_key, - realm, allowed + self, + account_id, + auth_token, + api_url, + download_url, + minimum_part_size, + application_key, + realm, + allowed, + account_id_or_app_key_id, ): """ Stores the auth data. Can assume that 'allowed' is present and valid. diff --git a/b2/account_info/in_memory.py b/b2/account_info/in_memory.py index 2289ad3..045f56b 100644 --- a/b2/account_info/in_memory.py +++ b/b2/account_info/in_memory.py @@ -38,6 +38,7 @@ class InMemoryAccountInfo(UrlPoolAccountInfo): def _clear_in_memory_account_fields(self): self._account_id = None + self._account_id_or_app_key_id = None self._allowed = None self._api_url = None self._application_key = None @@ -57,8 +58,10 @@ class InMemoryAccountInfo(UrlPoolAccountInfo): application_key, realm, allowed, + account_id_or_app_key_id, ): self._account_id = account_id + self._account_id_or_app_key_id = account_id_or_app_key_id self._auth_token = auth_token self._api_url = api_url self._download_url = download_url @@ -84,6 +87,10 @@ class InMemoryAccountInfo(UrlPoolAccountInfo): def get_account_id(self): return self._account_id + @_raise_missing_if_result_is_none + def get_account_id_or_app_key_id(self): + return self._account_id_or_app_key_id + @_raise_missing_if_result_is_none def get_account_auth_token(self): return self._auth_token diff --git a/b2/account_info/sqlite_account_info.py b/b2/account_info/sqlite_account_info.py index 72733f3..3e9ddaf 100644 --- a/b2/account_info/sqlite_account_info.py +++ b/b2/account_info/sqlite_account_info.py @@ -37,7 +37,11 @@ class SqliteAccountInfo(UrlPoolAccountInfo): completed. """ - def __init__(self, file_name=None): + def __init__(self, file_name=None, last_upgrade_to_run=None): + """ + :param file_name: The sqlite file to use; overrides the default. + :param last_upgrade_to_run: For testing only, override the auto-update on the db. + """ self.thread_local = threading.local() user_account_info_path = file_name or os.environ.get( B2_ACCOUNT_INFO_ENV_VAR, B2_ACCOUNT_INFO_DEFAULT_FILE @@ -45,23 +49,23 @@ class SqliteAccountInfo(UrlPoolAccountInfo): self.filename = file_name or os.path.expanduser(user_account_info_path) self._validate_database() with self._get_connection() as conn: - self._create_tables(conn) + self._create_tables(conn, last_upgrade_to_run) super(SqliteAccountInfo, self).__init__() - def _validate_database(self): + def _validate_database(self, last_upgrade_to_run=None): """ Makes sure that the database is openable. Removes the file if it's not. """ # If there is no file there, that's fine. It will get created when # we connect. if not os.path.exists(self.filename): - self._create_database() + self._create_database(last_upgrade_to_run) return # If we can connect to the database, and do anything, then all is good. try: with self._connect() as conn: - self._create_tables(conn) + self._create_tables(conn, last_upgrade_to_run) return except sqlite3.DatabaseError: pass # fall through to next case @@ -79,10 +83,10 @@ class SqliteAccountInfo(UrlPoolAccountInfo): # remove the json file os.unlink(self.filename) # create a database - self._create_database() + self._create_database(last_upgrade_to_run) # add the data from the JSON file with self._connect() as conn: - self._create_tables(conn) + self._create_tables(conn, last_upgrade_to_run) insert_statement = """ INSERT INTO account (account_id, application_key, account_auth_token, api_url, download_url, minimum_part_size, realm) @@ -111,7 +115,7 @@ class SqliteAccountInfo(UrlPoolAccountInfo): def _connect(self): return sqlite3.connect(self.filename, isolation_level='EXCLUSIVE') - def _create_database(self): + def _create_database(self, last_upgrade_to_run): """ Makes sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. @@ -120,14 +124,14 @@ class SqliteAccountInfo(UrlPoolAccountInfo): conn = self._connect() try: with conn: - self._create_tables(conn) + self._create_tables(conn, last_upgrade_to_run) finally: conn.close() # Set the file permissions os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR) - def _create_tables(self, conn): + def _create_tables(self, conn, last_upgrade_to_run): conn.execute( """ CREATE TABLE IF NOT EXISTS @@ -172,8 +176,14 @@ class SqliteAccountInfo(UrlPoolAccountInfo): ); """ ) + # By default, we run all the upgrades + last_upgrade_to_run = 2 if last_upgrade_to_run is None else last_upgrade_to_run # Add the 'allowed' column if it hasn't been yet. - self._ensure_update(1, 'ALTER TABLE account ADD COLUMN allowed TEXT;') + if 1 <= last_upgrade_to_run: + self._ensure_update(1, 'ALTER TABLE account ADD COLUMN allowed TEXT;') + # Add the 'account_id_or_app_key_id' column if it hasn't been yet + if 2 <= last_upgrade_to_run: + self._ensure_update(2, 'ALTER TABLE account ADD COLUMN account_id_or_app_key_id TEXT;') def _ensure_update(self, update_number, update_command): """ @@ -212,6 +222,7 @@ class SqliteAccountInfo(UrlPoolAccountInfo): application_key, realm, allowed, + account_id_or_app_key_id, ): assert self.allowed_is_valid(allowed) with self._get_connection() as conn: @@ -220,14 +231,53 @@ class SqliteAccountInfo(UrlPoolAccountInfo): conn.execute('DELETE FROM bucket_upload_url;') insert_statement = """ INSERT INTO account - (account_id, application_key, account_auth_token, api_url, download_url, minimum_part_size, realm, allowed) - values (?, ?, ?, ?, ?, ?, ?, ?); + (account_id, account_id_or_app_key_id, application_key, account_auth_token, api_url, download_url, minimum_part_size, realm, allowed) + values (?, ?, ?, ?, ?, ?, ?, ?, ?); + """ + + conn.execute( + insert_statement, ( + account_id, + account_id_or_app_key_id, + application_key, + auth_token, + api_url, + download_url, + minimum_part_size, + realm, + json.dumps(allowed), + ) + ) + + def set_auth_data_with_schema_0_for_test( + self, + account_id, + auth_token, + api_url, + download_url, + minimum_part_size, + application_key, + realm, + ): + with self._get_connection() as conn: + conn.execute('DELETE FROM account;') + conn.execute('DELETE FROM bucket;') + conn.execute('DELETE FROM bucket_upload_url;') + insert_statement = """ + INSERT INTO account + (account_id, application_key, account_auth_token, api_url, download_url, minimum_part_size, realm) + values (?, ?, ?, ?, ?, ?, ?); """ conn.execute( insert_statement, ( - account_id, application_key, auth_token, api_url, download_url, - minimum_part_size, realm, json.dumps(allowed) + account_id, + application_key, + auth_token, + api_url, + download_url, + minimum_part_size, + realm, ) ) @@ -237,6 +287,16 @@ class SqliteAccountInfo(UrlPoolAccountInfo): def get_account_id(self): return self._get_account_info_or_raise('account_id') + def get_account_id_or_app_key_id(self): + """ + The 'account_id_or_app_key_id' column was not in the original schema, so it may be NULL. + """ + result = self._get_account_info_or_raise('account_id_or_app_key_id') + if result is None: + return self.get_account_id() + else: + return result + def get_api_url(self): return self._get_account_info_or_raise('api_url') diff --git a/b2/api.py b/b2/api.py index a1400e1..644191e 100644 --- a/b2/api.py +++ b/b2/api.py @@ -103,7 +103,7 @@ class B2Api(object): try: self.authorize_account( self.account_info.get_realm(), - self.account_info.get_account_id(), + self.account_info.get_account_id_or_app_key_id(), self.account_info.get_application_key(), ) except MissingAccountData: @@ -163,6 +163,7 @@ class B2Api(object): application_key, realm, allowed, + account_id_or_key_id, ) def get_account_id(self): diff --git a/b2/raw_simulator.py b/b2/raw_simulator.py index 0fcb999..7513b23 100644 --- a/b2/raw_simulator.py +++ b/b2/raw_simulator.py @@ -542,6 +542,9 @@ class RawSimulator(AbstractRawApi): # Map from auth token to the KeySimulator for it. self.auth_token_to_key = dict() + # Set of auth tokens that have expired + self.expired_auth_tokens = set() + # Counter for generating auth tokens. self.auth_token_counter = 0 @@ -556,6 +559,16 @@ class RawSimulator(AbstractRawApi): self.app_key_counter = 0 self.upload_errors = [] + def expire_auth_token(self, auth_token): + """ + Simulate the auth token expiring. + + The next call that tries to use this auth token will get an + auth_token_expired error. + """ + assert auth_token in self.auth_token_to_key + self.expired_auth_tokens.add(auth_token) + def create_account(self): """ Returns (accountId, masterApplicationKey) for a newly created account. @@ -930,6 +943,8 @@ class RawSimulator(AbstractRawApi): assert key_sim is not None assert api_url == self.API_URL assert account_id == key_sim.account_id + if account_auth_token in self.expired_auth_tokens: + raise InvalidAuthToken('auth token expired', 'auth_token_expired') if capability not in key_sim.capabilities: raise Unauthorized('', 'unauthorized') if key_sim.bucket_id_or_none is not None and key_sim.bucket_id_or_none != bucket_id:
Automatic re-authorizing with application key does not work When it re-authorizes, it should use the same application key used for the original authentication, but it's using the account ID.
Backblaze/B2_Command_Line_Tool
diff --git a/test/stub_account_info.py b/test/stub_account_info.py index e8b2347..0d469b2 100644 --- a/test/stub_account_info.py +++ b/test/stub_account_info.py @@ -34,6 +34,7 @@ class StubAccountInfo(AbstractAccountInfo): self.download_url = None self.minimum_part_size = None self.realm = None + self.account_id_or_app_key_id = None self._large_file_uploads = collections.defaultdict(list) self._large_file_uploads_lock = threading.Lock() @@ -51,6 +52,7 @@ class StubAccountInfo(AbstractAccountInfo): application_key, realm, allowed, + account_id_or_app_key_id, ): self.account_id = account_id self.auth_token = auth_token @@ -60,6 +62,7 @@ class StubAccountInfo(AbstractAccountInfo): self.application_key = application_key self.realm = realm self.allowed = allowed + self.account_id_or_app_key_id = account_id_or_app_key_id def refresh_entire_bucket_name_cache(self, name_id_iterable): self.buckets = {} @@ -82,6 +85,9 @@ class StubAccountInfo(AbstractAccountInfo): def get_account_id(self): return self.account_id + def get_account_id_or_app_key_id(self): + return self.account_id_or_app_key_id + def get_account_auth_token(self): return self.auth_token diff --git a/test/test_account_info.py b/test/test_account_info.py index 923269c..d0fa8f7 100644 --- a/test/test_account_info.py +++ b/test/test_account_info.py @@ -261,11 +261,48 @@ class TestSqliteAccountInfo(AccountInfoBase, TestBase): account_info = self._make_info() self.assertEqual('auth_token', account_info.get_account_auth_token()) + def test_upgrade_1_default_allowed(self): + """ + The 'allowed' field should be the default for upgraded databases. + """ + old_account_info = self._make_sqlite_account_info(last_upgrade_to_run=0) + old_account_info.set_auth_data_with_schema_0_for_test( + 'account_id', + 'auth_token', + 'api_url', + 'dowload_url', + 100, # minimum part size + 'application_key', + 'realm', + ) + new_account_info = self._make_info() + self.assertEqual(AbstractAccountInfo.DEFAULT_ALLOWED, new_account_info.get_allowed()) + + def test_upgrade_2_default_app_key(self): + """ + The 'account_id_or_app_key_id' field should default to the account id. + """ + old_account_info = self._make_sqlite_account_info(last_upgrade_to_run=0) + old_account_info.set_auth_data_with_schema_0_for_test( + 'account_id', + 'auth_token', + 'api_url', + 'dowload_url', + 100, # minimum part size + 'application_key', + 'realm', + ) + new_account_info = self._make_info() + self.assertEqual('account_id', new_account_info.get_account_id_or_app_key_id()) + def _make_info(self): + return self._make_sqlite_account_info() + + def _make_sqlite_account_info(self, last_upgrade_to_run=None): """ Returns a new StoredAccountInfo that has just read the data from the file. """ - return SqliteAccountInfo(file_name=self.db_path) + return SqliteAccountInfo(file_name=self.db_path, last_upgrade_to_run=None) def test_account_info_persistence(self): self._test_account_info(check_persistence=True) diff --git a/test/test_api.py b/test/test_api.py index f72c336..fb2a016 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -42,6 +42,20 @@ class TestApi(TestBase): [b.name for b in self.api.list_buckets(bucket_name='bucket1')], ) + def test_reauthorize_with_app_key(self): + # authorize and create a key + self._authorize_account() + key = self.api.create_key(['listBuckets'], 'key1') + + # authorize with the key + self.api.authorize_account('production', key['applicationKeyId'], key['applicationKey']) + + # expire the auth token we just got + self.raw_api.expire_auth_token(self.account_info.get_account_auth_token()) + + # listing buckets should work, after it re-authorizes + self.api.list_buckets() + def test_list_buckets_with_restriction(self): self._authorize_account() bucket1 = self.api.create_bucket('bucket1', 'allPrivate')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 5 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "nose-cov", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
arrow==0.12.0 attrs==22.2.0 -e git+https://github.com/Backblaze/B2_Command_Line_Tool.git@f0822f0207097d36b06e30a987b8210470f92930#egg=b2 certifi==2021.5.30 charset-normalizer==2.0.12 cov-core==1.15.0 coverage==6.2 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 logfury==1.0.1 nose==1.3.7 nose-cov==1.6 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 requests==2.27.1 six==1.17.0 tomli==1.2.3 tqdm==4.64.1 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: B2_Command_Line_Tool channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - arrow==0.12.0 - attrs==22.2.0 - charset-normalizer==2.0.12 - cov-core==1.15.0 - coverage==6.2 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - logfury==1.0.1 - nose==1.3.7 - nose-cov==1.6 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - tqdm==4.64.1 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/B2_Command_Line_Tool
[ "test/test_account_info.py::TestSqliteAccountInfo::test_account_info_persistence", "test/test_account_info.py::TestSqliteAccountInfo::test_account_info_same_object", "test/test_account_info.py::TestSqliteAccountInfo::test_bucket", "test/test_account_info.py::TestSqliteAccountInfo::test_clear", "test/test_account_info.py::TestSqliteAccountInfo::test_clear_bucket_upload_data", "test/test_account_info.py::TestSqliteAccountInfo::test_clear_large_file_upload_urls", "test/test_account_info.py::TestSqliteAccountInfo::test_convert_from_json", "test/test_account_info.py::TestSqliteAccountInfo::test_corrupted", "test/test_account_info.py::TestSqliteAccountInfo::test_large_file_upload_urls", "test/test_account_info.py::TestSqliteAccountInfo::test_refresh_bucket", "test/test_account_info.py::TestSqliteAccountInfo::test_set_auth_data_compatibility", "test/test_account_info.py::TestSqliteAccountInfo::test_upgrade_1_default_allowed", "test/test_account_info.py::TestSqliteAccountInfo::test_upgrade_2_default_app_key", "test/test_api.py::TestApi::test_reauthorize_with_app_key" ]
[]
[ "test/test_account_info.py::TestUploadUrlPool::test_clear", "test/test_account_info.py::TestUploadUrlPool::test_put_and_take", "test/test_account_info.py::TestUploadUrlPool::test_take_empty", "test/test_account_info.py::TestInMemoryAccountInfo::test_account_info_same_object", "test/test_account_info.py::TestInMemoryAccountInfo::test_bucket", "test/test_account_info.py::TestInMemoryAccountInfo::test_clear", "test/test_account_info.py::TestInMemoryAccountInfo::test_clear_bucket_upload_data", "test/test_account_info.py::TestInMemoryAccountInfo::test_clear_large_file_upload_urls", "test/test_account_info.py::TestInMemoryAccountInfo::test_large_file_upload_urls", "test/test_account_info.py::TestInMemoryAccountInfo::test_refresh_bucket", "test/test_account_info.py::TestInMemoryAccountInfo::test_set_auth_data_compatibility", "test/test_api.py::TestApi::test_get_bucket_by_name_with_bucket_restriction", "test/test_api.py::TestApi::test_list_buckets", "test/test_api.py::TestApi::test_list_buckets_with_name", "test/test_api.py::TestApi::test_list_buckets_with_restriction", "test/test_api.py::TestApi::test_list_buckets_with_restriction_and_no_name", "test/test_api.py::TestApi::test_list_buckets_with_restriction_and_wrong_name" ]
[]
MIT License
2,961
3,004
[ "b2/account_info/abstract.py", "b2/account_info/in_memory.py", "b2/account_info/sqlite_account_info.py", "b2/api.py", "b2/raw_simulator.py" ]
dwavesystems__dimod-266
67f88fd545767cf999bf86e86bf93489f3a503b9
2018-08-21 21:32:44
2f6e129f4894ae07d16aa290c35d7e7859138cc8
diff --git a/dimod/embedding/transforms.py b/dimod/embedding/transforms.py index b72dbda6..4acba9fe 100644 --- a/dimod/embedding/transforms.py +++ b/dimod/embedding/transforms.py @@ -23,7 +23,7 @@ import numpy as np from six import iteritems, itervalues from dimod.binary_quadratic_model import BinaryQuadraticModel -from dimod.embedding.chain_breaks import majority_vote +from dimod.embedding.chain_breaks import majority_vote, broken_chains from dimod.embedding.utils import chain_to_quadratic from dimod.response import Response from dimod.vartypes import Vartype @@ -330,7 +330,8 @@ def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0): return target_Q -def unembed_response(target_response, embedding, source_bqm, chain_break_method=None): +def unembed_response(target_response, embedding, source_bqm, + chain_break_method=None, chain_break_fraction=False): """Unembed the response. Construct a response for the source binary quadratic model (BQM) by unembedding the given @@ -351,6 +352,10 @@ def unembed_response(target_response, embedding, source_bqm, chain_break_method= Method used to resolve chain breaks. Must be an iterator which accepts a sample and an embedding and yields unembedded samples. + chain_break_fraction (bool, optional, default=False): + If True, a 'chain_break_fraction' field is added to the unembedded response which report + what fraction of the chains were broken before unembedding. + Returns: :obj:`.Response`: Response for the source binary quadratic model. @@ -444,6 +449,9 @@ def unembed_response(target_response, embedding, source_bqm, chain_break_method= datatypes.extend((name, record[name].dtype, record[name].shape[1:]) for name in record.dtype.names if name not in {'sample', 'energy'}) + if chain_break_fraction: + datatypes.append(('chain_break_fraction', np.float64)) + data = np.rec.array(np.empty(num_samples, dtype=datatypes)) data.sample = unembedded @@ -452,4 +460,7 @@ def unembed_response(target_response, embedding, source_bqm, chain_break_method= if name not in {'sample', 'energy'}: data[name] = record[name][idxs] + if chain_break_fraction: + data['chain_break_fraction'] = broken_chains(record.sample, chain_idxs).mean(axis=1)[idxs] + return Response(data, variables, target_response.info, target_response.vartype)
Feature Request: Throw warning when unembedding results in too many chain breaks Proposed syntax: ``` resp = unembed_response(response, embedding, bqm, warning_threshold=.1) ``` In this case a `UserWarning` will be raised if more than 10% of the chains are broken.
dwavesystems/dimod
diff --git a/tests/test_embedding_transforms.py b/tests/test_embedding_transforms.py index f022020d..0a50fb25 100644 --- a/tests/test_embedding_transforms.py +++ b/tests/test_embedding_transforms.py @@ -202,6 +202,29 @@ class TestUnembedResponse(unittest.TestCase): np.testing.assert_array_equal(arr, unembedded.record) + def test_chain_break_statistics_discard(self): + sample0 = {0: -1, 1: -1, 2: +1} + sample1 = {0: +1, 1: -1, 2: +1} + samples = [sample0, sample1] + + # now set up an embedding that works for one sample and not the other + embedding = {'a': {0, 1}, 'b': {2}} + + bqm = dimod.BinaryQuadraticModel.from_ising({'a': 1}, {('a', 'b'): -1}) + + resp = dimod.Response.from_samples(samples, {'energy': [-1, 1]}, {}, dimod.SPIN) + + resp = dimod.unembed_response(resp, embedding, bqm, chain_break_method=dimod.embedding.discard, + chain_break_fraction=True) + + source_samples = list(resp) + + # only the first sample should be returned + self.assertEqual(len(source_samples), 1) + self.assertEqual(source_samples, [{'a': -1, 'b': +1}]) + + self.assertEqual(resp.record.chain_break_fraction.sum(), 0) + class TestEmbedBQM(unittest.TestCase): def test_embed_bqm_empty(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 decorator==5.1.1 -e git+https://github.com/dwavesystems/dimod.git@67f88fd545767cf999bf86e86bf93489f3a503b9#egg=dimod idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 jsonschema==2.6.0 mock==2.0.0 networkx==2.0 numpy==1.15.0 packaging==21.3 pandas==0.22.0 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pymongo==3.7.1 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 six==1.11.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: dimod channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - decorator==5.1.1 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsonschema==2.6.0 - mock==2.0.0 - networkx==2.0 - numpy==1.15.0 - packaging==21.3 - pandas==0.22.0 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pymongo==3.7.1 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - six==1.11.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/dimod
[ "tests/test_embedding_transforms.py::TestUnembedResponse::test_chain_break_statistics_discard" ]
[]
[ "tests/test_embedding_transforms.py::TestUnembedResponse::test_discard", "tests/test_embedding_transforms.py::TestUnembedResponse::test_discard_with_response", "tests/test_embedding_transforms.py::TestUnembedResponse::test_embedding_superset", "tests/test_embedding_transforms.py::TestUnembedResponse::test_energies_discard", "tests/test_embedding_transforms.py::TestUnembedResponse::test_energies_functional", "tests/test_embedding_transforms.py::TestUnembedResponse::test_majority_vote", "tests/test_embedding_transforms.py::TestUnembedResponse::test_majority_vote_with_response", "tests/test_embedding_transforms.py::TestUnembedResponse::test_unembed_response_with_discard_matrix_typical", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_BINARY", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_NAE3SAT_to_square", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_empty", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_identity", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_only_offset", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_bqm_subclass_propagation", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_bad_chain", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_components_empty", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_embedding_not_in_adj", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_h_embedding_mismatch", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_j_index_too_large", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_nonadj", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_ising_typical", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embed_qubo", "tests/test_embedding_transforms.py::TestEmbedBQM::test_embedding_with_extra_chains" ]
[]
Apache License 2.0
2,962
624
[ "dimod/embedding/transforms.py" ]
Azure__WALinuxAgent-1317
ae2aec6fc31a4742c139d93cfc5e571e7afc741b
2018-08-23 18:52:01
6e9b985c1d7d564253a1c344bab01b45093103cd
diff --git a/azurelinuxagent/ga/monitor.py b/azurelinuxagent/ga/monitor.py index c1215806..d6b66921 100644 --- a/azurelinuxagent/ga/monitor.py +++ b/azurelinuxagent/ga/monitor.py @@ -406,7 +406,11 @@ class MonitorHandler(object): CGroupsTelemetry.track_cgroup(CGroups.for_extension("")) CGroupsTelemetry.track_agent() except Exception as e: - logger.error("monitor: Exception tracking wrapper and agent: {0} [{1}]", e, traceback.format_exc()) + # when a hierarchy is not mounted, we raise an exception + # and we should therefore only issue a warning, since this + # is not unexpected + logger.warn("Monitor: cgroups not initialized: {0}", ustr(e)) + logger.verbose(traceback.format_exc()) def send_cgroup_telemetry(self): if self.last_cgroup_telemetry is None: @@ -419,13 +423,15 @@ class MonitorHandler(object): if value > 0: report_metric(metric_group, metric_name, cgroup_name, value) except Exception as e: - logger.warn("Failed to collect performance metrics: {0} [{1}]", e, traceback.format_exc()) + logger.warn("Monitor: failed to collect cgroups performance metrics: {0}", ustr(e)) + logger.verbose(traceback.format_exc()) # Look for extension cgroups we're not already tracking and track them try: CGroupsTelemetry.update_tracked(self.protocol.client.get_current_handlers()) except Exception as e: - logger.warn("Monitor: updating tracked extensions raised {0}: {1}", e, traceback.format_exc()) + logger.warn("Monitor: failed to update cgroups tracked extensions: {0}", ustr(e)) + logger.verbose(traceback.format_exc()) self.last_cgroup_telemetry = datetime.datetime.utcnow() diff --git a/azurelinuxagent/pa/provision/cloudinit.py b/azurelinuxagent/pa/provision/cloudinit.py index 9609d7da..3f3cdb04 100644 --- a/azurelinuxagent/pa/provision/cloudinit.py +++ b/azurelinuxagent/pa/provision/cloudinit.py @@ -69,9 +69,10 @@ class CloudInitProvisionHandler(ProvisionHandler): duration=elapsed_milliseconds(utc_start)) except ProvisionError as e: - logger.error("Provisioning failed: {0}", ustr(e)) + msg = "Provisioning with cloud-init failed: {0} ({1}s)".format(ustr(e), self._get_uptime_seconds()) + logger.error(msg) self.report_not_ready("ProvisioningFailed", ustr(e)) - self.report_event(ustr(e)) + self.report_event(msg) return def wait_for_ovfenv(self, max_retry=1800, sleep_time=1): diff --git a/azurelinuxagent/pa/provision/default.py b/azurelinuxagent/pa/provision/default.py index a6e50824..0eb0823c 100644 --- a/azurelinuxagent/pa/provision/default.py +++ b/azurelinuxagent/pa/provision/default.py @@ -98,9 +98,10 @@ class ProvisionHandler(object): logger.info("Provisioning complete") except (ProtocolError, ProvisionError) as e: + msg = "Provisioning failed: {0} ({1}s)".format(ustr(e), self._get_uptime_seconds()) + logger.error(msg) self.report_not_ready("ProvisioningFailed", ustr(e)) - self.report_event(ustr(e), is_success=False) - logger.error("Provisioning failed: {0}", ustr(e)) + self.report_event(msg, is_success=False) return @staticmethod
CGroups error in Ubuntu 14.04 ``` 2018/07/31 11:41:06.400633 ERROR ExtHandler monitor: Exception tracking wrapper and agent: 'Hierarchy memory is not mounted' [Traceback (most recent call last): File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/ga/monitor.py", line 397, in init_cgroups CGroupsTelemetry.track_cgroup(CGroups.for_extension("")) File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/common/cgroups.py", line 360, in for_extension return CGroups(name, CGroups._construct_custom_path_for_hierarchy) File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/common/cgroups.py", line 401, in __init__ raise CGroupsException("Hierarchy {0} is not mounted".format(hierarchy)) azurelinuxagent.common.cgroups.CGroupsException: 'Hierarchy memory is not mounted' ] ```
Azure/WALinuxAgent
diff --git a/tests/pa/test_provision.py b/tests/pa/test_provision.py index 0335bc9c..27f75266 100644 --- a/tests/pa/test_provision.py +++ b/tests/pa/test_provision.py @@ -268,8 +268,8 @@ class TestProvision(AgentTestCase): fileutil.write_file(ovfenv_file, ovfenv_data) ph.run() - ph.report_event.assert_called_once_with( - '[ProvisionError] --unit-test--', is_success=False) + positional_args, kw_args = ph.report_event.call_args_list[0] + self.assertTrue(re.match(r'Provisioning failed: \[ProvisionError\] --unit-test-- \(\d+\.\d+s\)', positional_args[0]) is not None) @patch('azurelinuxagent.pa.provision.default.ProvisionHandler.write_agent_disabled') @distros()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 3 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work -e git+https://github.com/Azure/WALinuxAgent.git@ae2aec6fc31a4742c139d93cfc5e571e7afc741b#egg=WALinuxAgent zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: WALinuxAgent channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - nose==1.3.7 prefix: /opt/conda/envs/WALinuxAgent
[ "tests/pa/test_provision.py::TestProvision::test_provision_telemetry_fail" ]
[]
[ "tests/pa/test_provision.py::TestProvision::test_customdata", "tests/pa/test_provision.py::TestProvision::test_handle_provision_guest_agent", "tests/pa/test_provision.py::TestProvision::test_is_provisioned_is_provisioned", "tests/pa/test_provision.py::TestProvision::test_is_provisioned_not_deprovisioned", "tests/pa/test_provision.py::TestProvision::test_is_provisioned_not_provisioned", "tests/pa/test_provision.py::TestProvision::test_provision", "tests/pa/test_provision.py::TestProvision::test_provision_telemetry_pga_bad", "tests/pa/test_provision.py::TestProvision::test_provision_telemetry_pga_empty", "tests/pa/test_provision.py::TestProvision::test_provision_telemetry_pga_false", "tests/pa/test_provision.py::TestProvision::test_provision_telemetry_pga_true", "tests/pa/test_provision.py::TestProvision::test_provisioning_is_skipped_when_not_enabled" ]
[]
Apache License 2.0
2,970
897
[ "azurelinuxagent/ga/monitor.py", "azurelinuxagent/pa/provision/cloudinit.py", "azurelinuxagent/pa/provision/default.py" ]
elastic__rally-555
31ac8b0f9eace24cafff7d995daa1285d1443309
2018-08-24 13:03:41
799e0642c27a0067931f305359a615cbf9fe2e20
diff --git a/esrally/track/loader.py b/esrally/track/loader.py index 39800a6a..fbe3a076 100644 --- a/esrally/track/loader.py +++ b/esrally/track/loader.py @@ -228,6 +228,19 @@ def operation_parameters(t, op): return params.param_source_for_operation(op.type, t, op.params) +def used_corpora(t, cfg): + corpora = {} + challenge = t.find_challenge_or_default(cfg.opts("track", "challenge.name")) + for task in challenge.schedule: + for sub_task in task: + param_source = operation_parameters(t, sub_task.operation) + if hasattr(param_source, "corpora"): + for c in param_source.corpora: + # We might have the same corpus *but* they contain different doc sets. Therefore also need to union over doc sets. + corpora[c.name] = corpora.get(c.name, c).union(c) + return corpora.values() + + def prepare_track(t, cfg): """ Ensures that all track data are available for running the benchmark. @@ -238,7 +251,7 @@ def prepare_track(t, cfg): logger = logging.getLogger(__name__) offline = cfg.opts("system", "offline.mode") test_mode = cfg.opts("track", "test.mode.enabled") - for corpus in t.corpora: + for corpus in used_corpora(t, cfg): data_root = data_dir(cfg, t.name, corpus.name) logger.info("Resolved data root directory for document corpus [%s] in track [%s] to %s.", corpus.name, t.name, data_root) prep = DocumentSetPreparator(t.name, offline, test_mode) diff --git a/esrally/track/track.py b/esrally/track/track.py index dcdbe72b..68083405 100644 --- a/esrally/track/track.py +++ b/esrally/track/track.py @@ -214,6 +214,14 @@ class DocumentCorpus: filtered.append(d) return DocumentCorpus(self.name, filtered) + def union(self, other): + if self.name != other.name: + raise exceptions.RallyAssertionError("Both document corpora must have the same name") + if self is other: + return self + else: + return DocumentCorpus(self.name, list(set(self.documents).union(other.documents))) + def __str__(self): return self.name
Only load required corpora Currently Rally is loading all referenced corpora of track, even if they are not needed. As it is possible that we download and extract a significant amount of data (usually several GB if not more), we should investigate whether we can load only the required ones.
elastic/rally
diff --git a/tests/track/loader_test.py b/tests/track/loader_test.py index e487640a..09e29262 100644 --- a/tests/track/loader_test.py +++ b/tests/track/loader_test.py @@ -459,6 +459,140 @@ class TrackPreparationTests(TestCase): self.assertEqual(0, decompress.call_count) self.assertEqual(0, prepare_file_offset_table.call_count) + def test_used_corpora(self): + cfg = config.Config() + cfg.add(config.Scope.application, "track", "challenge.name", "default-challenge") + track_specification = { + "description": "description for unit test", + "indices": [ + {"name": "logs-181998"}, + {"name": "logs-191998"}, + {"name": "logs-201998"}, + ], + "corpora": [ + { + "name": "http_logs_unparsed", + "target-type": "type", + "documents": [ + { + "target-index": "logs-181998", + "source-file": "documents-181998.unparsed.json.bz2", + "document-count": 2708746, + "compressed-bytes": 13064317, + "uncompressed-bytes": 303920342 + }, + { + "target-index": "logs-191998", + "source-file": "documents-191998.unparsed.json.bz2", + "document-count": 9697882, + "compressed-bytes": 47211781, + "uncompressed-bytes": 1088378738 + }, + { + "target-index": "logs-201998", + "source-file": "documents-201998.unparsed.json.bz2", + "document-count": 13053463, + "compressed-bytes": 63174979, + "uncompressed-bytes": 1456836090 + } + ] + }, + { + "name": "http_logs", + "target-type": "type", + "documents": [ + { + "target-index": "logs-181998", + "source-file": "documents-181998.json.bz2", + "document-count": 2708746, + "compressed-bytes": 13815456, + "uncompressed-bytes": 363512754 + }, + { + "target-index": "logs-191998", + "source-file": "documents-191998.json.bz2", + "document-count": 9697882, + "compressed-bytes": 49439633, + "uncompressed-bytes": 1301732149 + }, + { + "target-index": "logs-201998", + "source-file": "documents-201998.json.bz2", + "document-count": 13053463, + "compressed-bytes": 65623436, + "uncompressed-bytes": 1744012279 + } + ] + } + ], + "operations": [ + { + "name": "bulk-index-1", + "operation-type": "bulk", + "corpora": ["http_logs"], + "indices": ["logs-181998"], + "bulk-size": 500 + }, + { + "name": "bulk-index-2", + "operation-type": "bulk", + "corpora": ["http_logs"], + "indices": ["logs-191998"], + "bulk-size": 500 + }, + { + "name": "bulk-index-3", + "operation-type": "bulk", + "corpora": ["http_logs_unparsed"], + "indices": ["logs-201998"], + "bulk-size": 500 + }, + { + "name": "node-stats", + "operation-type": "node-stats" + }, + ], + "challenges": [ + { + "name": "default-challenge", + "schedule": [ + { + "parallel": { + "tasks": [ + { + "name": "index-1", + "operation": "bulk-index-1", + }, + { + "name": "index-2", + "operation": "bulk-index-2", + }, + { + "name": "index-3", + "operation": "bulk-index-3", + }, + ] + } + }, + { + "operation": "node-stats" + } + ] + } + ] + } + reader = loader.TrackSpecificationReader() + full_track = reader("unittest", track_specification, "/mappings") + used_corpora = sorted(loader.used_corpora(full_track, cfg), key=lambda c: c.name) + self.assertEqual(2, len(used_corpora)) + self.assertEqual("http_logs", used_corpora[0].name) + # each bulk operation requires a different data file but they should have been merged properly. + self.assertEqual({"documents-181998.json.bz2", "documents-191998.json.bz2"}, + {d.document_archive for d in used_corpora[0].documents}) + + self.assertEqual("http_logs_unparsed", used_corpora[1].name) + self.assertEqual({"documents-201998.unparsed.json.bz2"}, {d.document_archive for d in used_corpora[1].documents}) + @mock.patch("esrally.utils.io.prepare_file_offset_table") @mock.patch("esrally.utils.io.decompress") @mock.patch("os.path.getsize") diff --git a/tests/track/track_test.py b/tests/track/track_test.py index 05fa3907..bddd5d40 100644 --- a/tests/track/track_test.py +++ b/tests/track/track_test.py @@ -126,3 +126,32 @@ class DocumentCorpusTests(TestCase): self.assertEqual(2, len(filtered_corpus.documents)) self.assertEqual("logs-01", filtered_corpus.documents[0].target_index) self.assertEqual("logs-02", filtered_corpus.documents[1].target_index) + + def test_union_document_corpus_is_reflexive(self): + corpus = track.DocumentCorpus("test", documents=[ + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=5, target_index="logs-01"), + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=6, target_index="logs-02"), + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=7, target_index="logs-03"), + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=8, target_index=None) + ]) + self.assertTrue(corpus.union(corpus) is corpus) + + def test_union_document_corpora_is_symmetric(self): + a = track.DocumentCorpus("test", documents=[ + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=5, target_index="logs-01"), + ]) + b = track.DocumentCorpus("test", documents=[ + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=5, target_index="logs-02"), + ]) + self.assertEqual(b.union(a), a.union(b)) + self.assertEqual(2, len(a.union(b).documents)) + + def test_cannot_union_mixed_document_corpora(self): + a = track.DocumentCorpus("test", documents=[ + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=5, target_index="logs-01"), + ]) + b = track.DocumentCorpus("other", documents=[ + track.Documents(source_format=track.Documents.SOURCE_FORMAT_BULK, number_of_documents=5, target_index="logs-02"), + ]) + with self.assertRaisesRegex(exceptions.RallyAssertionError, "Both document corpora must have the same name"): + a.union(b)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-benchmark" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 elasticsearch==6.2.0 -e git+https://github.com/elastic/rally.git@31ac8b0f9eace24cafff7d995daa1285d1443309#egg=esrally importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==2.9.5 jsonschema==2.5.1 MarkupSafe==2.0.1 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==5.4.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work py-cpuinfo==3.2.0 pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-benchmark==3.4.1 tabulate==0.8.1 thespian==3.9.2 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.22 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: rally channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - elasticsearch==6.2.0 - jinja2==2.9.5 - jsonschema==2.5.1 - markupsafe==2.0.1 - psutil==5.4.0 - py-cpuinfo==3.2.0 - pytest-benchmark==3.4.1 - tabulate==0.8.1 - thespian==3.9.2 - urllib3==1.22 prefix: /opt/conda/envs/rally
[ "tests/track/loader_test.py::TrackPreparationTests::test_used_corpora", "tests/track/track_test.py::DocumentCorpusTests::test_cannot_union_mixed_document_corpora", "tests/track/track_test.py::DocumentCorpusTests::test_union_document_corpora_is_symmetric", "tests/track/track_test.py::DocumentCorpusTests::test_union_document_corpus_is_reflexive" ]
[]
[ "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_directory", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_directory_without_track", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_file", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_file_but_not_json", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_named_pipe", "tests/track/loader_test.py::SimpleTrackRepositoryTests::test_track_from_non_existing_path", "tests/track/loader_test.py::GitRepositoryTests::test_track_from_existing_repo", "tests/track/loader_test.py::TrackPreparationTests::test_decompresses_if_archive_available", "tests/track/loader_test.py::TrackPreparationTests::test_does_nothing_if_document_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_download_document_archive_if_no_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_download_document_file_if_no_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_decompresses_compressed_docs", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_does_nothing_if_no_document_files", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_error_compressed_docs_wrong_size", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_if_document_file_available", "tests/track/loader_test.py::TrackPreparationTests::test_prepare_bundled_document_set_uncompressed_docs_wrong_size", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_no_url_provided_and_file_missing", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_no_url_provided_and_wrong_file_size", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_if_offline", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_no_test_mode_file", "tests/track/loader_test.py::TrackPreparationTests::test_raise_download_error_on_connection_problems", "tests/track/loader_test.py::TrackPreparationTests::test_raise_error_if_compressed_does_not_contain_expected_document_file", "tests/track/loader_test.py::TrackPreparationTests::test_raise_error_on_wrong_uncompressed_file_size", "tests/track/loader_test.py::TemplateRenderTests::test_render_simple_template", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_external_variables", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_globbing", "tests/track/loader_test.py::TemplateRenderTests::test_render_template_with_variables", "tests/track/loader_test.py::TrackPostProcessingTests::test_post_processes_track_spec", "tests/track/loader_test.py::TrackPathTests::test_sets_absolute_path", "tests/track/loader_test.py::TrackFilterTests::test_create_filters_from_empty_included_tasks", "tests/track/loader_test.py::TrackFilterTests::test_create_filters_from_mixed_included_tasks", "tests/track/loader_test.py::TrackFilterTests::test_filters_tasks", "tests/track/loader_test.py::TrackFilterTests::test_rejects_invalid_syntax", "tests/track/loader_test.py::TrackFilterTests::test_rejects_unknown_filter_type", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_at_least_one_default_challenge", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_auto_generates_challenge_from_schedule", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_can_read_track_info", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_description_is_optional", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_document_count_mandatory_if_file_present", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_exactly_one_default_challenge", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_inline_operations", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_not_more_than_one_default_challenge_possible", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set_multiple_tasks_match", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_completed_by_set_no_task_matches", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_default_clients_does_not_propagate", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parallel_tasks_with_default_values", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_challenge_and_challenges_are_defined", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_duplicate_explicit_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_duplicate_implicit_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_missing_challenge_or_challenges", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_unique_task_names", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_valid_track_specification", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_valid_track_specification_with_index_template", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_with_mixed_warmup_iterations_and_measurement", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_parse_with_mixed_warmup_time_period_and_iterations", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_selects_sole_challenge_implicitly_as_default", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_supports_target_interval", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_supports_target_throughput", "tests/track/loader_test.py::TrackSpecificationReaderTests::test_unique_challenge_names", "tests/track/track_test.py::TrackTests::test_default_challenge_none_if_no_challenges", "tests/track/track_test.py::TrackTests::test_does_not_find_unknown_challenge", "tests/track/track_test.py::TrackTests::test_finds_challenge_by_name", "tests/track/track_test.py::TrackTests::test_finds_default_challenge", "tests/track/track_test.py::TrackTests::test_uses_default_challenge_if_no_name_given", "tests/track/track_test.py::IndexTests::test_matches_exactly", "tests/track/track_test.py::IndexTests::test_matches_if_catch_all_pattern_is_defined", "tests/track/track_test.py::IndexTests::test_matches_if_no_pattern_is_defined", "tests/track/track_test.py::IndexTests::test_str", "tests/track/track_test.py::DocumentCorpusTests::test_do_not_filter", "tests/track/track_test.py::DocumentCorpusTests::test_filter_documents_by_format", "tests/track/track_test.py::DocumentCorpusTests::test_filter_documents_by_format_and_indices", "tests/track/track_test.py::DocumentCorpusTests::test_filter_documents_by_indices" ]
[]
Apache License 2.0
2,972
588
[ "esrally/track/loader.py", "esrally/track/track.py" ]
globus__globus-sdk-python-307
d761ba9a104ba2d8a70d2e064d12ea95101596df
2018-08-24 15:33:56
d761ba9a104ba2d8a70d2e064d12ea95101596df
diff --git a/globus_sdk/base.py b/globus_sdk/base.py index ec668bcd..8fd51190 100644 --- a/globus_sdk/base.py +++ b/globus_sdk/base.py @@ -80,16 +80,16 @@ class BaseClient(object): type(self), self.allowed_authorizer_types, type(authorizer))) - # defer this default until instantiation time so that logging can - # capture the execution of the config load - if environment is None: - environment = config.get_default_environ() + # if an environment was passed, it will be used, but otherwise lookup + # the env var -- and in the special case of `production` translate to + # `default`, regardless of the source of that value + # logs the environment when it isn't `default` + self.environment = config.get_globus_environ(inputenv=environment) - self.environment = environment self.authorizer = authorizer if base_url is None: - self.base_url = config.get_service_url(environment, service) + self.base_url = config.get_service_url(self.environment, service) else: self.base_url = base_url if base_path is not None: @@ -104,13 +104,13 @@ class BaseClient(object): } # verify SSL? Usually true - self._verify = config.get_ssl_verify(environment) + self._verify = config.get_ssl_verify(self.environment) # HTTP connection timeout # this is passed verbatim to `requests`, and we therefore technically # support a tuple for connect/read timeouts, but we don't need to # advertise that... Just declare it as an float value if http_timeout is None: - http_timeout = config.get_http_timeout(environment) + http_timeout = config.get_http_timeout(self.environment) self._http_timeout = http_timeout # handle -1 by passing None to requests if self._http_timeout == -1: diff --git a/globus_sdk/config.py b/globus_sdk/config.py index d1c7147f..1f5bc364 100644 --- a/globus_sdk/config.py +++ b/globus_sdk/config.py @@ -175,17 +175,25 @@ def _bool_cast(value): raise ValueError("Invalid config bool") -def get_default_environ(): +def get_globus_environ(inputenv=None): """ - Get the default environment to look for in the config, as a string. + Get the environment to look for in the config, as a string. + Typically just "default", but it can be overridden with `GLOBUS_SDK_ENVIRONMENT` in the shell environment. In that case, any client which does not explicitly specify its environment will use this value. + + :param inputenv: An environment which was passed, e.g. to a client + instantiation """ - env = os.environ.get('GLOBUS_SDK_ENVIRONMENT', 'default') + if inputenv is None: + env = os.environ.get('GLOBUS_SDK_ENVIRONMENT', 'default') + else: + env = inputenv + if env == 'production': env = 'default' if env != 'default': logger.info(('On lookup, non-default environment: ' - 'GLOBUS_SDK_ENVIRONMENT={}'.format(env))) + 'globus_environment={}'.format(env))) return env
Creating a client with `environment="production"` does not properly translate as it would with the environment variable The default config section has the "production" environment values. We have handling code for this in `globus_sdk.config_get_default_environ`, but that only runs if `environment` isn't passed to a client. As a result, config lookups are done against the `production` section and fail. There are several ways of handling this, but one option which is probably pretty foolproof is to update this: https://github.com/globus/globus-sdk-python/blob/d761ba9a104ba2d8a70d2e064d12ea95101596df/globus_sdk/base.py#L85-L86 Instead of doing that, try ```python environment = config.get_default_environ(environment) ``` and update `get_default_environ` to take an input.
globus/globus-sdk-python
diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 7ed9106e..fee2929c 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -148,22 +148,35 @@ class ConfigParserTests(CapturedIOTestCase): with self.assertRaises(ValueError): globus_sdk.config._bool_cast("invalid") - def test_get_default_environ(self): + def test_get_globus_environ(self): """ Confirms returns "default", or the value of GLOBUS_SDK_ENVIRONMENT """ - # default if no environ value exists - prev_setting = None - if "GLOBUS_SDK_ENVIRONMENT" in os.environ: - prev_setting = os.environ["GLOBUS_SDK_ENVIRONMENT"] + # mock environ to ensure it gets reset + with mock.patch.dict(os.environ): + # set an environment value, ensure that it's returned + os.environ["GLOBUS_SDK_ENVIRONMENT"] = "beta" + self.assertEqual(globus_sdk.config.get_globus_environ(), "beta") + + # clear that value, "default" should be returned del os.environ["GLOBUS_SDK_ENVIRONMENT"] - self.assertEqual(globus_sdk.config.get_default_environ(), "default") - # otherwise environ value - os.environ["GLOBUS_SDK_ENVIRONMENT"] = "beta" - self.assertEqual(globus_sdk.config.get_default_environ(), "beta") - - # cleanup for other tests - if prev_setting: - os.environ["GLOBUS_SDK_ENVIRONMENT"] = prev_setting - else: + self.assertEqual(globus_sdk.config.get_globus_environ(), "default") + + # ensure that passing a value returns that value + self.assertEqual( + globus_sdk.config.get_globus_environ("beta"), "beta") + + def test_get_globus_environ_production(self): + """ + Confirms that get_globus_environ translates "production" to "default", + including when special values are passed + """ + # mock environ to ensure it gets reset + with mock.patch.dict(os.environ): + os.environ["GLOBUS_SDK_ENVIRONMENT"] = "production" + self.assertEqual(globus_sdk.config.get_globus_environ(), "default") + del os.environ["GLOBUS_SDK_ENVIRONMENT"] + # ensure that passing a value returns that value + self.assertEqual( + globus_sdk.config.get_globus_environ("production"), "default")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-randomly", "pytest-xdist", "pytest-cov", "coverage", "responses", "flaky", "execnet", "iniconfig", "packaging", "pluggy", "pyyaml", "requests", "urllib3", "charset-normalizer", "idna", "certifi" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 coverage==7.8.0 cryptography==44.0.2 exceptiongroup==1.2.2 execnet==2.1.1 flaky==3.8.1 -e git+https://github.com/globus/globus-sdk-python.git@d761ba9a104ba2d8a70d2e064d12ea95101596df#egg=globus_sdk idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pycparser==2.22 PyJWT==1.7.1 pytest==8.3.5 pytest-cov==6.0.0 pytest-randomly==3.16.0 pytest-xdist==3.6.1 PyYAML==6.0.2 requests==2.32.3 responses==0.25.7 six==1.17.0 tomli==2.2.1 urllib3==2.3.0 zipp==3.21.0
name: globus-sdk-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - coverage==7.8.0 - cryptography==44.0.2 - exceptiongroup==1.2.2 - execnet==2.1.1 - flaky==3.8.1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pyjwt==1.7.1 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-randomly==3.16.0 - pytest-xdist==3.6.1 - pyyaml==6.0.2 - requests==2.32.3 - responses==0.25.7 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/globus-sdk-python
[ "tests/unit/test_config.py::ConfigParserTests::test_get_globus_environ_production", "tests/unit/test_config.py::ConfigParserTests::test_get_globus_environ" ]
[]
[ "tests/unit/test_config.py::ConfigParserTests::test_get_service_url", "tests/unit/test_config.py::ConfigParserTests::test_get_lib_config_path", "tests/unit/test_config.py::ConfigParserTests::test_get_ssl_verify", "tests/unit/test_config.py::ConfigParserTests::test_get", "tests/unit/test_config.py::ConfigParserTests::test_init_and_load_config", "tests/unit/test_config.py::ConfigParserTests::test_bool_cast", "tests/unit/test_config.py::ConfigParserTests::test_get_parser" ]
[]
Apache License 2.0
2,974
791
[ "globus_sdk/base.py", "globus_sdk/config.py" ]
pypa__wheel-250
f3855494f20724f1ae844631d08e34367e977661
2018-08-28 20:35:56
e774538e0be3a5ca79ca31b1ae01c6672480bef6
codecov[bot]: # [Codecov](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=h1) Report > Merging [#250](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=desc) into [master](https://codecov.io/gh/pypa/wheel/commit/f3855494f20724f1ae844631d08e34367e977661?src=pr&el=desc) will **decrease** coverage by `4.17%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/pypa/wheel/pull/250/graphs/tree.svg?width=650&token=ey5B5hA7sW&height=150&src=pr)](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #250 +/- ## ========================================== - Coverage 59.31% 55.13% -4.18% ========================================== Files 12 12 Lines 816 818 +2 ========================================== - Hits 484 451 -33 - Misses 332 367 +35 ``` | [Impacted Files](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [wheel/metadata.py](https://codecov.io/gh/pypa/wheel/pull/250/diff?src=pr&el=tree#diff-d2hlZWwvbWV0YWRhdGEucHk=) | `81.81% <100%> (-15.52%)` | :arrow_down: | | [wheel/pkginfo.py](https://codecov.io/gh/pypa/wheel/pull/250/diff?src=pr&el=tree#diff-d2hlZWwvcGtnaW5mby5weQ==) | `48.27% <0%> (-37.94%)` | :arrow_down: | | [wheel/util.py](https://codecov.io/gh/pypa/wheel/pull/250/diff?src=pr&el=tree#diff-d2hlZWwvdXRpbC5weQ==) | `76.92% <0%> (-23.08%)` | :arrow_down: | | [wheel/pep425tags.py](https://codecov.io/gh/pypa/wheel/pull/250/diff?src=pr&el=tree#diff-d2hlZWwvcGVwNDI1dGFncy5weQ==) | `28.44% <0%> (-3.67%)` | :arrow_down: | | [wheel/wheelfile.py](https://codecov.io/gh/pypa/wheel/pull/250/diff?src=pr&el=tree#diff-d2hlZWwvd2hlZWxmaWxlLnB5) | `98.09% <0%> (-1.91%)` | :arrow_down: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=footer). Last update [f385549...5b576de](https://codecov.io/gh/pypa/wheel/pull/250?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments). cam72cam: I can confirm that this works in relation to https://github.com/pypa/pip/issues/5768 pradyunsg: The PEP changes are accepted, so merging this should be acceptable now IMO. /cc @pypa/wheel-committers
diff --git a/wheel/metadata.py b/wheel/metadata.py index 4fa17cd..c6a3736 100644 --- a/wheel/metadata.py +++ b/wheel/metadata.py @@ -16,7 +16,10 @@ EXTRA_RE = re.compile("""^(?P<package>.*?)(;\s*(?P<condition>.*?)(extra == '(?P< def requires_to_requires_dist(requirement): - """Compose the version predicates for requirement in PEP 345 fashion.""" + """Return the version specifier for a requirement in PEP 345/566 fashion.""" + if requirement.url: + return " @ " + requirement.url + requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver)
How should a PEP 508 requirement with an URL specifier be handled? Starting with pip 10.0, requirements with [URL specifiers](https://www.python.org/dev/peps/pep-0508/#examples) are now supported (as replacement for dependency links). With the following sample project' `setup.py`: ```python from setuptools import setup setup(name='projecta', version='42', install_requires=''' lazyImport@git+https://gitlab.com/KOLANICH1/lazyImport.py.git#egg=lazyImport-dev ''') ``` Installing from source work, but looking at the generated wheel metadata: ```shell > python setup.py -q bdist_wheel && unzip -p dist/projecta-42-py3-none-any.whl '*/METADATA' Metadata-Version: 2.1 Name: projecta Version: 42 Summary: Description! Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Platform: UNKNOWN Requires-Dist: lazyImport UNKNOWN ``` It works with the following patch: ```diff tests/test_metadata.py | 3 +++ wheel/metadata.py | 2 ++ 2 files changed, 5 insertions(+) diff --git i/tests/test_metadata.py w/tests/test_metadata.py index 3421430..2390e98 100644 --- i/tests/test_metadata.py +++ w/tests/test_metadata.py @@ -9,6 +9,7 @@ def test_pkginfo_to_metadata(tmpdir): ('Provides-Extra', 'test'), ('Provides-Extra', 'signatures'), ('Provides-Extra', 'faster-signatures'), + ('Requires-Dist', "pip @ https://github.com/pypa/pip/archive/1.3.1.zip"), ('Requires-Dist', "ed25519ll; extra == 'faster-signatures'"), ('Requires-Dist', "keyring; extra == 'signatures'"), ('Requires-Dist', "keyrings.alt; extra == 'signatures'"), @@ -28,6 +29,8 @@ def test_pkginfo_to_metadata(tmpdir): egg_info_dir = tmpdir.ensure_dir('test.egg-info') egg_info_dir.join('requires.txt').write("""\ +pip@ https://github.com/pypa/pip/archive/1.3.1.zip + [faster-signatures] ed25519ll diff --git i/wheel/metadata.py w/wheel/metadata.py index 4fa17cd..5b03e3e 100644 --- i/wheel/metadata.py +++ w/wheel/metadata.py @@ -17,6 +17,8 @@ def requires_to_requires_dist(requirement): """Compose the version predicates for requirement in PEP 345 fashion.""" + if requirement.url: + return " @ " + requirement.url requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver) ``` ```shell > python setup.py -q bdist_wheel && unzip -p dist/projecta-42-py3-none-any.whl '*/METADATA' Metadata-Version: 2.1 Name: projecta Version: 42 Summary: Description! Home-page: UNKNOWN Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Platform: UNKNOWN Requires-Dist: lazyImport @ git+https://gitlab.com/KOLANICH1/lazyImport.py.git UNKNOWN ``` Unfortunately, this is technically not valid [PEP 345](https://www.python.org/dev/peps/pep-0345/#requires-dist-multiple-use) metadata.
pypa/wheel
diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 3421430..78fe40d 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -9,6 +9,7 @@ def test_pkginfo_to_metadata(tmpdir): ('Provides-Extra', 'test'), ('Provides-Extra', 'signatures'), ('Provides-Extra', 'faster-signatures'), + ('Requires-Dist', "pip @ https://github.com/pypa/pip/archive/1.3.1.zip"), ('Requires-Dist', "ed25519ll; extra == 'faster-signatures'"), ('Requires-Dist', "keyring; extra == 'signatures'"), ('Requires-Dist', "keyrings.alt; extra == 'signatures'"), @@ -28,6 +29,8 @@ Provides-Extra: faster-signatures""") egg_info_dir = tmpdir.ensure_dir('test.egg-info') egg_info_dir.join('requires.txt').write("""\ +pip@https://github.com/pypa/pip/archive/1.3.1.zip + [faster-signatures] ed25519ll
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.31
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: wheel channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - pytest-cov==6.0.0 prefix: /opt/conda/envs/wheel
[ "tests/test_metadata.py::test_pkginfo_to_metadata" ]
[]
[]
[]
MIT License
2,986
190
[ "wheel/metadata.py" ]
fatiando__pooch-23
ea607a2f9ff4c8e3dc03d7eb350555dd544709d4
2018-08-29 03:45:40
1ff4910849be2db6dec33c5d3c3828f2e9addb74
leouieda: Waiting on conda-forge/pytest-feedstock#55 to fix the pytest issues on Mac.
diff --git a/pooch/core.py b/pooch/core.py index 7093b7c..1967913 100644 --- a/pooch/core.py +++ b/pooch/core.py @@ -2,9 +2,10 @@ Functions to download, verify, and update a sample dataset. """ import os +import sys from pathlib import Path import shutil -from tempfile import NamedTemporaryFile +import tempfile from warnings import warn import requests @@ -12,6 +13,11 @@ import requests from .utils import file_hash, check_version +# PermissionError was introduced in Python 3.3. This can be deleted when dropping 2.7 +if sys.version_info[0] < 3: + PermissionError = OSError # pylint: disable=redefined-builtin,invalid-name + + def create(path, base_url, version, version_dev, env=None, registry=None): """ Create a new :class:`~pooch.Pooch` with sensible defaults to fetch data files. @@ -27,8 +33,6 @@ def create(path, base_url, version, version_dev, env=None, registry=None): ``https://github.com/fatiando/pooch/raw/v0.1/data``). If the version string contains ``+XX.XXXXX``, it will be interpreted as a development version. - If the local storage path doesn't exit, it will be created. - Parameters ---------- path : str, PathLike, list or tuple @@ -73,9 +77,6 @@ def create(path, base_url, version, version_dev, env=None, registry=None): ... registry={"data.txt": "9081wo2eb2gc0u..."}) >>> print(pup.path.parts) # The path is a pathlib.Path ('myproject', 'v0.1') - >>> # We'll create the directory if it doesn't exist yet. - >>> pup.path.exists() - True >>> print(pup.base_url) http://some.link.com/v0.1/ >>> print(pup.registry) @@ -89,8 +90,6 @@ def create(path, base_url, version, version_dev, env=None, registry=None): ... version_dev="master") >>> print(pup.path.parts) ('myproject', 'master') - >>> pup.path.exists() - True >>> print(pup.base_url) http://some.link.com/master/ @@ -103,8 +102,6 @@ def create(path, base_url, version, version_dev, env=None, registry=None): ... version_dev="master") >>> print(pup.path.parts) ('myproject', 'cache', 'data', 'v0.1') - >>> pup.path.exists() - True The user can overwrite the storage path by setting an environment variable: @@ -127,10 +124,6 @@ def create(path, base_url, version, version_dev, env=None, registry=None): >>> print(pup.path.parts) ('myproject', 'from_env', 'v0.1') - Clean up the files we created: - - >>> import shutil; shutil.rmtree("myproject") - """ version = check_version(version, fallback=version_dev) if isinstance(path, (list, tuple)): @@ -138,9 +131,25 @@ def create(path, base_url, version, version_dev, env=None, registry=None): if env is not None and env in os.environ and os.environ[env]: path = os.environ[env] versioned_path = os.path.join(os.path.expanduser(str(path)), version) - # Create the directory if it doesn't already exist - if not os.path.exists(versioned_path): - os.makedirs(versioned_path) + # Check that the data directory is writable + try: + if not os.path.exists(versioned_path): + os.makedirs(versioned_path) + else: + tempfile.NamedTemporaryFile(dir=versioned_path) + except PermissionError: + message = ( + "Cannot write to data cache '{}'. " + "Will not be able to download remote data files.".format(versioned_path) + ) + if env is not None: + message = ( + message + + "Use environment variable '{}' to specify another directory.".format( + env + ) + ) + warn(message) if registry is None: registry = dict() pup = Pooch( @@ -185,10 +194,10 @@ class Pooch: """ Get the absolute path to a file in the local storage. - If it's not in the local storage, it will be downloaded. If the hash of file in - local storage doesn't match the one in the registry, will download a new copy of - the file. This is considered a sign that the file was updated in the remote - storage. If the hash of the downloaded file doesn't match the one in the + If it's not in the local storage, it will be downloaded. If the hash of the file + in local storage doesn't match the one in the registry, will download a new copy + of the file. This is considered a sign that the file was updated in the remote + storage. If the hash of the downloaded file still doesn't match the one in the registry, will raise an exception to warn of possible file corruption. Parameters @@ -206,15 +215,27 @@ class Pooch: """ if fname not in self.registry: raise ValueError("File '{}' is not in the registry.".format(fname)) + # Create the local data directory if it doesn't already exist + if not self.abspath.exists(): + os.makedirs(str(self.abspath)) full_path = self.abspath / fname in_storage = full_path.exists() - update = in_storage and file_hash(str(full_path)) != self.registry[fname] - download = not in_storage - if update or download: - self._download_file(fname, update) + if not in_storage: + action = "Downloading" + elif in_storage and file_hash(str(full_path)) != self.registry[fname]: + action = "Updating" + else: + action = "Nothing" + if action in ("Updating", "Downloading"): + warn( + "{} data file '{}' from remote data store '{}' to '{}'.".format( + action, fname, self.base_url, str(self.path) + ) + ) + self._download_file(fname) return str(full_path) - def _download_file(self, fname, update): + def _download_file(self, fname): """ Download a file from the remote data storage to the local storage. @@ -223,8 +244,6 @@ class Pooch: fname : str The file name (relative to the *base_url* of the remote data storage) to fetch from the local storage. - update : bool - True if the file already exists in the storage but needs an update. Raises ------ @@ -232,22 +251,13 @@ class Pooch: If the hash of the downloaded file doesn't match the hash in the registry. """ - destination = Path(self.abspath, fname) + destination = self.abspath / fname source = "".join([self.base_url, fname]) - if update: - action = "Updating" - else: - action = "Downloading" - warn( - "{} data file '{}' from remote data store '{}' to '{}'.".format( - action, fname, self.base_url, str(self.path) - ) - ) - response = requests.get(source, stream=True) - response.raise_for_status() # Stream the file to a temporary so that we can safely check its hash before # overwriting the original - with NamedTemporaryFile(delete=False) as fout: + with tempfile.NamedTemporaryFile(delete=False) as fout: + response = requests.get(source, stream=True) + response.raise_for_status() for chunk in response.iter_content(chunk_size=1024): if chunk: fout.write(chunk)
pooch.create should test for write access to directories and have a failback for failures See realworld implementation problem with Unidata/MetPy#933 `pooch.create` can fail to write to whatever cache directory it is presented with. A failback mechanism should exist, like what does with `matplotlib` when it attempts to find writable locations. There is also a [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) for this. ```python POOCH = pooch.create( path=pooch.os_cache('metpy'), base_url='https://github.com/Unidata/MetPy/raw/{version}/staticdata/', version='v' + __version__, version_dev='master', env='TEST_DATA_DIR') ``` ## Full error message ``` File "/opt/miniconda3/envs/prod/lib/python3.6/site-packages/pooch/core.py", line 143, in create os.makedirs(versioned_path) File "/opt/miniconda3/envs/prod/lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/opt/miniconda3/envs/prod/lib/python3.6/os.py", line 210, in makedirs makedirs(head, mode, exist_ok) File "/opt/miniconda3/envs/prod/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/share/httpd/.cache' ``` thank you
fatiando/pooch
diff --git a/pooch/tests/test_core.py b/pooch/tests/test_core.py index 55a8f42..28d6bb0 100644 --- a/pooch/tests/test_core.py +++ b/pooch/tests/test_core.py @@ -2,7 +2,9 @@ Test the core class and factory function. """ import os +import sys from pathlib import Path +import tempfile try: from tempfile import TemporaryDirectory @@ -12,11 +14,16 @@ import warnings import pytest -from .. import Pooch +from .. import Pooch, create from ..utils import file_hash from .utils import pooch_test_url, pooch_test_registry, check_tiny_data +# PermissionError was introduced in Python 3.3. This can be deleted when dropping 2.7 +if sys.version_info[0] < 3: + PermissionError = OSError # pylint: disable=redefined-builtin,invalid-name + + DATA_DIR = str(Path(__file__).parent / "data") REGISTRY = pooch_test_registry() BASEURL = pooch_test_url() @@ -104,3 +111,66 @@ def test_pooch_load_registry_invalid_line(): pup = Pooch(path="", base_url="", registry={}) with pytest.raises(ValueError): pup.load_registry(os.path.join(DATA_DIR, "registry-invalid.txt")) + + +def test_create_makedirs_permissionerror(monkeypatch): + "Should warn the user when can't create the local data dir" + + def mockmakedirs(path): # pylint: disable=unused-argument + "Raise an exception to mimic permission issues" + raise PermissionError("Fake error") + + data_cache = os.path.join(os.curdir, "test_permission") + assert not os.path.exists(data_cache) + + monkeypatch.setattr(os, "makedirs", mockmakedirs) + + with warnings.catch_warnings(record=True) as warn: + pup = create( + path=data_cache, + base_url="", + version="1.0", + version_dev="master", + env="SOME_VARIABLE", + registry={"afile.txt": "ahash"}, + ) + assert len(warn) == 1 + assert issubclass(warn[-1].category, UserWarning) + assert str(warn[-1].message).startswith("Cannot write to data cache") + assert "'SOME_VARIABLE'" in str(warn[-1].message) + + with pytest.raises(PermissionError): + pup.fetch("afile.txt") + + +def test_create_newfile_permissionerror(monkeypatch): + "Should warn the user when can't write to the local data dir" + # This is a separate function because there should be a warning if the data dir + # already exists but we can't write to it. + + def mocktempfile(**kwargs): # pylint: disable=unused-argument + "Raise an exception to mimic permission issues" + raise PermissionError("Fake error") + + with TemporaryDirectory() as data_cache: + os.makedirs(os.path.join(data_cache, "1.0")) + assert os.path.exists(data_cache) + + monkeypatch.setattr(tempfile, "NamedTemporaryFile", mocktempfile) + + with warnings.catch_warnings(record=True) as warn: + pup = create( + path=data_cache, + base_url="", + version="1.0", + version_dev="master", + env="SOME_VARIABLE", + registry={"afile.txt": "ahash"}, + ) + assert len(warn) == 1 + assert issubclass(warn[-1].category, UserWarning) + assert str(warn[-1].message).startswith("Cannot write to data cache") + assert "'SOME_VARIABLE'" in str(warn[-1].message) + + with pytest.raises(PermissionError): + pup.fetch("afile.txt") diff --git a/pooch/tests/test_integration.py b/pooch/tests/test_integration.py index aeb4ada..d7dd16f 100644 --- a/pooch/tests/test_integration.py +++ b/pooch/tests/test_integration.py @@ -26,15 +26,16 @@ def pup(): ) # The str conversion is needed in Python 3.5 doggo.load_registry(str(Path(os.path.dirname(__file__), "data", "registry.txt"))) + if os.path.exists(str(doggo.abspath)): + shutil.rmtree(str(doggo.abspath)) yield doggo shutil.rmtree(str(doggo.abspath)) def test_fetch(pup): "Fetch a data file from the local storage" - # Make sure the storage exists and is empty to begin - assert pup.abspath.exists() - assert not list(pup.abspath.iterdir()) + # Make sure the storage has been cleaned up before running the tests + assert not pup.abspath.exists() for target in ["tiny-data.txt", "subdir/tiny-data.txt"]: with warnings.catch_warnings(record=True) as warn: fname = pup.fetch(target)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 astroid==2.11.7 attrs==22.2.0 Babel==2.11.0 bleach==4.1.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 colorama==0.4.5 coverage==6.2 cryptography==40.0.2 dill==0.3.4 docutils==0.18.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 isort==5.10.1 jeepney==0.7.1 Jinja2==3.0.3 keyring==23.4.1 lazy-object-proxy==1.7.1 MarkupSafe==2.0.1 mccabe==0.7.0 numpydoc==1.1.0 packaging==21.3 pkginfo==1.10.0 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/fatiando/pooch.git@ea607a2f9ff4c8e3dc03d7eb350555dd544709d4#egg=pooch py==1.11.0 pycparser==2.21 Pygments==2.14.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytz==2025.2 readme-renderer==34.0 requests==2.27.1 requests-toolbelt==1.0.0 rfc3986==1.5.0 SecretStorage==3.3.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 tqdm==4.64.1 twine==3.8.0 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 webencodings==0.5.1 wrapt==1.16.0 zipp==3.6.0
name: pooch channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - astroid==2.11.7 - attrs==22.2.0 - babel==2.11.0 - bleach==4.1.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - coverage==6.2 - cryptography==40.0.2 - dill==0.3.4 - docutils==0.18.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - isort==5.10.1 - jeepney==0.7.1 - jinja2==3.0.3 - keyring==23.4.1 - lazy-object-proxy==1.7.1 - markupsafe==2.0.1 - mccabe==0.7.0 - numpydoc==1.1.0 - packaging==21.3 - pkginfo==1.10.0 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycparser==2.21 - pygments==2.14.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytz==2025.2 - readme-renderer==34.0 - requests==2.27.1 - requests-toolbelt==1.0.0 - rfc3986==1.5.0 - secretstorage==3.3.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - tqdm==4.64.1 - twine==3.8.0 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - webencodings==0.5.1 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/pooch
[ "pooch/tests/test_core.py::test_create_makedirs_permissionerror", "pooch/tests/test_core.py::test_create_newfile_permissionerror" ]
[ "pooch/tests/test_core.py::test_pooch_update", "pooch/tests/test_core.py::test_pooch_corrupted", "pooch/tests/test_integration.py::test_fetch" ]
[ "pooch/tests/test_core.py::test_pooch_local", "pooch/tests/test_core.py::test_pooch_file_not_in_registry", "pooch/tests/test_core.py::test_pooch_load_registry", "pooch/tests/test_core.py::test_pooch_load_registry_invalid_line" ]
[]
BSD License
2,987
1,859
[ "pooch/core.py" ]
dask__dask-3919
09100d02ad8f2b23da70234707888b1374dd46bd
2018-08-29 16:23:29
df1cee3b55706443303b85563e7c01e26611603d
TomAugspurger: I *think* this is what we want to do here. This may surprise some users, if their callable either expects or incidentally creates a pandas dataframe. If a concrete dataframe really is needed, then `df.map_blocks(pd.DataFrame.assign, column=callable)` should be used instead I think. mrocklin: Is anyone available to review this?
diff --git a/dask/dataframe/categorical.py b/dask/dataframe/categorical.py index 9900b54af..f372aa2ca 100644 --- a/dask/dataframe/categorical.py +++ b/dask/dataframe/categorical.py @@ -184,7 +184,7 @@ class CategoricalAccessor(Accessor): Keywords to pass on to the call to `compute`. """ if self.known: - return self + return self._series categories = self._property_map('categories').unique().compute(**kwargs) return self.set_categories(categories.values) diff --git a/dask/dataframe/core.py b/dask/dataframe/core.py index 807111334..855eed317 100644 --- a/dask/dataframe/core.py +++ b/dask/dataframe/core.py @@ -2681,6 +2681,9 @@ class DataFrame(_Frame): callable(v) or pd.api.types.is_scalar(v)): raise TypeError("Column assignment doesn't support type " "{0}".format(type(v).__name__)) + if callable(v): + kwargs[k] = v(self) + pairs = list(sum(kwargs.items(), ())) # Figure out columns of the output
`.assign` leads to different results when using lambda vs not using lambda `.assign` leads to different results when using lambda vs not using lambda. Please see the example below. The difference seems to happen only in the divisions limits. I guess this is a bug? Any idea on why this is happening? ### Imports ```python import pandas as pd import numpy as np import dask.dataframe as dd ``` ### Create Dataframe ```python idx = pd.date_range(start='2013-01-01 00:00:00', end='2013-01-01 06:00:00', freq='30t') df_pd = pd.DataFrame({'col_1':[1,2,3,4,5,6,7,8,9,10,11,12,13,]}, index=idx) df = dd.from_pandas(df_pd, npartitions=2) df.compute() ``` <div> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>col_1</th> </tr> </thead> <tbody> <tr> <th>2013-01-01 00:00:00</th> <td>1</td> </tr> <tr> <th>2013-01-01 00:30:00</th> <td>2</td> </tr> <tr> <th>2013-01-01 01:00:00</th> <td>3</td> </tr> <tr> <th>2013-01-01 01:30:00</th> <td>4</td> </tr> <tr> <th>2013-01-01 02:00:00</th> <td>5</td> </tr> <tr> <th>2013-01-01 02:30:00</th> <td>6</td> </tr> <tr> <th>2013-01-01 03:00:00</th> <td>7</td> </tr> <tr> <th>2013-01-01 03:30:00</th> <td>8</td> </tr> <tr> <th>2013-01-01 04:00:00</th> <td>9</td> </tr> <tr> <th>2013-01-01 04:30:00</th> <td>10</td> </tr> <tr> <th>2013-01-01 05:00:00</th> <td>11</td> </tr> <tr> <th>2013-01-01 05:30:00</th> <td>12</td> </tr> <tr> <th>2013-01-01 06:00:00</th> <td>13</td> </tr> </tbody> </table> </div> ```python df.divisions ``` (Timestamp('2013-01-01 00:00:00', freq='30T'), Timestamp('2013-01-01 03:30:00', freq='30T'), Timestamp('2013-01-01 06:00:00', freq='30T')) ### This is what the shifted column looks like: ```python df.col_1.shift(freq='1h').compute().to_frame() ``` <div> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>col_1</th> </tr> </thead> <tbody> <tr> <th>2013-01-01 01:00:00</th> <td>1</td> </tr> <tr> <th>2013-01-01 01:30:00</th> <td>2</td> </tr> <tr> <th>2013-01-01 02:00:00</th> <td>3</td> </tr> <tr> <th>2013-01-01 02:30:00</th> <td>4</td> </tr> <tr> <th>2013-01-01 03:00:00</th> <td>5</td> </tr> <tr> <th>2013-01-01 03:30:00</th> <td>6</td> </tr> <tr> <th>2013-01-01 04:00:00</th> <td>7</td> </tr> <tr> <th>2013-01-01 04:30:00</th> <td>8</td> </tr> <tr> <th>2013-01-01 05:00:00</th> <td>9</td> </tr> <tr> <th>2013-01-01 05:30:00</th> <td>10</td> </tr> <tr> <th>2013-01-01 06:00:00</th> <td>11</td> </tr> <tr> <th>2013-01-01 06:30:00</th> <td>12</td> </tr> <tr> <th>2013-01-01 07:00:00</th> <td>13</td> </tr> </tbody> </table> </div> ### This is what assigning the shifted column without using lambda, looks like: ```python df.assign(shifted=df.col_1.shift(freq='1h')).compute() ``` <div> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>col_1</th> <th>shifted</th> </tr> </thead> <tbody> <tr> <th>2013-01-01 00:00:00</th> <td>1</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 00:30:00</th> <td>2</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 01:00:00</th> <td>3</td> <td>1.0</td> </tr> <tr> <th>2013-01-01 01:30:00</th> <td>4</td> <td>2.0</td> </tr> <tr> <th>2013-01-01 02:00:00</th> <td>5</td> <td>3.0</td> </tr> <tr> <th>2013-01-01 02:30:00</th> <td>6</td> <td>4.0</td> </tr> <tr> <th>2013-01-01 03:00:00</th> <td>7</td> <td>5.0</td> </tr> <tr> <th>2013-01-01 03:30:00</th> <td>8</td> <td>6.0</td> </tr> <tr> <th>2013-01-01 04:00:00</th> <td>9</td> <td>7.0</td> </tr> <tr> <th>2013-01-01 04:30:00</th> <td>10</td> <td>8.0</td> </tr> <tr> <th>2013-01-01 05:00:00</th> <td>11</td> <td>9.0</td> </tr> <tr> <th>2013-01-01 05:30:00</th> <td>12</td> <td>10.0</td> </tr> <tr> <th>2013-01-01 06:00:00</th> <td>13</td> <td>11.0</td> </tr> </tbody> </table> </div> ### This is what assigning the shifted column using lambda, looks like: ```python df.assign(shifted=lambda x: x.col_1.shift(freq='1h')).compute() ``` <div> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>col_1</th> <th>shifted</th> </tr> </thead> <tbody> <tr> <th>2013-01-01 00:00:00</th> <td>1</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 00:30:00</th> <td>2</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 01:00:00</th> <td>3</td> <td>1.0</td> </tr> <tr> <th>2013-01-01 01:30:00</th> <td>4</td> <td>2.0</td> </tr> <tr> <th>2013-01-01 02:00:00</th> <td>5</td> <td>3.0</td> </tr> <tr> <th>2013-01-01 02:30:00</th> <td>6</td> <td>4.0</td> </tr> <tr> <th>2013-01-01 03:00:00</th> <td>7</td> <td>5.0</td> </tr> <tr> <th>2013-01-01 03:30:00</th> <td>8</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 04:00:00</th> <td>9</td> <td>NaN</td> </tr> <tr> <th>2013-01-01 04:30:00</th> <td>10</td> <td>8.0</td> </tr> <tr> <th>2013-01-01 05:00:00</th> <td>11</td> <td>9.0</td> </tr> <tr> <th>2013-01-01 05:30:00</th> <td>12</td> <td>10.0</td> </tr> <tr> <th>2013-01-01 06:00:00</th> <td>13</td> <td>11.0</td> </tr> </tbody> </table> </div>
dask/dask
diff --git a/dask/dataframe/tests/test_categorical.py b/dask/dataframe/tests/test_categorical.py index b84011818..3b643e82e 100644 --- a/dask/dataframe/tests/test_categorical.py +++ b/dask/dataframe/tests/test_categorical.py @@ -271,6 +271,14 @@ def assert_array_index_eq(left, right): assert_eq(left, pd.Index(right) if isinstance(right, np.ndarray) else right) +def test_return_type_known_categories(): + df = pd.DataFrame({"A": ['a', 'b', 'c']}) + df['A'] = df['A'].astype('category') + dask_df = dd.from_pandas(df, 2) + ret_type = dask_df.A.cat.as_known() + assert isinstance(ret_type, dd.core.Series) + + class TestCategoricalAccessor: @pytest.mark.parametrize('series', cat_series) diff --git a/dask/dataframe/tests/test_dataframe.py b/dask/dataframe/tests/test_dataframe.py index 41a50385d..a9e61cc86 100644 --- a/dask/dataframe/tests/test_dataframe.py +++ b/dask/dataframe/tests/test_dataframe.py @@ -925,6 +925,13 @@ def test_assign(): d.assign(foo=d_unknown.a) +def test_assign_callable(): + df = dd.from_pandas(pd.DataFrame({"A": range(10)}), npartitions=2) + a = df.assign(B=df.A.shift()) + b = df.assign(B=lambda x: x.A.shift()) + assert_eq(a, b) + + def test_map(): assert_eq(d.a.map(lambda x: x + 1), full.a.map(lambda x: x + 1)) lk = dict((v, v + 1) for v in full.a.values)
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 2 }
1.23
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-xdist", "pytest-cov", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 click==8.0.4 cloudpickle==2.2.1 coverage==6.2 -e git+https://github.com/dask/dask.git@09100d02ad8f2b23da70234707888b1374dd46bd#egg=dask distributed==1.28.1 execnet==1.9.0 HeapDict==1.0.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work locket==1.0.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work msgpack==1.0.5 numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 partd==1.2.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work psutil==7.0.0 py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 six==1.17.0 sortedcontainers==2.4.0 tblib==1.7.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 toolz==0.12.0 tornado==6.1 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zict==2.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - click==8.0.4 - cloudpickle==2.2.1 - coverage==6.2 - distributed==1.28.1 - execnet==1.9.0 - heapdict==1.0.1 - locket==1.0.0 - msgpack==1.0.5 - numpy==1.19.5 - pandas==1.1.5 - partd==1.2.0 - psutil==7.0.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - six==1.17.0 - sortedcontainers==2.4.0 - tblib==1.7.0 - tomli==1.2.3 - toolz==0.12.0 - tornado==6.1 - zict==2.1.0 prefix: /opt/conda/envs/dask
[ "dask/dataframe/tests/test_categorical.py::test_return_type_known_categories", "dask/dataframe/tests/test_dataframe.py::test_assign_callable" ]
[ "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_unused_categories-kwargs8-series2]", "dask/dataframe/tests/test_dataframe.py::test_attributes", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[npartitions1]", "dask/dataframe/tests/test_dataframe.py::test_clip[2-5]", "dask/dataframe/tests/test_dataframe.py::test_clip[2.5-3.5]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_picklable", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_month", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include0-None]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[None-exclude1]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include2-exclude2]", "dask/dataframe/tests/test_dataframe.py::test_select_dtypes[include3-None]", "dask/dataframe/tests/test_dataframe.py::test_to_timestamp", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array_raises[False0]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array_raises[False1]", "dask/dataframe/tests/test_dataframe.py::test_apply", "dask/dataframe/tests/test_dataframe.py::test_apply_warns", "dask/dataframe/tests/test_dataframe.py::test_apply_infer_columns", "dask/dataframe/tests/test_dataframe.py::test_info", "dask/dataframe/tests/test_dataframe.py::test_groupby_multilevel_info", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx2-False]", "dask/dataframe/tests/test_dataframe.py::test_shift", "dask/dataframe/tests/test_dataframe.py::test_shift_with_freq", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[first]", "dask/dataframe/tests/test_dataframe.py::test_first_and_last[last]", "dask/dataframe/tests/test_dataframe.py::test_datetime_loc_open_slicing" ]
[ "dask/dataframe/tests/test_categorical.py::test_concat_unions_categoricals", "dask/dataframe/tests/test_categorical.py::test_unknown_categoricals", "dask/dataframe/tests/test_categorical.py::test_is_categorical_dtype", "dask/dataframe/tests/test_categorical.py::test_categorize", "dask/dataframe/tests/test_categorical.py::test_categorize_index", "dask/dataframe/tests/test_categorical.py::test_categorical_set_index[disk]", "dask/dataframe/tests/test_categorical.py::test_categorical_set_index[tasks]", "dask/dataframe/tests/test_categorical.py::test_repartition_on_categoricals[1]", "dask/dataframe/tests/test_categorical.py::test_repartition_on_categoricals[4]", "dask/dataframe/tests/test_categorical.py::test_categorical_accessor_presence", "dask/dataframe/tests/test_categorical.py::test_categorize_nan", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[categories-assert_array_index_eq-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[categories-assert_array_index_eq-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[categories-assert_array_index_eq-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[ordered-assert_eq-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[ordered-assert_eq-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[ordered-assert_eq-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[codes-assert_array_index_eq-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[codes-assert_array_index_eq-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_properties[codes-assert_array_index_eq-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[add_categories-kwargs0-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[add_categories-kwargs0-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[add_categories-kwargs0-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs1-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs1-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs1-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_unordered-kwargs2-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_unordered-kwargs2-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_unordered-kwargs2-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs3-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs3-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[as_ordered-kwargs3-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_categories-kwargs4-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_categories-kwargs4-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_categories-kwargs4-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[rename_categories-kwargs5-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[rename_categories-kwargs5-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[rename_categories-kwargs5-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[reorder_categories-kwargs6-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[reorder_categories-kwargs6-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[reorder_categories-kwargs6-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[set_categories-kwargs7-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[set_categories-kwargs7-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[set_categories-kwargs7-series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_unused_categories-kwargs8-series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_callable[remove_unused_categories-kwargs8-series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_categorical_empty", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_unknown_categories[series0]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_unknown_categories[series1]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_unknown_categories[series2]", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_categorical_string_ops", "dask/dataframe/tests/test_categorical.py::TestCategoricalAccessor::test_categorical_non_string_raises", "dask/dataframe/tests/test_dataframe.py::test_Dataframe", "dask/dataframe/tests/test_dataframe.py::test_head_tail", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions", "dask/dataframe/tests/test_dataframe.py::test_head_npartitions_warn", "dask/dataframe/tests/test_dataframe.py::test_index_head", "dask/dataframe/tests/test_dataframe.py::test_Series", "dask/dataframe/tests/test_dataframe.py::test_Index", "dask/dataframe/tests/test_dataframe.py::test_Scalar", "dask/dataframe/tests/test_dataframe.py::test_column_names", "dask/dataframe/tests/test_dataframe.py::test_index_names", "dask/dataframe/tests/test_dataframe.py::test_timezone_freq[1]", "dask/dataframe/tests/test_dataframe.py::test_rename_columns", "dask/dataframe/tests/test_dataframe.py::test_rename_series", "dask/dataframe/tests/test_dataframe.py::test_rename_series_method", "dask/dataframe/tests/test_dataframe.py::test_describe", "dask/dataframe/tests/test_dataframe.py::test_describe_empty", "dask/dataframe/tests/test_dataframe.py::test_cumulative", "dask/dataframe/tests/test_dataframe.py::test_dropna", "dask/dataframe/tests/test_dataframe.py::test_squeeze", "dask/dataframe/tests/test_dataframe.py::test_where_mask", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_multi_argument", "dask/dataframe/tests/test_dataframe.py::test_map_partitions", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_column_info", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_method_names", "dask/dataframe/tests/test_dataframe.py::test_map_partitions_keeps_kwargs_readable", "dask/dataframe/tests/test_dataframe.py::test_metadata_inference_single_partition_aligned_args", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates", "dask/dataframe/tests/test_dataframe.py::test_drop_duplicates_subset", "dask/dataframe/tests/test_dataframe.py::test_get_partition", "dask/dataframe/tests/test_dataframe.py::test_ndim", "dask/dataframe/tests/test_dataframe.py::test_dtype", "dask/dataframe/tests/test_dataframe.py::test_value_counts", "dask/dataframe/tests/test_dataframe.py::test_unique", "dask/dataframe/tests/test_dataframe.py::test_isin", "dask/dataframe/tests/test_dataframe.py::test_len", "dask/dataframe/tests/test_dataframe.py::test_size", "dask/dataframe/tests/test_dataframe.py::test_shape", "dask/dataframe/tests/test_dataframe.py::test_nbytes", "dask/dataframe/tests/test_dataframe.py::test_quantile", "dask/dataframe/tests/test_dataframe.py::test_quantile_missing", "dask/dataframe/tests/test_dataframe.py::test_empty_quantile", "dask/dataframe/tests/test_dataframe.py::test_dataframe_quantile", "dask/dataframe/tests/test_dataframe.py::test_index", "dask/dataframe/tests/test_dataframe.py::test_assign", "dask/dataframe/tests/test_dataframe.py::test_map", "dask/dataframe/tests/test_dataframe.py::test_concat", "dask/dataframe/tests/test_dataframe.py::test_args", "dask/dataframe/tests/test_dataframe.py::test_known_divisions", "dask/dataframe/tests/test_dataframe.py::test_unknown_divisions", "dask/dataframe/tests/test_dataframe.py::test_align[inner]", "dask/dataframe/tests/test_dataframe.py::test_align[outer]", "dask/dataframe/tests/test_dataframe.py::test_align[left]", "dask/dataframe/tests/test_dataframe.py::test_align[right]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[inner]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[outer]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[left]", "dask/dataframe/tests/test_dataframe.py::test_align_axis[right]", "dask/dataframe/tests/test_dataframe.py::test_combine", "dask/dataframe/tests/test_dataframe.py::test_combine_first", "dask/dataframe/tests/test_dataframe.py::test_random_partitions", "dask/dataframe/tests/test_dataframe.py::test_series_round", "dask/dataframe/tests/test_dataframe.py::test_repartition_divisions", "dask/dataframe/tests/test_dataframe.py::test_repartition_on_pandas_dataframe", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>0-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-int-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-float-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-1-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-2-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-4-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-1-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-2-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-4-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-True]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions[<lambda>1-M8[ns]-5-5-False]", "dask/dataframe/tests/test_dataframe.py::test_repartition_npartitions_same_limits", "dask/dataframe/tests/test_dataframe.py::test_repartition_object_index", "dask/dataframe/tests/test_dataframe.py::test_repartition_freq_errors", "dask/dataframe/tests/test_dataframe.py::test_embarrassingly_parallel_operations", "dask/dataframe/tests/test_dataframe.py::test_fillna", "dask/dataframe/tests/test_dataframe.py::test_fillna_multi_dataframe", "dask/dataframe/tests/test_dataframe.py::test_ffill_bfill", "dask/dataframe/tests/test_dataframe.py::test_fillna_series_types", "dask/dataframe/tests/test_dataframe.py::test_sample", "dask/dataframe/tests/test_dataframe.py::test_sample_without_replacement", "dask/dataframe/tests/test_dataframe.py::test_sample_raises", "dask/dataframe/tests/test_dataframe.py::test_datetime_accessor", "dask/dataframe/tests/test_dataframe.py::test_str_accessor", "dask/dataframe/tests/test_dataframe.py::test_empty_max", "dask/dataframe/tests/test_dataframe.py::test_deterministic_apply_concat_apply_names", "dask/dataframe/tests/test_dataframe.py::test_aca_meta_infer", "dask/dataframe/tests/test_dataframe.py::test_aca_split_every", "dask/dataframe/tests/test_dataframe.py::test_reduction_method", "dask/dataframe/tests/test_dataframe.py::test_reduction_method_split_every", "dask/dataframe/tests/test_dataframe.py::test_pipe", "dask/dataframe/tests/test_dataframe.py::test_gh_517", "dask/dataframe/tests/test_dataframe.py::test_drop_axis_1", "dask/dataframe/tests/test_dataframe.py::test_gh580", "dask/dataframe/tests/test_dataframe.py::test_rename_dict", "dask/dataframe/tests/test_dataframe.py::test_rename_function", "dask/dataframe/tests/test_dataframe.py::test_rename_index", "dask/dataframe/tests/test_dataframe.py::test_to_frame", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array_unknown[False0]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array_unknown[False1]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array[False0-lengths0]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array[False0-True]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array[False1-lengths0]", "dask/dataframe/tests/test_dataframe.py::test_to_dask_array[False1-True]", "dask/dataframe/tests/test_dataframe.py::test_applymap", "dask/dataframe/tests/test_dataframe.py::test_abs", "dask/dataframe/tests/test_dataframe.py::test_round", "dask/dataframe/tests/test_dataframe.py::test_cov", "dask/dataframe/tests/test_dataframe.py::test_corr", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_meta", "dask/dataframe/tests/test_dataframe.py::test_cov_corr_mixed", "dask/dataframe/tests/test_dataframe.py::test_autocorr", "dask/dataframe/tests/test_dataframe.py::test_index_time_properties", "dask/dataframe/tests/test_dataframe.py::test_nlargest_nsmallest", "dask/dataframe/tests/test_dataframe.py::test_reset_index", "dask/dataframe/tests/test_dataframe.py::test_dataframe_compute_forward_kwargs", "dask/dataframe/tests/test_dataframe.py::test_series_iteritems", "dask/dataframe/tests/test_dataframe.py::test_dataframe_iterrows", "dask/dataframe/tests/test_dataframe.py::test_dataframe_itertuples", "dask/dataframe/tests/test_dataframe.py::test_astype", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals", "dask/dataframe/tests/test_dataframe.py::test_astype_categoricals_known", "dask/dataframe/tests/test_dataframe.py::test_groupby_callable", "dask/dataframe/tests/test_dataframe.py::test_methods_tokenize_differently", "dask/dataframe/tests/test_dataframe.py::test_categorize_info", "dask/dataframe/tests/test_dataframe.py::test_gh_1301", "dask/dataframe/tests/test_dataframe.py::test_timeseries_sorted", "dask/dataframe/tests/test_dataframe.py::test_column_assignment", "dask/dataframe/tests/test_dataframe.py::test_columns_assignment", "dask/dataframe/tests/test_dataframe.py::test_attribute_assignment", "dask/dataframe/tests/test_dataframe.py::test_setitem_triggering_realign", "dask/dataframe/tests/test_dataframe.py::test_inplace_operators", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx0-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-True]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin[idx1-False]", "dask/dataframe/tests/test_dataframe.py::test_idxmaxmin_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_getitem_meta", "dask/dataframe/tests/test_dataframe.py::test_getitem_multilevel", "dask/dataframe/tests/test_dataframe.py::test_getitem_string_subclass", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[list]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[array]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Series]", "dask/dataframe/tests/test_dataframe.py::test_getitem_column_types[Index]", "dask/dataframe/tests/test_dataframe.py::test_ipython_completion", "dask/dataframe/tests/test_dataframe.py::test_diff", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[None-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[1-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[5-5-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-2-20]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-1]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-4]", "dask/dataframe/tests/test_dataframe.py::test_hash_split_unique[20-5-20]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_drop_duplicates[2]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[None]", "dask/dataframe/tests/test_dataframe.py::test_split_out_value_counts[2]", "dask/dataframe/tests/test_dataframe.py::test_values", "dask/dataframe/tests/test_dataframe.py::test_copy", "dask/dataframe/tests/test_dataframe.py::test_del", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[True-False]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-True]", "dask/dataframe/tests/test_dataframe.py::test_memory_usage[False-False]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sum]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[mean]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[std]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[var]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[count]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[min]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[max]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmin]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[idxmax]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[prod]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[all]", "dask/dataframe/tests/test_dataframe.py::test_dataframe_reductions_arithmetic[sem]", "dask/dataframe/tests/test_dataframe.py::test_to_datetime", "dask/dataframe/tests/test_dataframe.py::test_to_timedelta", "dask/dataframe/tests/test_dataframe.py::test_isna[values0]", "dask/dataframe/tests/test_dataframe.py::test_isna[values1]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[0]", "dask/dataframe/tests/test_dataframe.py::test_slice_on_filtered_boundary[9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_nonmonotonic", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-False-drop0]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1-None-False-True-drop1]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-False-False-drop2]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3-True-False-drop3]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-False-drop4]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-0.5-None-False-True-drop5]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[-1.5-None-False-True-drop6]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-False-False-drop7]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-3.5-True-False-drop8]", "dask/dataframe/tests/test_dataframe.py::test_with_boundary[None-2.5-False-False-drop9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index0-0-9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index1--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index2-None-10]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index3-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index4--1-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index5-None-2]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index6--2-3]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index7-None-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index8-left8-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index9-None-right9]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index10-left10-None]", "dask/dataframe/tests/test_dataframe.py::test_boundary_slice_same[index11-None-right11]", "dask/dataframe/tests/test_dataframe.py::test_better_errors_object_reductions", "dask/dataframe/tests/test_dataframe.py::test_sample_empty_partitions", "dask/dataframe/tests/test_dataframe.py::test_coerce", "dask/dataframe/tests/test_dataframe.py::test_bool", "dask/dataframe/tests/test_dataframe.py::test_cumulative_multiple_columns", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[asarray]", "dask/dataframe/tests/test_dataframe.py::test_map_partition_array[func1]", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_operations_errors", "dask/dataframe/tests/test_dataframe.py::test_mixed_dask_array_multi_dimensional", "dask/dataframe/tests/test_dataframe.py::test_meta_raises" ]
[]
BSD 3-Clause "New" or "Revised" License
2,992
298
[ "dask/dataframe/categorical.py", "dask/dataframe/core.py" ]
python-pillow__Pillow-3324
5af867df4a7a13a924590af49d24030225b5c93e
2018-08-31 22:27:25
78c8b1f341919a4f7e19e29056713d8f738c9c88
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index fec2f7663..645bb26bf 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -166,6 +166,7 @@ class GifImageFile(ImageFile.ImageFile): from copy import copy self.palette = copy(self.global_palette) + info = {} while True: s = self.fp.read(1) @@ -184,8 +185,8 @@ class GifImageFile(ImageFile.ImageFile): # flags = i8(block[0]) if flags & 1: - self.info["transparency"] = i8(block[3]) - self.info["duration"] = i16(block[1:3]) * 10 + info["transparency"] = i8(block[3]) + info["duration"] = i16(block[1:3]) * 10 # disposal method - find the value of bits 4 - 6 dispose_bits = 0b00011100 & flags @@ -200,16 +201,16 @@ class GifImageFile(ImageFile.ImageFile): # # comment extension # - self.info["comment"] = block + info["comment"] = block elif i8(s) == 255: # # application extension # - self.info["extension"] = block, self.fp.tell() + info["extension"] = block, self.fp.tell() if block[:11] == b"NETSCAPE2.0": block = self.data() if len(block) >= 3 and i8(block[0]) == 1: - self.info["loop"] = i16(block[1:3]) + info["loop"] = i16(block[1:3]) while self.data(): pass @@ -268,6 +269,12 @@ class GifImageFile(ImageFile.ImageFile): # self.__fp = None raise EOFError + for k in ["transparency", "duration", "comment", "extension", "loop"]: + if k in info: + self.info[k] = info[k] + elif k in self.info: + del self.info[k] + self.mode = "L" if self.palette: self.mode = "P"
TypeError: object of type 'NoneType' has no len() ### TypeError: object of type 'NoneType' has no len() This image has a value "comment" is None. It raises that error. This is my PR https://github.com/python-pillow/Pillow/pull/3314 https://github.com/python-pillow/Pillow/blob/master/src/PIL/GifImagePlugin.py#L527 ```python > if "comment" in im.encoderinfo and 1 <= len(im.encoderinfo["comment"]) <= 255: E TypeError: object of type 'NoneType' has no len() ``` https://github.com/python-pillow/Pillow/blob/master/src/PIL/GifImagePlugin.py#L697 ```python def _get_global_header(im, info): """Return a list of strings representing a GIF header""" # Header Block # http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp version = b"87a" for extensionKey in ["transparency", "duration", "loop", "comment"]: if info and extensionKey in info: if ((extensionKey == "duration" and info[extensionKey] == 0) or > (extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255))): E TypeError: object of type 'NoneType' has no len() ``` ```python {'background': 160, 'comment': None, 'duration': 500, 'optimize': True, 'version': b'GIF89a'} ``` This code is reproducing that issue ```python from PIL import Image from io import BytesIO filename = 'test.gif' with open(filename, "rb") as fp: img = Image.open(fp) file_obj = BytesIO() print(img.info) getattr(img, "is_animated", False) print(img.info) img.save(file_obj, format="GIF") ``` ![test2](https://user-images.githubusercontent.com/9821654/44784628-f9408780-ab96-11e8-9e9b-038467b6058a.gif)
python-pillow/Pillow
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 086a0f5d0..917b36905 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -134,13 +134,15 @@ class TestFileGif(PillowTestCase): # Multiframe image im = Image.open("Tests/images/dispose_bgnd.gif") + info = im.info.copy() + out = self.tempfile('temp.gif') im.save(out, save_all=True) reread = Image.open(out) for header in important_headers: self.assertEqual( - im.info[header], + info[header], reread.info[header] ) @@ -207,6 +209,15 @@ class TestFileGif(PillowTestCase): except EOFError: self.assertEqual(framecount, 5) + def test_seek_info(self): + im = Image.open("Tests/images/iss634.gif") + info = im.info.copy() + + im.seek(1) + im.seek(0) + + self.assertEqual(im.info, info) + def test_n_frames(self): for path, n_frames in [ [TEST_GIF, 1],
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
5.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 babel==2.17.0 blessed==1.20.0 build==1.2.2.post1 certifi==2025.1.31 charset-normalizer==3.4.1 check-manifest==0.50 cov-core==1.15.0 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 docutils==0.21.2 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 jarn.viewdoc==2.7 Jinja2==3.1.6 MarkupSafe==3.0.2 olefile==0.47 packaging==24.2 -e git+https://github.com/python-pillow/Pillow.git@5af867df4a7a13a924590af49d24030225b5c93e#egg=Pillow pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 Pygments==2.19.1 pyproject_hooks==1.2.0 pyroma==4.2 pytest==8.3.5 pytest-cov==6.0.0 pytz==2025.2 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 trove-classifiers==2025.3.19.19 urllib3==2.3.0 wcwidth==0.2.13 zipp==3.21.0
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - babel==2.17.0 - blessed==1.20.0 - build==1.2.2.post1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - check-manifest==0.50 - cov-core==1.15.0 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - docutils==0.21.2 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jarn-viewdoc==2.7 - jinja2==3.1.6 - markupsafe==3.0.2 - olefile==0.47 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyproject-hooks==1.2.0 - pyroma==4.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - trove-classifiers==2025.3.19.19 - urllib3==2.3.0 - wcwidth==0.2.13 - zipp==3.21.0 prefix: /opt/conda/envs/Pillow
[ "Tests/test_file_gif.py::TestFileGif::test_seek_info", "Tests/test_file_gif.py::TestFileGif::test_transparent_optimize", "Tests/test_file_gif.py::TestFileGif::test_version" ]
[]
[ "Tests/test_file_gif.py::TestFileGif::test_append_images", "Tests/test_file_gif.py::TestFileGif::test_background", "Tests/test_file_gif.py::TestFileGif::test_bbox", "Tests/test_file_gif.py::TestFileGif::test_comment", "Tests/test_file_gif.py::TestFileGif::test_dispose_background", "Tests/test_file_gif.py::TestFileGif::test_dispose_none", "Tests/test_file_gif.py::TestFileGif::test_dispose_previous", "Tests/test_file_gif.py::TestFileGif::test_duration", "Tests/test_file_gif.py::TestFileGif::test_eoferror", "Tests/test_file_gif.py::TestFileGif::test_getdata", "Tests/test_file_gif.py::TestFileGif::test_headers_saving_for_animated_gifs", "Tests/test_file_gif.py::TestFileGif::test_identical_frames", "Tests/test_file_gif.py::TestFileGif::test_invalid_file", "Tests/test_file_gif.py::TestFileGif::test_iss634", "Tests/test_file_gif.py::TestFileGif::test_lzw_bits", "Tests/test_file_gif.py::TestFileGif::test_multiple_duration", "Tests/test_file_gif.py::TestFileGif::test_n_frames", "Tests/test_file_gif.py::TestFileGif::test_number_of_loops", "Tests/test_file_gif.py::TestFileGif::test_optimize", "Tests/test_file_gif.py::TestFileGif::test_optimize_correctness", "Tests/test_file_gif.py::TestFileGif::test_optimize_full_l", "Tests/test_file_gif.py::TestFileGif::test_palette_434", "Tests/test_file_gif.py::TestFileGif::test_palette_handling", "Tests/test_file_gif.py::TestFileGif::test_palette_save_ImagePalette", "Tests/test_file_gif.py::TestFileGif::test_palette_save_L", "Tests/test_file_gif.py::TestFileGif::test_palette_save_P", "Tests/test_file_gif.py::TestFileGif::test_roundtrip", "Tests/test_file_gif.py::TestFileGif::test_roundtrip2", "Tests/test_file_gif.py::TestFileGif::test_roundtrip_save_all", "Tests/test_file_gif.py::TestFileGif::test_sanity", "Tests/test_file_gif.py::TestFileGif::test_save_I", "Tests/test_file_gif.py::TestFileGif::test_save_dispose", "Tests/test_file_gif.py::TestFileGif::test_seek" ]
[]
MIT-CMU License
3,003
571
[ "src/PIL/GifImagePlugin.py" ]
python-pillow__Pillow-3327
41954f244705b247667f1ea228e932ca6390bcd6
2018-09-01 13:24:45
78c8b1f341919a4f7e19e29056713d8f738c9c88
diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py index 57b6ae2c8..02893e837 100644 --- a/src/PIL/TgaImagePlugin.py +++ b/src/PIL/TgaImagePlugin.py @@ -20,6 +20,8 @@ from . import Image, ImageFile, ImagePalette from ._binary import i8, i16le as i16, o8, o16le as o16 +import warnings + __version__ = "0.3" @@ -53,7 +55,7 @@ class TgaImageFile(ImageFile.ImageFile): # process header s = self.fp.read(18) - idlen = i8(s[0]) + id_len = i8(s[0]) colormaptype = i8(s[1]) imagetype = i8(s[2]) @@ -100,8 +102,8 @@ class TgaImageFile(ImageFile.ImageFile): if imagetype & 8: self.info["compression"] = "tga_rle" - if idlen: - self.info["id_section"] = self.fp.read(idlen) + if id_len: + self.info["id_section"] = self.fp.read(id_len) if colormaptype: # read palette @@ -151,11 +153,23 @@ def _save(im, fp, filename): except KeyError: raise IOError("cannot write mode %s as TGA" % im.mode) - rle = im.encoderinfo.get("rle", False) - + if "rle" in im.encoderinfo: + rle = im.encoderinfo["rle"] + else: + compression = im.encoderinfo.get("compression", + im.info.get("compression")) + rle = compression == "tga_rle" if rle: imagetype += 8 + id_section = im.encoderinfo.get("id_section", + im.info.get("id_section", "")) + id_len = len(id_section) + if id_len > 255: + id_len = 255 + id_section = id_section[:255] + warnings.warn("id_section has been trimmed to 255 characters") + if colormaptype: colormapfirst, colormaplength, colormapentry = 0, 256, 24 else: @@ -166,11 +180,12 @@ def _save(im, fp, filename): else: flags = 0 - orientation = im.info.get("orientation", -1) + orientation = im.encoderinfo.get("orientation", + im.info.get("orientation", -1)) if orientation > 0: flags = flags | 0x20 - fp.write(b"\000" + + fp.write(o8(id_len) + o8(colormaptype) + o8(imagetype) + o16(colormapfirst) + @@ -183,6 +198,9 @@ def _save(im, fp, filename): o8(bits) + o8(flags)) + if id_section: + fp.write(id_section) + if colormaptype: fp.write(im.im.getpalette("RGB", "BGR"))
Sanitize TGA Image.info Currently, the TGA image plugin sets `Image.info` "compression" to "tga_rle" on `load()`, while `save()` takes "rle" (bool) option. Both methods should use the same option for consistency. It probably makes sense to keep "rle" as TGA format doesn't support other compression methods, but "compression" may be more consistent with BMP and TIFF plugins. Neither of the options is documented, so there is no danger of breaking backward compatibility. Also, it's not very clear whether `save()` method should "inherit" info like TIFF and PNG plugins do: https://github.com/python-pillow/Pillow/blob/4407cb65079a7d1150277e3b9a144996f56357c9/src/PIL/TiffImagePlugin.py#L1399-L1400 Currently, TGA plugin only inherits "orientation" but doesn't allow to specify it as a keyword to `save()`, and "id_section" is ignored altogether.
python-pillow/Pillow
diff --git a/Tests/test_file_tga.py b/Tests/test_file_tga.py index 226b899dc..77695f2d1 100644 --- a/Tests/test_file_tga.py +++ b/Tests/test_file_tga.py @@ -53,10 +53,10 @@ class TestFileTga(PillowTestCase): # Generate a new test name every time so the # test will not fail with permission error # on Windows. - test_file = self.tempfile("temp.tga") + out = self.tempfile("temp.tga") - original_im.save(test_file, rle=rle) - saved_im = Image.open(test_file) + original_im.save(out, rle=rle) + saved_im = Image.open(out) if rle: self.assertEqual( saved_im.info["compression"], @@ -95,34 +95,93 @@ class TestFileTga(PillowTestCase): test_file = "Tests/images/tga_id_field.tga" im = Image.open(test_file) - test_file = self.tempfile("temp.tga") + out = self.tempfile("temp.tga") # Save - im.save(test_file) - test_im = Image.open(test_file) + im.save(out) + test_im = Image.open(out) self.assertEqual(test_im.size, (100, 100)) + self.assertEqual(test_im.info["id_section"], im.info["id_section"]) # RGBA save - im.convert("RGBA").save(test_file) - test_im = Image.open(test_file) + im.convert("RGBA").save(out) + test_im = Image.open(out) self.assertEqual(test_im.size, (100, 100)) + def test_save_id_section(self): + test_file = "Tests/images/rgb32rle.tga" + im = Image.open(test_file) + + out = self.tempfile("temp.tga") + + # Check there is no id section + im.save(out) + test_im = Image.open(out) + self.assertNotIn("id_section", test_im.info) + + # Save with custom id section + im.save(out, id_section=b"Test content") + test_im = Image.open(out) + self.assertEqual(test_im.info["id_section"], b"Test content") + + # Save with custom id section greater than 255 characters + id_section = b"Test content" * 25 + self.assert_warning(UserWarning, + lambda: im.save(out, id_section=id_section)) + test_im = Image.open(out) + self.assertEqual(test_im.info["id_section"], id_section[:255]) + + test_file = "Tests/images/tga_id_field.tga" + im = Image.open(test_file) + + # Save with no id section + im.save(out, id_section="") + test_im = Image.open(out) + self.assertNotIn("id_section", test_im.info) + + def test_save_orientation(self): + test_file = "Tests/images/rgb32rle.tga" + im = Image.open(test_file) + self.assertEqual(im.info["orientation"], -1) + + out = self.tempfile("temp.tga") + + im.save(out, orientation=1) + test_im = Image.open(out) + self.assertEqual(test_im.info["orientation"], 1) + def test_save_rle(self): test_file = "Tests/images/rgb32rle.tga" im = Image.open(test_file) + self.assertEqual(im.info["compression"], "tga_rle") - test_file = self.tempfile("temp.tga") + out = self.tempfile("temp.tga") # Save - im.save(test_file) - test_im = Image.open(test_file) + im.save(out) + test_im = Image.open(out) self.assertEqual(test_im.size, (199, 199)) + self.assertEqual(test_im.info["compression"], "tga_rle") + + # Save without compression + im.save(out, compression=None) + test_im = Image.open(out) + self.assertNotIn("compression", test_im.info) # RGBA save - im.convert("RGBA").save(test_file) - test_im = Image.open(test_file) + im.convert("RGBA").save(out) + test_im = Image.open(out) self.assertEqual(test_im.size, (199, 199)) + test_file = "Tests/images/tga_id_field.tga" + im = Image.open(test_file) + self.assertNotIn("compression", im.info) + + # Save with compression + im.save(out, compression="tga_rle") + test_im = Image.open(out) + self.assertEqual(test_im.info["compression"], "tga_rle") + def test_save_l_transparency(self): # There are 559 transparent pixels in la.tga. num_transparent = 559 @@ -133,10 +192,10 @@ class TestFileTga(PillowTestCase): self.assertEqual( im.getchannel("A").getcolors()[0][0], num_transparent) - test_file = self.tempfile("temp.tga") - im.save(test_file) + out = self.tempfile("temp.tga") + im.save(out) - test_im = Image.open(test_file) + test_im = Image.open(out) self.assertEqual(test_im.mode, "LA") self.assertEqual( test_im.getchannel("A").getcolors()[0][0], num_transparent)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
5.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 babel==2.17.0 blessed==1.20.0 build==1.2.2.post1 certifi==2025.1.31 charset-normalizer==3.4.1 check-manifest==0.50 cov-core==1.15.0 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 docutils==0.21.2 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 jarn.viewdoc==2.7 Jinja2==3.1.6 MarkupSafe==3.0.2 olefile==0.47 packaging==24.2 -e git+https://github.com/python-pillow/Pillow.git@41954f244705b247667f1ea228e932ca6390bcd6#egg=Pillow pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 Pygments==2.19.1 pyproject_hooks==1.2.0 pyroma==4.2 pytest==8.3.5 pytest-cov==6.0.0 pytz==2025.2 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 trove-classifiers==2025.3.19.19 urllib3==2.3.0 wcwidth==0.2.13 zipp==3.21.0
name: Pillow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - babel==2.17.0 - blessed==1.20.0 - build==1.2.2.post1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - check-manifest==0.50 - cov-core==1.15.0 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - docutils==0.21.2 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jarn-viewdoc==2.7 - jinja2==3.1.6 - markupsafe==3.0.2 - olefile==0.47 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pygments==2.19.1 - pyproject-hooks==1.2.0 - pyroma==4.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - trove-classifiers==2025.3.19.19 - urllib3==2.3.0 - wcwidth==0.2.13 - zipp==3.21.0 prefix: /opt/conda/envs/Pillow
[ "Tests/test_file_tga.py::TestFileTga::test_save", "Tests/test_file_tga.py::TestFileTga::test_save_id_section", "Tests/test_file_tga.py::TestFileTga::test_save_l_transparency", "Tests/test_file_tga.py::TestFileTga::test_save_orientation", "Tests/test_file_tga.py::TestFileTga::test_save_rle" ]
[]
[ "Tests/test_file_tga.py::TestFileTga::test_id_field", "Tests/test_file_tga.py::TestFileTga::test_id_field_rle", "Tests/test_file_tga.py::TestFileTga::test_sanity" ]
[]
MIT-CMU License
3,004
768
[ "src/PIL/TgaImagePlugin.py" ]
conan-io__conan-3477
82631b05304f07dddfbd9f2cb0721e10fcd43d17
2018-09-04 15:41:29
b02cce4e78d5982e00b66f80a683465b3c679033
diff --git a/conans/model/conan_file.py b/conans/model/conan_file.py index f025e5367..c77ae3263 100644 --- a/conans/model/conan_file.py +++ b/conans/model/conan_file.py @@ -22,13 +22,13 @@ def create_options(conanfile): default_options = getattr(conanfile, "default_options", None) if default_options: - if isinstance(default_options, (list, tuple)): + if isinstance(default_options, (list, tuple, dict)): default_values = OptionsValues(default_options) elif isinstance(default_options, str): default_values = OptionsValues.loads(default_options) else: - raise ConanException("Please define your default_options as list or " - "multiline string") + raise ConanException("Please define your default_options as list, " + "multiline string or dictionary") options.values = default_values return options except Exception as e: diff --git a/conans/model/options.py b/conans/model/options.py index da7cde5b0..51feaa4fb 100644 --- a/conans/model/options.py +++ b/conans/model/options.py @@ -1,8 +1,11 @@ -from conans.util.sha import sha1 -from conans.errors import ConanException + import yaml import six import fnmatch +from collections import Counter + +from conans.util.sha import sha1 +from conans.errors import ConanException _falsey_options = ["false", "none", "0", "off", ""] @@ -162,19 +165,20 @@ class OptionsValues(object): # convert tuple "Pkg:option=value", "..." to list of tuples(name, value) if isinstance(values, tuple): - new_values = [] - for v in values: - option, value = v.split("=", 1) - new_values.append((option.strip(), value.strip())) - values = new_values + values = [item.split("=", 1) for item in values] + + # convert dict {"Pkg:option": "value", "..": "..", ...} to list of tuples (name, value) + if isinstance(values, dict): + values = [(k, v) for k, v in values.items()] # handle list of tuples (name, value) for (k, v) in values: + k = k.strip() + v = v.strip() if isinstance(v, six.string_types) else v tokens = k.split(":") if len(tokens) == 2: package, option = tokens - package_values = self._reqs_options.setdefault(package.strip(), - PackageOptionValues()) + package_values = self._reqs_options.setdefault(package.strip(), PackageOptionValues()) package_values.add_option(option, v) else: self._package_values.add_option(k, v) @@ -264,14 +268,8 @@ class OptionsValues(object): other_option=3 OtherPack:opt3=12.1 """ - result = [] - for line in text.splitlines(): - line = line.strip() - if not line: - continue - name, value = line.split("=", 1) - result.append((name.strip(), value.strip())) - return OptionsValues(result) + options = tuple(line.strip() for line in text.splitlines() if line.strip()) + return OptionsValues(options) @property def sha(self):
Allow specifying default options as a dictionary To help us debug your issue please explain: - [x] I've read the [CONTRIBUTING guide](https://raw.githubusercontent.com/conan-io/conan/develop/.github/CONTRIBUTING.md). - [x] I've specified the Conan version, operating system version and any tool that can be relevant. - [x] I've explained the steps to reproduce the error or the motivation/use case of the question/suggestion. Hello, Looking at the structure of the conanfile.py, I always found it weird why the options were specified as a dictionary, but the default_options as a list of tuples. This is not an issue for packages that have a small amount of options, but it gets ugly for projects with a lot of options. I always end up doing the following: ```python _default_options = { "shared": True, "tools": True, ... } default_options = [(k, str(v)) for k, v in _default_options.items()] ``` In my opinion, it would be a great enhancement if the default_options would allow specifying values as a dictionary and would make the style of the conanfile.py more uniform. Software information: I'm currently using ```Conan version 1.2.0``` on ``` ProductName: Mac OS X ProductVersion: 10.13.3 BuildVersion: 17D102 ``` with ``` Xcode 9.2 Build version 9C40b ``` and ```Python 3.6.4``` installed from brew
conan-io/conan
diff --git a/conans/test/integration/options_test.py b/conans/test/integration/options_test.py index 5ea8211a6..05b59e375 100644 --- a/conans/test/integration/options_test.py +++ b/conans/test/integration/options_test.py @@ -65,6 +65,73 @@ zlib/0.1@lasote/testing conaninfo = load(os.path.join(client.current_folder, CONANINFO)) self.assertNotIn("zlib:shared=True", conaninfo) + def test_default_options(self): + client = TestClient() + conanfile = """ +from conans import ConanFile + +class MyConanFile(ConanFile): + name = "MyConanFile" + version = "1.0" + options = {"config": %s} + default_options = "config%s" + + def configure(self): + if self.options.config: + self.output.info("Boolean evaluation") + if self.options.config is None: + self.output.info("None evaluation") + if self.options.config == "None": + self.output.info("String evaluation") +""" + # Using "ANY" as possible options + client.save({"conanfile.py": conanfile % ("\"ANY\"", "")}) + error = client.run("create . danimtb/testing", ignore_error=True) + self.assertTrue(error) + self.assertIn("Error while initializing options.", client.out) + client.save({"conanfile.py": conanfile % ("\"ANY\"", "=None")}) + client.run("create . danimtb/testing") + self.assertNotIn("Boolean evaluation", client.out) + self.assertNotIn("None evaluation", client.out) + self.assertIn("String evaluation", client.out) + + # Using None as possible options + client.save({"conanfile.py": conanfile % ("[None]", "")}) + error = client.run("create . danimtb/testing", ignore_error=True) + self.assertTrue(error) + self.assertIn("Error while initializing options.", client.out) + client.save({"conanfile.py": conanfile % ("[None]", "=None")}) + client.run("create . danimtb/testing") + self.assertNotIn("Boolean evaluation", client.out) + self.assertNotIn("None evaluation", client.out) + self.assertIn("String evaluation", client.out) + + # Using "None" as possible options + client.save({"conanfile.py": conanfile % ("[\"None\"]", "")}) + error = client.run("create . danimtb/testing", ignore_error=True) + self.assertTrue(error) + self.assertIn("Error while initializing options.", client.out) + client.save({"conanfile.py": conanfile % ("[\"None\"]", "=None")}) + client.run("create . danimtb/testing") + self.assertNotIn("Boolean evaluation", client.out) + self.assertNotIn("None evaluation", client.out) + self.assertIn("String evaluation", client.out) + client.save({"conanfile.py": conanfile % ("[\"None\"]", "=\\\"None\\\"")}) + error = client.run("create . danimtb/testing", ignore_error=True) + self.assertTrue(error) + self.assertIn("'\"None\"' is not a valid 'options.config' value", client.out) + + # Using "ANY" as possible options and "otherstringvalue" as default + client.save({"conanfile.py": conanfile % ("[\"otherstringvalue\"]", "")}) + error = client.run("create . danimtb/testing", ignore_error=True) + self.assertTrue(error) + self.assertIn("Error while initializing options.", client.out) + client.save({"conanfile.py": conanfile % ("\"ANY\"", "=otherstringvalue")}) + client.run("create . danimtb/testing") + self.assertIn("Boolean evaluation", client.out) + self.assertNotIn("None evaluation", client.out) + self.assertNotIn("String evaluation", client.out) + def general_scope_options_test(self): # https://github.com/conan-io/conan/issues/2538 client = TestClient() diff --git a/conans/test/model/options_test.py b/conans/test/model/options_test.py index c672bf204..6b4a24e2d 100644 --- a/conans/test/model/options_test.py +++ b/conans/test/model/options_test.py @@ -1,3 +1,4 @@ +import six import unittest from conans.model.options import OptionsValues, PackageOptions, Options, PackageOptionValues,\ option_undefined_msg @@ -239,6 +240,39 @@ class OptionsValuesTest(unittest.TestCase): option_values = OptionsValues(self.sut.as_list()) self.assertEqual(option_values.dumps(), self.sut.dumps()) + def test_from_dict(self): + options_as_dict = dict([item.split('=') for item in self.sut.dumps().splitlines()]) + option_values = OptionsValues(options_as_dict) + self.assertEqual(option_values.dumps(), self.sut.dumps()) + + def test_consistency(self): + def _check_equal(hs1, hs2, hs3, hs4): + opt_values1 = OptionsValues(hs1) + opt_values2 = OptionsValues(hs2) + opt_values3 = OptionsValues(hs3) + opt_values4 = OptionsValues(hs4) + + self.assertEqual(opt_values1.dumps(), opt_values2.dumps()) + self.assertEqual(opt_values1.dumps(), opt_values3.dumps()) + self.assertEqual(opt_values1.dumps(), opt_values4.dumps()) + + # Check that all possible input options give the same result + _check_equal([('opt', 3)], [('opt', '3'), ], ('opt=3', ), {'opt': 3}) + _check_equal([('opt', True)], [('opt', 'True'), ], ('opt=True', ), {'opt': True}) + _check_equal([('opt', False)], [('opt', 'False'), ], ('opt=False', ), {'opt': False}) + _check_equal([('opt', None)], [('opt', 'None'), ], ('opt=None', ), {'opt': None}) + _check_equal([('opt', 0)], [('opt', '0'), ], ('opt=0', ), {'opt': 0}) + _check_equal([('opt', '')], [('opt', ''), ], ('opt=', ), {'opt': ''}) + + # Check for leading and trailing spaces + _check_equal([(' opt ', 3)], [(' opt ', '3'), ], (' opt =3', ), {' opt ': 3}) + _check_equal([('opt', ' value ')], [('opt', ' value '), ], ('opt= value ', ), + {'opt': ' value '}) + + # This is expected behaviour: + self.assertNotEqual(OptionsValues([('opt', ''), ]).dumps(), + OptionsValues(('opt=""', )).dumps()) + def test_dumps(self): self.assertEqual(self.sut.dumps(), "\n".join(["optimized=3", "static=True", @@ -265,3 +299,34 @@ class OptionsValuesTest(unittest.TestCase): "Poco:new_option=0"])) self.assertEqual(self.sut.sha, "2442d43f1d558621069a15ff5968535f818939b5") + + def test_loads_exceptions(self): + emsg = "not enough values to unpack" if six.PY3 else "need more than 1 value to unpack" + with self.assertRaisesRegexp(ValueError, emsg): + OptionsValues.loads("a=2\nconfig\nb=3") + + with self.assertRaisesRegexp(ValueError, emsg): + OptionsValues.loads("config\na=2\ncommit\nb=3") + + def test_exceptions_empty_value(self): + emsg = "not enough values to unpack" if six.PY3 else "need more than 1 value to unpack" + with self.assertRaisesRegexp(ValueError, emsg): + OptionsValues("a=2\nconfig\nb=3") + + with self.assertRaisesRegexp(ValueError, emsg): + OptionsValues(("a=2", "config")) + + with self.assertRaisesRegexp(ValueError, emsg): + OptionsValues([('a', 2), ('config', ), ]) + + def test_exceptions_repeated_value(self): + try: + OptionsValues.loads("a=2\na=12\nb=3").dumps() + OptionsValues(("a=2", "b=23", "a=12")) + OptionsValues([('a', 2), ('b', True), ('a', '12')]) + except Exception as e: + self.fail("Not expected exception: {}".format(e)) + + def test_package_with_spaces(self): + self.assertEqual(OptionsValues([('pck2:opt', 50), ]).dumps(), + OptionsValues([('pck2 :opt', 50), ]).dumps()) diff --git a/conans/test/model/transitive_reqs_test.py b/conans/test/model/transitive_reqs_test.py index 5ef9a24ea..fb867ce48 100644 --- a/conans/test/model/transitive_reqs_test.py +++ b/conans/test/model/transitive_reqs_test.py @@ -560,6 +560,17 @@ class HelloConan(ConanFile): """ _assert_conanfile(hello_content_tuple) + hello_content_dict = """ +from conans import ConanFile + +class HelloConan(ConanFile): + name = "Hello" + version = "1.2" + requires = "Say/0.1@user/testing" + default_options = {"Say:myoption" : 234, } # To test dict definition +""" + _assert_conanfile(hello_content_dict) + def test_transitive_two_levels_options(self): say_content = """ from conans import ConanFile
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "nose-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@82631b05304f07dddfbd9f2cb0721e10fcd43d17#egg=conan cov-core==1.15.0 coverage==4.2 deprecation==2.0.7 dill==0.3.4 distro==1.1.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 node-semver==0.2.0 nose==1.3.7 nose-cov==1.6 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 Pygments==2.14.0 PyJWT==1.7.1 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 PyYAML==3.13 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - cov-core==1.15.0 - coverage==4.2 - deprecation==2.0.7 - dill==0.3.4 - distro==1.1.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - node-semver==0.2.0 - nose==1.3.7 - nose-cov==1.6 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==3.13 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/model/options_test.py::OptionsValuesTest::test_consistency", "conans/test/model/options_test.py::OptionsValuesTest::test_from_dict", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic_transitive_option" ]
[ "conans/test/integration/options_test.py::OptionsTest::test_default_options" ]
[ "conans/test/model/options_test.py::OptionsTest::test_in", "conans/test/model/options_test.py::OptionsTest::test_int", "conans/test/model/options_test.py::OptionsValuesTest::test_dumps", "conans/test/model/options_test.py::OptionsValuesTest::test_exceptions_empty_value", "conans/test/model/options_test.py::OptionsValuesTest::test_exceptions_repeated_value", "conans/test/model/options_test.py::OptionsValuesTest::test_from_list", "conans/test/model/options_test.py::OptionsValuesTest::test_loads_exceptions", "conans/test/model/options_test.py::OptionsValuesTest::test_package_with_spaces", "conans/test/model/options_test.py::OptionsValuesTest::test_sha_constant", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_basic_option", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_conditional", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_conditional_diamond", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_dep_requires_clear", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_error", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_options_solved", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_conflict_solved", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_no_conflict", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_diamond_no_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_propagate_indirect_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_remove_build_requires", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_remove_two_build_requires", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_simple_override", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_diamond_private", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_pattern_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_private", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_transitive_two_levels_wrong_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_version_requires2_change", "conans/test/model/transitive_reqs_test.py::ConanRequirementsTest::test_version_requires_change", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_avoid_duplicate_expansion", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_conflict_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_options", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_requirements", "conans/test/model/transitive_reqs_test.py::ConanRequirementsOptimizerTest::test_expand_requirements_direct", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_basic", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config_remove", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_config_remove2", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_errors", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_new_configure", "conans/test/model/transitive_reqs_test.py::CoreSettingsTest::test_transitive_two_levels_options" ]
[]
MIT License
3,020
802
[ "conans/model/conan_file.py", "conans/model/options.py" ]
oduwsdl__MementoEmbed-131
dfff20f4d336e76de33851d77c3f4a4af83a5ed2
2018-09-06 20:43:09
dfff20f4d336e76de33851d77c3f4a4af83a5ed2
diff --git a/docs/source/conf.py b/docs/source/conf.py index c7c0614..9892732 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -26,7 +26,7 @@ author = 'Shawn M. Jones' # The short X.Y version version = '' # The full version, including alpha/beta/rc tags -release = '0.2018.09.05.234815' +release = '0.2018.09.06.202242' # -- General configuration --------------------------------------------------- diff --git a/mementoembed/favicon.py b/mementoembed/favicon.py index 60203f0..2d53036 100644 --- a/mementoembed/favicon.py +++ b/mementoembed/favicon.py @@ -52,18 +52,27 @@ def get_favicon_from_html(content): for link in links: - if 'icon' in link['rel']: - favicon_uri = link['href'] - break + try: + if 'icon' in link['rel']: + favicon_uri = link['href'] + break + except KeyError: + module_logger.exception("there was no 'rel' attribute in this link tag: {}".format(link)) + favicon_uri == None # if that fails, try the older, nonstandard relation 'shortcut' if favicon_uri == None: for link in links: - if 'shortcut' in link['rel']: - favicon_uri = link['href'] - break + try: + if 'shortcut' in link['rel']: + favicon_uri = link['href'] + break + except KeyError: + module_logger.exception("there was no 'rel' attribute in this link tag: {}".format(link)) + favicon_uri == None + return favicon_uri diff --git a/mementoembed/version.py b/mementoembed/version.py index 72f9069..d1f031b 100644 --- a/mementoembed/version.py +++ b/mementoembed/version.py @@ -1,3 +1,3 @@ __appname__ = "MementoEmbed" -__appversion__ = '0.2018.09.05.234815' +__appversion__ = '0.2018.09.06.202242' __useragent__ = "{}/{}".format(__appname__, __appversion__)
Exception while searching for favicon MementoEmbed throws an exception for the following URI-M: * http://wayback.archive-it.org/4887/20141104211213/http://time.com/3502740/ebola-virus-1976/ Here is the log entry: ``` [2018-09-06 14:07:36,093 -0600 ] - ERROR - [ /services/product/socialcard/http://wayback.archive-it.org/4887/20141104211213/http://time.com/3502740/ebola-virus-1976/ ]: mementoembed.services.errors - An unforeseen error has occurred Traceback (most recent call last): File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/services/errors.py", line 27, in handle_errors return function_name(urim, preferences) File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/services/product.py", line 77, in generate_socialcard_response original_favicon_uri = s.original_favicon File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/mementosurrogate.py", line 71, in original_favicon return self.originalresource.favicon File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/originalresource.py", line 49, in favicon candidate_favicon = get_favicon_from_html(self.content) File "/Volumes/nerfherder External/Unsynced-Projects/MementoEmbed/mementoembed/favicon.py", line 55, in get_favicon_from_html if 'icon' in link['rel']: File "/Users/smj/.virtualenvs/MementoEmbed-gkunwTeo/lib/python3.7/site-packages/bs4/element.py", line 1071, in __getitem__ return self.attrs[key] KeyError: 'rel' ``` The problem is that the code assumes that all `link` tags in html have a `rel` attribute.
oduwsdl/MementoEmbed
diff --git a/tests/test_archiveresource.py b/tests/test_archiveresource.py index 0be51a5..8c33160 100644 --- a/tests/test_archiveresource.py +++ b/tests/test_archiveresource.py @@ -279,3 +279,52 @@ class TestArchiveResource(unittest.TestCase): x = ArchiveResource(urim, httpcache) self.assertEqual(x.favicon, expected_favicon) + + def test_link_tag_no_rel(self): + + expected_favicon = None + + cachedict = { + "http://myarchive.org": + mock_response( + headers={}, + content="""<html> + <head> + <title>Is this a good title?</title> + <link title="a good title" href="content/favicon.ico"> + </head> + <body>Is this all there is to content?</body> + </html>""", + status=200, + url = "testing-url://notused" + ), + expected_favicon: + mock_response( + headers = { 'content-type': 'image/x-testing'}, + content = "a", + status=200, + url = "testing-url://notused" + ), + "http://myarchive.org/favicon.ico": + mock_response( + headers={}, + content="not found", + status=404, + url="testing-url://notused" + ), + "https://www.google.com/s2/favicons?domain=myarchive.org": + mock_response( + headers={}, + content="not found", + status=404, + url="testing-url://notused" + ) + } + + httpcache = mock_httpcache(cachedict) + + urim = "http://myarchive.org/20160518000858/http://example.com/somecontent" + + x = ArchiveResource(urim, httpcache) + + self.assertEqual(x.favicon, expected_favicon)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 3 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "numpy>=1.16.0", "pandas>=1.0.0" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiu==0.2.4 async-timeout==5.0.1 beautifulsoup4==4.13.3 blinker==1.9.0 bs4==0.0.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 cssselect==1.3.0 dicttoxml==1.7.16 exceptiongroup==1.2.2 filelock==3.18.0 Flask==3.1.0 html5lib==1.1 htmlmin==0.1.12 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 itsdangerous==2.2.0 Jinja2==3.1.6 jusText==3.0.2 lxml==5.3.1 lxml_html_clean==0.4.1 MarkupSafe==3.0.2 -e git+https://github.com/oduwsdl/MementoEmbed.git@dfff20f4d336e76de33851d77c3f4a4af83a5ed2#egg=mementoembed numpy==2.0.2 packaging==24.2 pandas==2.2.3 pillow==11.1.0 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 readability-lxml==0.8.1 redis==5.2.1 requests==2.32.3 requests-cache==0.5.2 requests-file==2.1.0 requests-futures==1.0.2 six==1.17.0 soupsieve==2.6 tldextract==5.1.3 tomli==2.2.1 typing_extensions==4.13.0 tzdata==2025.2 urllib3==2.3.0 warcio==1.7.5 webencodings==0.5.1 Werkzeug==3.1.3 zipp==3.21.0
name: MementoEmbed channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiu==0.2.4 - async-timeout==5.0.1 - beautifulsoup4==4.13.3 - blinker==1.9.0 - bs4==0.0.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - cssselect==1.3.0 - dicttoxml==1.7.16 - exceptiongroup==1.2.2 - filelock==3.18.0 - flask==3.1.0 - html5lib==1.1 - htmlmin==0.1.12 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - itsdangerous==2.2.0 - jinja2==3.1.6 - justext==3.0.2 - lxml==5.3.1 - lxml-html-clean==0.4.1 - markupsafe==3.0.2 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pillow==11.1.0 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - readability-lxml==0.8.1 - redis==5.2.1 - requests==2.32.3 - requests-cache==0.5.2 - requests-file==2.1.0 - requests-futures==1.0.2 - six==1.17.0 - soupsieve==2.6 - tldextract==5.1.3 - tomli==2.2.1 - typing-extensions==4.13.0 - tzdata==2025.2 - urllib3==2.3.0 - warcio==1.7.5 - webencodings==0.5.1 - werkzeug==3.1.3 - zipp==3.21.0 prefix: /opt/conda/envs/MementoEmbed
[ "tests/test_archiveresource.py::TestArchiveResource::test_link_tag_no_rel" ]
[]
[ "tests/test_archiveresource.py::TestArchiveResource::test_404_favicon_from_constructed_favicon_uri_so_google_service", "tests/test_archiveresource.py::TestArchiveResource::test_404_favicon_from_html_so_constructed_favicon_uri", "tests/test_archiveresource.py::TestArchiveResource::test_collection_data_extraction", "tests/test_archiveresource.py::TestArchiveResource::test_favicon_from_html", "tests/test_archiveresource.py::TestArchiveResource::test_favicon_from_html_relative_uri", "tests/test_archiveresource.py::TestArchiveResource::test_no_good_favicon", "tests/test_archiveresource.py::TestArchiveResource::test_simplestuff" ]
[]
MIT License
3,032
594
[ "docs/source/conf.py", "mementoembed/favicon.py", "mementoembed/version.py" ]
horejsek__python-fastjsonschema-24
dc3ae94332ce901181120db8a2f9f8b6d5339622
2018-09-12 12:06:19
97d45db2d13c3a769d9805cca2a672643b17bb6b
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])\.)*'
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.)
horejsek/python-fastjsonschema
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)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[devel]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-benchmark", "pytest-cache" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 attrs==25.3.0 certifi==2025.1.31 charset-normalizer==3.4.1 colorama==0.4.6 dill==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 -e git+https://github.com/horejsek/python-fastjsonschema.git@dc3ae94332ce901181120db8a2f9f8b6d5339622#egg=fastjsonschema idna==3.10 iniconfig==2.1.0 isort==6.0.1 json-spec==0.10.1 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 mccabe==0.7.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 py-cpuinfo==9.0.0 pylint==3.3.6 pytest==8.3.5 pytest-benchmark==5.1.0 pytest-cache==1.0 referencing==0.36.2 requests==2.32.3 rpds-py==0.24.0 six==1.17.0 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 urllib3==2.3.0 validictory==1.1.3
name: python-fastjsonschema channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - attrs==25.3.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - colorama==0.4.6 - dill==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - isort==6.0.1 - json-spec==0.10.1 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - mccabe==0.7.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pylint==3.3.6 - pytest==8.3.5 - pytest-benchmark==5.1.0 - pytest-cache==1.0 - referencing==0.36.2 - requests==2.32.3 - rpds-py==0.24.0 - six==1.17.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - urllib3==2.3.0 - validictory==1.1.3 prefix: /opt/conda/envs/python-fastjsonschema
[ "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]" ]
[]
BSD 3-Clause "New" or "Revised" License
3,055
321
[ "fastjsonschema/draft04.py" ]
horejsek__python-fastjsonschema-25
97d45db2d13c3a769d9805cca2a672643b17bb6b
2018-09-12 12:38:34
97d45db2d13c3a769d9805cca2a672643b17bb6b
diff --git a/fastjsonschema/draft04.py b/fastjsonschema/draft04.py index 6d79a1e..3ee257b 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])\.)*' 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',
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`
horejsek/python-fastjsonschema
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 diff --git a/tests/test_datetime.py b/tests/test_datetime.py deleted file mode 100644 index 2263e9f..0000000 --- a/tests/test_datetime.py +++ /dev/null @@ -1,15 +0,0 @@ - -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)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 2 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[devel]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-benchmark", "pytest-cache" ], "pre_install": [ "apt-get update", "apt-get install -y gcc", "git submodule init", "git submodule update" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 attrs==25.3.0 certifi==2025.1.31 charset-normalizer==3.4.1 colorama==0.4.6 dill==0.3.9 exceptiongroup==1.2.2 execnet==2.1.1 -e git+https://github.com/horejsek/python-fastjsonschema.git@97d45db2d13c3a769d9805cca2a672643b17bb6b#egg=fastjsonschema idna==3.10 iniconfig==2.1.0 isort==6.0.1 json-spec==0.10.1 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 mccabe==0.7.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 py-cpuinfo==9.0.0 pylint==3.3.6 pytest==8.3.5 pytest-benchmark==5.1.0 pytest-cache==1.0 referencing==0.36.2 requests==2.32.3 rpds-py==0.24.0 six==1.17.0 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0 urllib3==2.3.0 validictory==1.1.3
name: python-fastjsonschema channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - attrs==25.3.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - colorama==0.4.6 - dill==0.3.9 - exceptiongroup==1.2.2 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - isort==6.0.1 - json-spec==0.10.1 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - mccabe==0.7.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pylint==3.3.6 - pytest==8.3.5 - pytest-benchmark==5.1.0 - pytest-cache==1.0 - referencing==0.36.2 - requests==2.32.3 - rpds-py==0.24.0 - six==1.17.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 - urllib3==2.3.0 - validictory==1.1.3 prefix: /opt/conda/envs/python-fastjsonschema
[ "tests/test_compile_to_code.py::test_compile_to_code_ipv6_regex" ]
[]
[ "tests/test_compile_to_code.py::test_compile_to_code" ]
[]
BSD 3-Clause "New" or "Revised" License
3,056
479
[ "fastjsonschema/draft04.py", "fastjsonschema/generator.py" ]
capitalone__datacompy-30
e406940f0c4b9acc6284ab27dcaecd96b857ae83
2018-09-12 19:37:53
246aad8c381f7591512f6ecef9debf6341261578
diff --git a/datacompy/core.py b/datacompy/core.py index c6553f8..e39fa5e 100644 --- a/datacompy/core.py +++ b/datacompy/core.py @@ -62,6 +62,8 @@ class Compare(object): A string name for the second dataframe ignore_spaces : bool, optional Flag to strip whitespace (including newlines) from string columns + ignore_case : bool, optional + Flag to ignore the case of string columns Attributes ---------- @@ -82,6 +84,7 @@ class Compare(object): df1_name="df1", df2_name="df2", ignore_spaces=False, + ignore_case=False, ): if on_index and join_columns is not None: @@ -105,7 +108,7 @@ class Compare(object): self.rel_tol = rel_tol self.df1_unq_rows = self.df2_unq_rows = self.intersect_rows = None self.column_stats = [] - self._compare(ignore_spaces) + self._compare(ignore_spaces, ignore_case) @property def df1(self): @@ -154,7 +157,7 @@ class Compare(object): if len(dataframe.drop_duplicates(subset=self.join_columns)) < len(dataframe): self._any_dupes = True - def _compare(self, ignore_spaces): + def _compare(self, ignore_spaces, ignore_case): """Actually run the comparison. This tries to run df1.equals(df2) first so that if they're truly equal we can tell. @@ -176,7 +179,7 @@ class Compare(object): LOG.info("Number of columns in df2 and not in df1: {}".format(len(self.df2_unq_columns()))) LOG.debug("Merging dataframes") self._dataframe_merge(ignore_spaces) - self._intersect_compare(ignore_spaces) + self._intersect_compare(ignore_spaces, ignore_case) if self.matches(): LOG.info("df1 matches df2") else: @@ -270,7 +273,7 @@ class Compare(object): ) ) - def _intersect_compare(self, ignore_spaces): + def _intersect_compare(self, ignore_spaces, ignore_case): """Run the comparison on the intersect dataframe This loops through all columns that are shared between df1 and df2, and @@ -295,6 +298,7 @@ class Compare(object): self.rel_tol, self.abs_tol, ignore_spaces, + ignore_case, ) match_cnt = self.intersect_rows[col_match].sum() max_diff = calculate_max_diff( @@ -585,7 +589,7 @@ def render(filename, *fields): return file_open.read().format(*fields) -def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0, ignore_spaces=False): +def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0, ignore_spaces=False, ignore_case=False): """Compares two columns from a dataframe, returning a True/False series, with the same index as column 1. @@ -609,6 +613,8 @@ def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0, ignore_spaces=False): Absolute tolerance ignore_spaces : bool, optional Flag to strip whitespace (including newlines) from string columns + ignore_case : bool, optional + Flag to ignore the case of string columns Returns ------- @@ -637,6 +643,12 @@ def columns_equal(col_1, col_2, rel_tol=0, abs_tol=0, ignore_spaces=False): if col_2.dtype.kind == "O": col_2 = col_2.str.strip() + if ignore_case: + if col_1.dtype.kind == "O": + col_1 = col_1.str.upper() + if col_2.dtype.kind == "O": + col_2 = col_2.str.upper() + if set([col_1.dtype.kind, col_2.dtype.kind]) == set(["M", "O"]): compare = compare_string_and_date_columns(col_1, col_2) else:
Ignore case when comparing strings Might be a nice to have a optional ignore case feature so that `STRING` == `string`. Should be relatively simple to add. Happy to take it on. @theianrobertson thoughts?
capitalone/datacompy
diff --git a/tests/test_core.py b/tests/test_core.py index 3251d37..7e37ac4 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -108,6 +108,28 @@ something||False assert_series_equal(expect_out, actual_out, check_names=False) +def test_string_columns_equal_with_ignore_spaces_and_case(): + data = """a|b|expected +Hi|Hi|True +Yo|Yo|True +Hey|Hey |True +résumé|resume|False +résumé|résumé|True +💩|💩|True +💩|🤔|False + | |True + | |True +datacompy|DataComPy|True +something||False +|something|False +||True""" + df = pd.read_csv(six.StringIO(data), sep="|") + actual_out = datacompy.columns_equal(df.a, df.b, rel_tol=0.2, ignore_spaces=True, + ignore_case=True) + expect_out = df["expected"] + assert_series_equal(expect_out, actual_out, check_names=False) + + def test_date_columns_equal(): data = """a|b|expected 2017-01-01|2017-01-01|True @@ -158,6 +180,32 @@ def test_date_columns_equal_with_ignore_spaces(): assert_series_equal(expect_out, actual_out_rev, check_names=False) +def test_date_columns_equal_with_ignore_spaces_and_case(): + data = """a|b|expected +2017-01-01|2017-01-01 |True +2017-01-02 |2017-01-02|True +2017-10-01 |2017-10-10 |False +2017-01-01||False +|2017-01-01|False +||True""" + df = pd.read_csv(six.StringIO(data), sep="|") + # First compare just the strings + actual_out = datacompy.columns_equal(df.a, df.b, rel_tol=0.2, ignore_spaces=True, + ignore_case=True) + expect_out = df["expected"] + assert_series_equal(expect_out, actual_out, check_names=False) + + # Then compare converted to datetime objects + df["a"] = pd.to_datetime(df["a"]) + df["b"] = pd.to_datetime(df["b"]) + actual_out = datacompy.columns_equal(df.a, df.b, rel_tol=0.2, ignore_spaces=True) + expect_out = df["expected"] + assert_series_equal(expect_out, actual_out, check_names=False) + # and reverse + actual_out_rev = datacompy.columns_equal(df.b, df.a, rel_tol=0.2, ignore_spaces=True) + assert_series_equal(expect_out, actual_out_rev, check_names=False) + + def test_date_columns_unequal(): """I want datetime fields to match with dates stored as strings """ @@ -323,6 +371,25 @@ def test_mixed_column_with_ignore_spaces(): assert_series_equal(expect_out, actual_out, check_names=False) +def test_mixed_column_with_ignore_spaces_and_case(): + df = pd.DataFrame( + [ + {"a": "hi", "b": "hi ", "expected": True}, + {"a": 1, "b": 1, "expected": True}, + {"a": np.inf, "b": np.inf, "expected": True}, + {"a": Decimal("1"), "b": Decimal("1"), "expected": True}, + {"a": 1, "b": "1 ", "expected": False}, + {"a": 1, "b": "yo ", "expected": False}, + {"a": "Hi", "b": "hI ", "expected": True}, + {"a": "HI", "b": "HI ", "expected": True}, + {"a": "hi", "b": "hi ", "expected": True}, + ] + ) + actual_out = datacompy.columns_equal(df.a, df.b, ignore_spaces=True, ignore_case=True) + expect_out = df["expected"] + assert_series_equal(expect_out, actual_out, check_names=False) + + def test_compare_df_setter_bad(): df = pd.DataFrame([{"a": 1, "A": 2}, {"a": 2, "A": 2}]) with raises(TypeError, message="df1 must be a pandas DataFrame"): @@ -668,6 +735,23 @@ def test_strings_with_joins_with_ignore_spaces(): assert compare.intersect_rows_match() + +def test_strings_with_joins_with_ignore_case(): + df1 = pd.DataFrame([{"a": "hi", "b": "a"}, {"a": "bye", "b": "A"}]) + df2 = pd.DataFrame([{"a": "hi", "b": "A"}, {"a": "bye", "b": "a"}]) + compare = datacompy.Compare(df1, df2, "a", ignore_case=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, "a", ignore_case=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match() + + def test_decimal_with_joins_with_ignore_spaces(): df1 = pd.DataFrame([{"a": 1, "b": " A"}, {"a": 2, "b": "A"}]) df2 = pd.DataFrame([{"a": 1, "b": "A"}, {"a": 2, "b": "A "}]) @@ -684,6 +768,22 @@ def test_decimal_with_joins_with_ignore_spaces(): assert compare.intersect_rows_match() +def test_decimal_with_joins_with_ignore_case(): + df1 = pd.DataFrame([{"a": 1, "b": "a"}, {"a": 2, "b": "A"}]) + df2 = pd.DataFrame([{"a": 1, "b": "A"}, {"a": 2, "b": "a"}]) + compare = datacompy.Compare(df1, df2, "a", ignore_case=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, "a", ignore_case=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match() + + def test_index_with_joins_with_ignore_spaces(): df1 = pd.DataFrame([{"a": 1, "b": " A"}, {"a": 2, "b": "A"}]) df2 = pd.DataFrame([{"a": 1, "b": "A"}, {"a": 2, "b": "A "}]) @@ -700,6 +800,22 @@ def test_index_with_joins_with_ignore_spaces(): assert compare.intersect_rows_match() +def test_index_with_joins_with_ignore_case(): + df1 = pd.DataFrame([{"a": 1, "b": "a"}, {"a": 2, "b": "A"}]) + df2 = pd.DataFrame([{"a": 1, "b": "A"}, {"a": 2, "b": "a"}]) + compare = datacompy.Compare(df1, df2, on_index=True, ignore_case=False) + assert not compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert not compare.intersect_rows_match() + + compare = datacompy.Compare(df1, df2, "a", ignore_case=True) + assert compare.matches() + assert compare.all_columns_match() + assert compare.all_rows_overlap() + assert compare.intersect_rows_match() + + MAX_DIFF_DF = pd.DataFrame( { "base": [1, 1, 1, 1, 1],
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=3.0.6", "Sphinx>=1.6.2", "sphinx-rtd-theme>=0.2.4", "numpydoc>=0.6.0", "mock>=2.0.0", "pre-commit>=1.10.4", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 cfgv==3.3.1 charset-normalizer==2.0.12 -e git+https://github.com/capitalone/datacompy.git@e406940f0c4b9acc6284ab27dcaecd96b857ae83#egg=datacompy distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 identify==2.4.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.2.3 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 nodeenv==1.6.0 numpy==1.19.5 numpydoc==1.1.0 packaging==21.3 pandas==0.23.3 platformdirs==2.4.0 pluggy==1.0.0 pre-commit==2.17.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 toml==0.10.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 zipp==3.6.0
name: datacompy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - cfgv==3.3.1 - charset-normalizer==2.0.12 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - identify==2.4.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.2.3 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - nodeenv==1.6.0 - numpy==1.19.5 - numpydoc==1.1.0 - packaging==21.3 - pandas==0.23.3 - platformdirs==2.4.0 - pluggy==1.0.0 - pre-commit==2.17.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - toml==0.10.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - zipp==3.6.0 prefix: /opt/conda/envs/datacompy
[ "tests/test_core.py::test_string_columns_equal_with_ignore_spaces_and_case", "tests/test_core.py::test_date_columns_equal_with_ignore_spaces_and_case", "tests/test_core.py::test_mixed_column_with_ignore_spaces_and_case", "tests/test_core.py::test_strings_with_joins_with_ignore_case", "tests/test_core.py::test_decimal_with_joins_with_ignore_case", "tests/test_core.py::test_index_with_joins_with_ignore_case" ]
[ "tests/test_core.py::test_compare_df_setter_bad", "tests/test_core.py::test_compare_df_setter_bad_index", "tests/test_core.py::test_compare_on_index_and_join_columns" ]
[ "tests/test_core.py::test_numeric_columns_equal_abs", "tests/test_core.py::test_numeric_columns_equal_rel", "tests/test_core.py::test_string_columns_equal", "tests/test_core.py::test_string_columns_equal_with_ignore_spaces", "tests/test_core.py::test_date_columns_equal", "tests/test_core.py::test_date_columns_equal_with_ignore_spaces", "tests/test_core.py::test_date_columns_unequal", "tests/test_core.py::test_bad_date_columns", "tests/test_core.py::test_rounded_date_columns", "tests/test_core.py::test_decimal_float_columns_equal", "tests/test_core.py::test_decimal_float_columns_equal_rel", "tests/test_core.py::test_decimal_columns_equal", "tests/test_core.py::test_decimal_columns_equal_rel", "tests/test_core.py::test_infinity_and_beyond", "tests/test_core.py::test_mixed_column", "tests/test_core.py::test_mixed_column_with_ignore_spaces", "tests/test_core.py::test_compare_df_setter_good", "tests/test_core.py::test_compare_df_setter_different_cases", "tests/test_core.py::test_compare_df_setter_good_index", "tests/test_core.py::test_columns_overlap", "tests/test_core.py::test_columns_no_overlap", "tests/test_core.py::test_10k_rows", "tests/test_core.py::test_subset", "tests/test_core.py::test_not_subset", "tests/test_core.py::test_large_subset", "tests/test_core.py::test_string_joiner", "tests/test_core.py::test_decimal_with_joins", "tests/test_core.py::test_decimal_with_nulls", "tests/test_core.py::test_strings_with_joins", "tests/test_core.py::test_index_joining", "tests/test_core.py::test_index_joining_strings_i_guess", "tests/test_core.py::test_index_joining_non_overlapping", "tests/test_core.py::test_temp_column_name", "tests/test_core.py::test_temp_column_name_one_has", "tests/test_core.py::test_temp_column_name_both_have", "tests/test_core.py::test_temp_column_name_one_already", "tests/test_core.py::test_simple_dupes_one_field", "tests/test_core.py::test_simple_dupes_two_fields", "tests/test_core.py::test_simple_dupes_index", "tests/test_core.py::test_simple_dupes_one_field_two_vals", "tests/test_core.py::test_simple_dupes_one_field_three_to_two_vals", "tests/test_core.py::test_dupes_from_real_data", "tests/test_core.py::test_strings_with_joins_with_ignore_spaces", "tests/test_core.py::test_decimal_with_joins_with_ignore_spaces", "tests/test_core.py::test_index_with_joins_with_ignore_spaces", "tests/test_core.py::test_calculate_max_diff[base-0]", "tests/test_core.py::test_calculate_max_diff[floats-0.2]", "tests/test_core.py::test_calculate_max_diff[decimals-0.1]", "tests/test_core.py::test_calculate_max_diff[null_floats-0.1]", "tests/test_core.py::test_calculate_max_diff[strings-0.1]", "tests/test_core.py::test_calculate_max_diff[mixed_strings-0]", "tests/test_core.py::test_calculate_max_diff[infinity-inf]" ]
[]
Apache License 2.0
3,061
972
[ "datacompy/core.py" ]
google__importlab-23
77f04151272440dacea197b8c4f74aa26fdbe950
2018-09-12 22:25:03
676d17cd41ac68de6ebb48fb71780ad6110c4ae3
diff --git a/importlab/resolve.py b/importlab/resolve.py index 23314bc..d55f34d 100644 --- a/importlab/resolve.py +++ b/importlab/resolve.py @@ -102,6 +102,9 @@ def infer_module_name(filename, fspath): for f in fspath: short_name = f.relative_path(filename) if short_name: + # The module name for __init__.py files is the directory. + if short_name.endswith(os.path.sep + "__init__"): + short_name = short_name[:short_name.rfind(os.path.sep)] return short_name.replace(os.path.sep, '.') # We have not found filename relative to anywhere in pythonpath. return ''
Incorrect inferred module name for __init__.py files See google/pytype#154 for more detail. `resolve.infer_module_name` calculates the wrong name for `__init__.py` files. For example, for `foo/bar/__init__.py`, it will return `foo.bar.__init__`. The module name should be `foo.bar`.
google/importlab
diff --git a/tests/test_resolve.py b/tests/test_resolve.py index 2a217d3..9891764 100644 --- a/tests/test_resolve.py +++ b/tests/test_resolve.py @@ -293,6 +293,15 @@ class TestResolverUtils(unittest.TestCase): resolve.infer_module_name("/some/random/file", fspath), "") + def testInferInitModuleName(self): + with utils.Tempdir() as d: + os_fs = fs.OSFileSystem(d.path) + fspath = [os_fs] + py_file = d.create_file("foo/__init__.py") + self.assertEqual( + resolve.infer_module_name(py_file, fspath), + "foo") + def testGetAbsoluteName(self): test_cases = [ ("x.y", "a.b", "x.y.a.b"),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 decorator==4.4.2 -e git+https://github.com/google/importlab.git@77f04151272440dacea197b8c4f74aa26fdbe950#egg=importlab importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work networkx==2.5.1 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: importlab channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - decorator==4.4.2 - networkx==2.5.1 - six==1.17.0 prefix: /opt/conda/envs/importlab
[ "tests/test_resolve.py::TestResolverUtils::testInferInitModuleName" ]
[]
[ "tests/test_resolve.py::TestResolver::testFallBackToSource", "tests/test_resolve.py::TestResolver::testGetPyFromPycSource", "tests/test_resolve.py::TestResolver::testOverrideSource", "tests/test_resolve.py::TestResolver::testPycSourceWithoutPy", "tests/test_resolve.py::TestResolver::testResolveBuiltin", "tests/test_resolve.py::TestResolver::testResolveInitFile", "tests/test_resolve.py::TestResolver::testResolveInitFileRelative", "tests/test_resolve.py::TestResolver::testResolveModuleFromFile", "tests/test_resolve.py::TestResolver::testResolvePackageFile", "tests/test_resolve.py::TestResolver::testResolveParentPackageFile", "tests/test_resolve.py::TestResolver::testResolveParentPackageFileWithModule", "tests/test_resolve.py::TestResolver::testResolvePyiFile", "tests/test_resolve.py::TestResolver::testResolveRelativeFromInitFileWithModule", "tests/test_resolve.py::TestResolver::testResolveRelativeInNonPackage", "tests/test_resolve.py::TestResolver::testResolveSamePackageFile", "tests/test_resolve.py::TestResolver::testResolveSiblingPackageFile", "tests/test_resolve.py::TestResolver::testResolveStarImport", "tests/test_resolve.py::TestResolver::testResolveStarImportBuiltin", "tests/test_resolve.py::TestResolver::testResolveStarImportSystem", "tests/test_resolve.py::TestResolver::testResolveSymbolFromFile", "tests/test_resolve.py::TestResolver::testResolveSystemInitFile", "tests/test_resolve.py::TestResolver::testResolveSystemPackageDir", "tests/test_resolve.py::TestResolver::testResolveSystemRelative", "tests/test_resolve.py::TestResolver::testResolveSystemSymbol", "tests/test_resolve.py::TestResolver::testResolveSystemSymbolNameClash", "tests/test_resolve.py::TestResolver::testResolveTopLevel", "tests/test_resolve.py::TestResolver::testResolveWithFilesystem", "tests/test_resolve.py::TestResolverUtils::testGetAbsoluteName", "tests/test_resolve.py::TestResolverUtils::testInferModuleName" ]
[]
Apache License 2.0
3,062
174
[ "importlab/resolve.py" ]
kutaslab__fitgrid-23
1cba86280c45b7a5f1422621167aeee1952a2254
2018-09-15 23:56:13
fa73573d86934c0d22d09eb0b0af1d0849218ff6
diff --git a/fitgrid/epochs.py b/fitgrid/epochs.py index 1b09227..b14ad8a 100644 --- a/fitgrid/epochs.py +++ b/fitgrid/epochs.py @@ -41,12 +41,13 @@ class Epochs: levels_to_remove = set(epochs_table.index.names) levels_to_remove.discard(EPOCH_ID) - # so we remove all levels from index except EPOCH_ID - epochs_table.reset_index(list(levels_to_remove), inplace=True) - assert epochs_table.index.names == [EPOCH_ID] + # copy since we are about to modify + self.table = epochs_table.copy() + # remove all levels from index except EPOCH_ID + self.table.reset_index(list(levels_to_remove), inplace=True) + assert self.table.index.names == [EPOCH_ID] - self.table = epochs_table - snapshots = epochs_table.groupby(TIME) + snapshots = self.table.groupby(TIME) # check that snapshots across epochs have equal index by transitivity prev_group = None @@ -66,10 +67,13 @@ class Epochs: if not prev_group.index.is_unique: raise FitGridError( f'Duplicate values in {EPOCH_ID} index not allowed:', - tools.get_index_duplicates_table(epochs_table, EPOCH_ID), + tools.get_index_duplicates_table(self.table, EPOCH_ID), ) - # we're good, set instance variable + self.table.reset_index(inplace=True) + self.table.set_index([EPOCH_ID, TIME], inplace=True) + assert self.table.index.names == [EPOCH_ID, TIME] + self.snapshots = snapshots def lm(self, LHS='default', RHS=None):
Set epochs table index to EPOCH_ID and TIME during Epochs creation In `__init__` we reset the index to only keep `EPOCH_ID`. After `snapshots` are created, set index to `EPOCH_ID`, `TIME`. This is needed for plotting of individual epochs.
kutaslab/fitgrid
diff --git a/tests/test_epochs.py b/tests/test_epochs.py index 736db4b..a92bf85 100644 --- a/tests/test_epochs.py +++ b/tests/test_epochs.py @@ -2,7 +2,8 @@ import pytest import numpy as np from .context import fitgrid -from fitgrid import fake_data, epochs, errors +from fitgrid import fake_data, errors +from fitgrid.epochs import Epochs def test_epochs_unequal_snapshots(): @@ -13,7 +14,7 @@ def test_epochs_unequal_snapshots(): epochs_table.drop(epochs_table.index[42], inplace=True) with pytest.raises(errors.FitGridError) as error: - epochs.Epochs(epochs_table) + Epochs(epochs_table) assert 'differs from previous snapshot' in str(error.value) @@ -34,6 +35,23 @@ def test__raises_error_on_epoch_index_mismatch(): # now time index is equal to row number in the table overall with pytest.raises(errors.FitGridError) as error: - epochs.Epochs(epochs_table) + Epochs(epochs_table) assert 'differs from previous snapshot' in str(error.value) + + +def test_multiple_indices_end_up_EPOCH_ID_and_TIME(): + + from fitgrid import EPOCH_ID, TIME + + epochs_table = fake_data._generate( + n_epochs=10, n_samples=100, n_categories=2, n_channels=32 + ) + epochs_table.reset_index(inplace=True) + epochs_table.set_index([EPOCH_ID, TIME, 'categorical'], inplace=True) + + epochs = Epochs(epochs_table) + # internal table has EPOCH_ID and TIME in index + assert epochs.table.index.names == [EPOCH_ID, TIME] + # input table is not altered + assert epochs_table.index.names == [EPOCH_ID, TIME, 'categorical']
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
blosc2==2.5.1 contourpy==1.3.0 cycler==0.12.1 exceptiongroup==1.2.2 -e git+https://github.com/kutaslab/fitgrid.git@1cba86280c45b7a5f1422621167aeee1952a2254#egg=fitgrid fonttools==4.56.0 importlib_resources==6.5.2 iniconfig==2.1.0 kiwisolver==1.4.7 matplotlib==3.9.4 msgpack==1.1.0 ndindex==1.9.2 numexpr==2.10.2 numpy==2.0.2 packaging==24.2 pandas==2.2.3 patsy==1.0.1 pillow==11.1.0 pluggy==1.5.0 py-cpuinfo==9.0.0 pyparsing==3.2.3 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 scipy==1.13.1 six==1.17.0 statsmodels==0.14.4 tables==3.9.2 tomli==2.2.1 tqdm==4.67.1 tzdata==2025.2 zipp==3.21.0
name: fitgrid channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - blosc2==2.5.1 - contourpy==1.3.0 - cycler==0.12.1 - exceptiongroup==1.2.2 - fonttools==4.56.0 - importlib-resources==6.5.2 - iniconfig==2.1.0 - kiwisolver==1.4.7 - matplotlib==3.9.4 - msgpack==1.1.0 - ndindex==1.9.2 - numexpr==2.10.2 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - patsy==1.0.1 - pillow==11.1.0 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pyparsing==3.2.3 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - scipy==1.13.1 - six==1.17.0 - statsmodels==0.14.4 - tables==3.9.2 - tomli==2.2.1 - tqdm==4.67.1 - tzdata==2025.2 - zipp==3.21.0 prefix: /opt/conda/envs/fitgrid
[ "tests/test_epochs.py::test_multiple_indices_end_up_EPOCH_ID_and_TIME" ]
[ "tests/test_epochs.py::test__raises_error_on_epoch_index_mismatch" ]
[ "tests/test_epochs.py::test_epochs_unequal_snapshots" ]
[]
BSD 3-Clause "New" or "Revised" License
3,078
405
[ "fitgrid/epochs.py" ]
conan-io__conan-3560
bb404b34bc894032ac4c56ac03d2cf3e6a7ef3e9
2018-09-17 09:34:00
b02cce4e78d5982e00b66f80a683465b3c679033
diff --git a/conans/client/graph/graph.py b/conans/client/graph/graph.py index dabc5ff3e..16570b31c 100644 --- a/conans/client/graph/graph.py +++ b/conans/client/graph/graph.py @@ -275,7 +275,7 @@ class DepsGraph(object): if new_level: result.append(new_level) return result - + def nodes_to_build(self): ret = [] for level in self.by_levels(): diff --git a/conans/client/graph/graph_builder.py b/conans/client/graph/graph_builder.py index 587dd487b..1704247f7 100644 --- a/conans/client/graph/graph_builder.py +++ b/conans/client/graph/graph_builder.py @@ -56,14 +56,14 @@ class DepsGraphBuilder(object): if alias: req.conan_reference = alias - if not hasattr(conanfile, "_evaluated_requires"): - conanfile._evaluated_requires = conanfile.requires.copy() - elif conanfile.requires != conanfile._evaluated_requires: + if not hasattr(conanfile, "_conan_evaluated_requires"): + conanfile._conan_evaluated_requires = conanfile.requires.copy() + elif conanfile.requires != conanfile._conan_evaluated_requires: raise ConanException("%s: Incompatible requirements obtained in different " "evaluations of 'requirements'\n" " Previous requirements: %s\n" " New requirements: %s" - % (conanref, list(conanfile._evaluated_requires.values()), + % (conanref, list(conanfile._conan_evaluated_requires.values()), list(conanfile.requires.values()))) def _load_deps(self, node, down_reqs, dep_graph, public_deps, down_ref, down_options, @@ -179,10 +179,10 @@ class DepsGraphBuilder(object): # So it is necessary to save the "requires" state and restore it before a second # execution of requirements(). It is a shallow copy, if first iteration is # RequireResolve'd or overridden, the inner requirements are modified - if not hasattr(conanfile, "_original_requires"): - conanfile._original_requires = conanfile.requires.copy() + if not hasattr(conanfile, "_conan_original_requires"): + conanfile._conan_original_requires = conanfile.requires.copy() else: - conanfile.requires = conanfile._original_requires.copy() + conanfile.requires = conanfile._conan_original_requires.copy() with conanfile_exception_formatter(str(conanfile), "requirements"): conanfile.requirements() diff --git a/conans/client/graph/graph_manager.py b/conans/client/graph/graph_manager.py index 32bdb94a9..415e83107 100644 --- a/conans/client/graph/graph_manager.py +++ b/conans/client/graph/graph_manager.py @@ -100,8 +100,8 @@ class GraphManager(object): require.conan_reference = require.range_reference = reference else: conanfile.requires(str(reference)) - conanfile._user = reference.user - conanfile._channel = reference.channel + conanfile._conan_user = reference.user + conanfile._conan_channel = reference.channel # Computing the full dependency graph cache_settings = self._client_cache.settings.copy() diff --git a/conans/client/installer.py b/conans/client/installer.py index b0fe070eb..119df2cdd 100644 --- a/conans/client/installer.py +++ b/conans/client/installer.py @@ -407,7 +407,7 @@ class ConanInstaller(object): # Update the info but filtering the package values that not apply to the subtree # of this current node and its dependencies. subtree_libnames = [node.conan_ref.name for node in node_order] - for package_name, env_vars in conan_file._env_values.data.items(): + for package_name, env_vars in conan_file._conan_env_values.data.items(): for name, value in env_vars.items(): if not package_name or package_name in subtree_libnames or \ package_name == conan_file.name: diff --git a/conans/client/loader.py b/conans/client/loader.py index de3db350e..05d07feec 100644 --- a/conans/client/loader.py +++ b/conans/client/loader.py @@ -159,7 +159,7 @@ class ConanFileLoader(object): # imports method conanfile.imports = parser.imports_method(conanfile) - conanfile._env_values.update(processed_profile._env_values) + conanfile._conan_env_values.update(processed_profile._env_values) return conanfile def load_virtual(self, references, processed_profile, scope_options=True, diff --git a/conans/client/tools/win.py b/conans/client/tools/win.py index d864f8ea8..fb8790e99 100644 --- a/conans/client/tools/win.py +++ b/conans/client/tools/win.py @@ -489,4 +489,4 @@ def run_in_windows_bash(conanfile, bashcmd, cwd=None, subsystem=None, msys_mingw wincmd = '%s --login -c %s' % (bash_path, escape_windows_cmd(to_run)) conanfile.output.info('run_in_windows_bash: %s' % wincmd) # https://github.com/conan-io/conan/issues/2839 (subprocess=True) - return conanfile._runner(wincmd, output=conanfile.output, subprocess=True) + return conanfile._conan_runner(wincmd, output=conanfile.output, subprocess=True) diff --git a/conans/model/conan_file.py b/conans/model/conan_file.py index f025e5367..798790c00 100644 --- a/conans/model/conan_file.py +++ b/conans/model/conan_file.py @@ -109,9 +109,9 @@ class ConanFile(object): # an output stream (writeln, info, warn error) self.output = output # something that can run commands, as os.sytem - self._runner = runner - self._user = user - self._channel = channel + self._conan_runner = runner + self._conan_user = user + self._conan_channel = channel def initialize(self, settings, env, local=None): if isinstance(self.generators, str): @@ -147,15 +147,15 @@ class ConanFile(object): self.deps_user_info = DepsUserInfo() # user specified env variables - self._env_values = env.copy() # user specified -e + self._conan_env_values = env.copy() # user specified -e @property def env(self): - """Apply the self.deps_env_info into a copy of self._env_values (will prioritize the - self._env_values, user specified from profiles or -e first, then inherited)""" + """Apply the self.deps_env_info into a copy of self._conan_env_values (will prioritize the + self._conan_env_values, user specified from profiles or -e first, then inherited)""" # Cannot be lazy cached, because it's called in configure node, and we still don't have # the deps_env_info objects available - tmp_env_values = self._env_values.copy() + tmp_env_values = self._conan_env_values.copy() tmp_env_values.update(self.deps_env_info) ret, multiple = tmp_env_values.env_dicts(self.name) @@ -164,21 +164,21 @@ class ConanFile(object): @property def channel(self): - if not self._channel: - self._channel = os.getenv("CONAN_CHANNEL") - if not self._channel: + if not self._conan_channel: + self._conan_channel = os.getenv("CONAN_CHANNEL") + if not self._conan_channel: raise ConanException("CONAN_CHANNEL environment variable not defined, " "but self.channel is used in conanfile") - return self._channel + return self._conan_channel @property def user(self): - if not self._user: - self._user = os.getenv("CONAN_USERNAME") - if not self._user: + if not self._conan_user: + self._conan_user = os.getenv("CONAN_USERNAME") + if not self._conan_user: raise ConanException("CONAN_USERNAME environment variable not defined, " "but self.user is used in conanfile") - return self._user + return self._conan_user def collect_libs(self, folder="lib"): self.output.warn("Use 'self.collect_libs' is deprecated, " @@ -239,14 +239,15 @@ class ConanFile(object): ignore_errors=False, run_environment=False): def _run(): if not win_bash: - return self._runner(command, output, os.path.abspath(RUN_LOG_NAME), cwd) + return self._conan_runner(command, output, os.path.abspath(RUN_LOG_NAME), cwd) # FIXME: run in windows bash is not using output return tools.run_in_windows_bash(self, bashcmd=command, cwd=cwd, subsystem=subsystem, msys_mingw=msys_mingw) if run_environment: with tools.run_environment(self): if os_info.is_macos: - command = 'DYLD_LIBRARY_PATH="%s" %s' % (os.environ.get('DYLD_LIBRARY_PATH', ''), command) + command = 'DYLD_LIBRARY_PATH="%s" %s' % (os.environ.get('DYLD_LIBRARY_PATH', ''), + command) retcode = _run() else: retcode = _run() @@ -268,7 +269,7 @@ class ConanFile(object): raise ConanException("You need to create a method 'test' in your test/conanfile.py") def __repr__(self): - if self.name and self.version and self._channel and self._user: + if self.name and self.version and self._conan_channel and self._conan_user: return "%s/%s@%s/%s" % (self.name, self.version, self.user, self.channel) elif self.name and self.version: return "%s/%s@PROJECT" % (self.name, self.version)
Define policy for conan vs user ConanFile attributes and methods To reduce possible future collisions when things are added to conan. E.g.: - Use "_myattribute" for user defined attributes. Conan reserves all public members - Use "__myattribute" for user defined atributes. (What happens for inheritance via python_requires?) - Etc.
conan-io/conan
diff --git a/conans/test/model/conanfile_test.py b/conans/test/model/conanfile_test.py new file mode 100644 index 000000000..e515cf5a7 --- /dev/null +++ b/conans/test/model/conanfile_test.py @@ -0,0 +1,41 @@ +import unittest +from conans.model.conan_file import ConanFile +from conans.model.env_info import EnvValues +from conans.model.settings import Settings +from conans.test.utils.tools import TestClient + + +class ConanFileTest(unittest.TestCase): + def test_conanfile_naming(self): + for member in vars(ConanFile): + if member.startswith('_') and not member.startswith("__"): + self.assertTrue(member.startswith('_conan')) + + conanfile = ConanFile(None, None) + conanfile.initialize(Settings(), EnvValues()) + + for member in vars(conanfile): + if member.startswith('_') and not member.startswith("__"): + self.assertTrue(member.startswith('_conan')) + + def test_conanfile_naming_complete(self): + client = TestClient() + conanfile = """from conans import ConanFile +class Pkg(ConanFile): + pass + def package_info(self): + for member in Pkg.__dict__: + if member.startswith('_') and not member.startswith("__"): + assert(member.startswith('_conan')) + for member in vars(self): + if member.startswith('_') and not member.startswith("__"): + assert(member.startswith('_conan')) +""" + client.save({"conanfile.py": conanfile}) + client.run("create . PkgA/0.1@user/testing") + client.save({"conanfile.py": conanfile.replace("pass", + "requires = 'PkgA/0.1@user/testing'")}) + client.run("create . PkgB/0.1@user/testing") + client.save({"conanfile.py": conanfile.replace("pass", + "requires = 'PkgB/0.1@user/testing'")}) + client.run("create . PkgC/0.1@user/testing") diff --git a/conans/test/util/tools_test.py b/conans/test/util/tools_test.py index daf39682f..7b8f9e55d 100644 --- a/conans/test/util/tools_test.py +++ b/conans/test/util/tools_test.py @@ -864,9 +864,8 @@ ProgramFiles(x86)=C:\Program Files (x86) self.assertEqual(vcvars["PROCESSOR_REVISION"], "9e09") self.assertEqual(vcvars["ProgramFiles(x86)"], "C:\Program Files (x86)") + @unittest.skipUnless(platform.system() == "Windows", "Requires Windows") def run_in_bash_test(self): - if platform.system() != "Windows": - return class MockConanfile(object): def __init__(self): @@ -878,22 +877,22 @@ ProgramFiles(x86)=C:\Program Files (x86) def __call__(self, command, output, log_filepath=None, cwd=None, subprocess=False): # @UnusedVariable self.command = command - self._runner = MyRun() + self._conan_runner = MyRun() conanfile = MockConanfile() with patch.object(OSInfo, "bash_path", return_value='bash'): tools.run_in_windows_bash(conanfile, "a_command.bat", subsystem="cygwin") - self.assertIn("bash", conanfile._runner.command) - self.assertIn("--login -c", conanfile._runner.command) - self.assertIn("^&^& a_command.bat ^", conanfile._runner.command) + self.assertIn("bash", conanfile._conan_runner.command) + self.assertIn("--login -c", conanfile._conan_runner.command) + self.assertIn("^&^& a_command.bat ^", conanfile._conan_runner.command) with tools.environment_append({"CONAN_BASH_PATH": "path\\to\\mybash.exe"}): tools.run_in_windows_bash(conanfile, "a_command.bat", subsystem="cygwin") - self.assertIn('path\\to\\mybash.exe --login -c', conanfile._runner.command) + self.assertIn('path\\to\\mybash.exe --login -c', conanfile._conan_runner.command) with tools.environment_append({"CONAN_BASH_PATH": "path with spaces\\to\\mybash.exe"}): tools.run_in_windows_bash(conanfile, "a_command.bat", subsystem="cygwin") - self.assertIn('"path with spaces\\to\\mybash.exe" --login -c', conanfile._runner.command) + self.assertIn('"path with spaces\\to\\mybash.exe" --login -c', conanfile._conan_runner.command) # try to append more env vars conanfile = MockConanfile() @@ -901,7 +900,7 @@ ProgramFiles(x86)=C:\Program Files (x86) tools.run_in_windows_bash(conanfile, "a_command.bat", subsystem="cygwin", env={"PATH": "/other/path", "MYVAR": "34"}) self.assertIn('^&^& PATH=\\^"/cygdrive/other/path:/cygdrive/path/to/somewhere:$PATH\\^" ' - '^&^& MYVAR=34 ^&^& a_command.bat ^', conanfile._runner.command) + '^&^& MYVAR=34 ^&^& a_command.bat ^', conanfile._conan_runner.command) def download_retries_test(self): http_server = StoppableThreadBottle()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 7 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist" ], "pre_install": [ "apt-get update", "apt-get install -y gcc g++-multilib wget unzip" ], "python": "3.6", "reqs_path": [ "conans/requirements.txt", "conans/requirements_server.txt", "conans/requirements_dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 beautifulsoup4==4.12.3 bottle==0.12.25 certifi==2021.5.30 charset-normalizer==2.0.12 codecov==2.1.13 colorama==0.3.9 -e git+https://github.com/conan-io/conan.git@bb404b34bc894032ac4c56ac03d2cf3e6a7ef3e9#egg=conan coverage==4.2 deprecation==2.0.7 dill==0.3.4 distro==1.1.0 execnet==1.9.0 fasteners==0.19 future==0.16.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 lazy-object-proxy==1.7.1 mccabe==0.7.0 mock==1.3.0 node-semver==0.2.0 nose==1.3.7 packaging==21.3 parameterized==0.8.1 patch==1.16 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 pluginbase==0.7 py==1.11.0 Pygments==2.14.0 PyJWT==1.7.1 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-xdist==3.0.2 PyYAML==3.13 requests==2.27.1 six==1.17.0 soupsieve==2.3.2.post1 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 waitress==2.0.0 WebOb==1.8.9 WebTest==2.0.35 wrapt==1.16.0 zipp==3.6.0
name: conan channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - beautifulsoup4==4.12.3 - bottle==0.12.25 - charset-normalizer==2.0.12 - codecov==2.1.13 - colorama==0.3.9 - coverage==4.2 - deprecation==2.0.7 - dill==0.3.4 - distro==1.1.0 - execnet==1.9.0 - fasteners==0.19 - future==0.16.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - mccabe==0.7.0 - mock==1.3.0 - node-semver==0.2.0 - nose==1.3.7 - packaging==21.3 - parameterized==0.8.1 - patch==1.16 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - pluginbase==0.7 - py==1.11.0 - pygments==2.14.0 - pyjwt==1.7.1 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-xdist==3.0.2 - pyyaml==3.13 - requests==2.27.1 - six==1.17.0 - soupsieve==2.3.2.post1 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - waitress==2.0.0 - webob==1.8.9 - webtest==2.0.35 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/conan
[ "conans/test/model/conanfile_test.py::ConanFileTest::test_conanfile_naming" ]
[ "conans/test/model/conanfile_test.py::ConanFileTest::test_conanfile_naming_complete", "conans/test/util/tools_test.py::ToolsTest::test_get_env_in_conanfile", "conans/test/util/tools_test.py::ToolsTest::test_global_tools_overrided", "conans/test/util/tools_test.py::GitToolTest::test_clone_submodule_git" ]
[ "conans/test/util/tools_test.py::ReplaceInFileTest::test_replace_in_file", "conans/test/util/tools_test.py::ToolsTest::test_environment_nested", "conans/test/util/tools_test.py::GitToolTest::test_clone_existing_folder_git", "conans/test/util/tools_test.py::GitToolTest::test_clone_existing_folder_without_branch", "conans/test/util/tools_test.py::GitToolTest::test_clone_git", "conans/test/util/tools_test.py::GitToolTest::test_credentials", "conans/test/util/tools_test.py::GitToolTest::test_repo_root", "conans/test/util/tools_test.py::GitToolTest::test_verify_ssl" ]
[]
MIT License
3,085
2,459
[ "conans/client/graph/graph.py", "conans/client/graph/graph_builder.py", "conans/client/graph/graph_manager.py", "conans/client/installer.py", "conans/client/loader.py", "conans/client/tools/win.py", "conans/model/conan_file.py" ]
google__mobly-497
5fdd0397ec5b32ac61be7b47e1c35ce84943e87c
2018-09-17 20:26:25
95286a01a566e056d44acfa9577a45bc7f37f51d
diff --git a/mobly/controller_manager.py b/mobly/controller_manager.py new file mode 100644 index 0000000..db23688 --- /dev/null +++ b/mobly/controller_manager.py @@ -0,0 +1,207 @@ +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Module for Mobly controller management.""" +import collections +import copy +import logging +import yaml + +from mobly import records +from mobly import signals + + +def verify_controller_module(module): + """Verifies a module object follows the required interface for + controllers. + + The interface is explained in the docstring of + `base_test.BaseTestClass.register_controller`. + + Args: + module: An object that is a controller module. This is usually + imported with import statements or loaded by importlib. + + Raises: + ControllerError: if the module does not match the Mobly controller + interface, or one of the required members is null. + """ + required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME') + for attr in required_attributes: + if not hasattr(module, attr): + raise signals.ControllerError( + 'Module %s missing required controller module attribute' + ' %s.' % (module.__name__, attr)) + if not getattr(module, attr): + raise signals.ControllerError( + 'Controller interface %s in %s cannot be null.' % + (attr, module.__name__)) + + +class ControllerManager(object): + """Manages the controller objects for Mobly. + + This manages the life cycles and info retrieval of all controller objects + used in a test. + """ + + def __init__(self, class_name, controller_configs): + # Controller object management. + self._controller_objects = collections.OrderedDict( + ) # controller_name: objects + self._controller_modules = {} # controller_name: module + self._class_name = class_name + self._controller_configs = controller_configs + + def register_controller(self, module, required=True, min_number=1): + """Loads a controller module and returns its loaded devices. + + This is to be used in a mobly test class. + + Args: + module: A module that follows the controller module interface. + required: A bool. If True, failing to register the specified + controller module raises exceptions. If False, the objects + failed to instantiate will be skipped. + min_number: An integer that is the minimum number of controller + objects to be created. Default is one, since you should not + register a controller module without expecting at least one + object. + + Returns: + A list of controller objects instantiated from controller_module, or + None if no config existed for this controller and it was not a + required controller. + + Raises: + ControllerError: + * The controller module has already been registered. + * The actual number of objects instantiated is less than the + * `min_number`. + * `required` is True and no corresponding config can be found. + * Any other error occurred in the registration process. + """ + verify_controller_module(module) + # Use the module's name as the ref name + module_ref_name = module.__name__.split('.')[-1] + if module_ref_name in self._controller_objects: + raise signals.ControllerError( + 'Controller module %s has already been registered. It cannot ' + 'be registered again.' % module_ref_name) + # Create controller objects. + module_config_name = module.MOBLY_CONTROLLER_CONFIG_NAME + if module_config_name not in self._controller_configs: + if required: + raise signals.ControllerError( + 'No corresponding config found for %s' % + module_config_name) + logging.warning( + 'No corresponding config found for optional controller %s', + module_config_name) + return None + try: + # Make a deep copy of the config to pass to the controller module, + # in case the controller module modifies the config internally. + original_config = self._controller_configs[module_config_name] + controller_config = copy.deepcopy(original_config) + objects = module.create(controller_config) + except: + logging.exception( + 'Failed to initialize objects for controller %s, abort!', + module_config_name) + raise + if not isinstance(objects, list): + raise signals.ControllerError( + 'Controller module %s did not return a list of objects, abort.' + % module_ref_name) + # Check we got enough controller objects to continue. + actual_number = len(objects) + if actual_number < min_number: + module.destroy(objects) + raise signals.ControllerError( + 'Expected to get at least %d controller objects, got %d.' % + (min_number, actual_number)) + # Save a shallow copy of the list for internal usage, so tests can't + # affect internal registry by manipulating the object list. + self._controller_objects[module_ref_name] = copy.copy(objects) + logging.debug('Found %d objects for controller %s', len(objects), + module_config_name) + self._controller_modules[module_ref_name] = module + return objects + + def unregister_controllers(self): + """Destroy controller objects and clear internal registry. + + This will be called after each test class. + """ + # TODO(xpconanfan): actually record these errors instead of just + # logging them. + for name, module in self._controller_modules.items(): + logging.debug('Destroying %s.', name) + try: + module.destroy(self._controller_objects[name]) + except: + logging.exception('Exception occurred destroying %s.', name) + self._controller_objects = collections.OrderedDict() + self._controller_modules = {} + + def _create_controller_info_record(self, controller_module_name): + """Creates controller info record for a particular controller type. + + Info is retrieved from all the controller objects spawned from the + specified module, using the controller module's `get_info` function. + + Args: + controller_module_name: string, the name of the controller module + to retrieve info from. + + Returns: + A records.ControllerInfoRecord object. + """ + module = self._controller_modules[controller_module_name] + controller_info = None + try: + controller_info = module.get_info( + copy.copy(self._controller_objects[controller_module_name])) + except AttributeError: + logging.warning('No optional debug info found for controller ' + '%s. To provide it, implement `get_info`.', + controller_module_name) + try: + yaml.dump(controller_info) + except TypeError: + logging.warning('The info of controller %s in class "%s" is not ' + 'YAML serializable! Coercing it to string.', + controller_module_name, self._class_name) + controller_info = str(controller_info) + return records.ControllerInfoRecord( + self._class_name, module.MOBLY_CONTROLLER_CONFIG_NAME, + controller_info) + + def get_controller_info_records(self): + """Get the info records for all the controller objects in the manager. + + New info records for each controller object are created for every call + so the latest info is included. + + Returns: + List of records.ControllerInfoRecord objects. Each opject conatins + the info of a type of controller + """ + info_records = [] + for controller_module_name in self._controller_objects.keys(): + record = self._create_controller_info_record( + controller_module_name) + if record: + info_records.append(record) + return info_records diff --git a/mobly/records.py b/mobly/records.py index 171c0ca..1dec134 100644 --- a/mobly/records.py +++ b/mobly/records.py @@ -539,28 +539,16 @@ class TestResult(object): else: self.error.append(record) - def add_controller_info(self, controller_name, controller_info, - test_class): - """Adds controller info to results. + def add_controller_info_record(self, controller_info_record): + """Adds a controller info record to results. - This can be called multiple times for each + This can be called multiple times for each test class. Args: - controller_name: string, name of the controller. - controller_info: yaml serializable info about the controller. - test_class: string, a tag for identifying a class. This should be - the test class's own `TAG` attribute. + controller_info_record: ControllerInfoRecord object to be added to + the result. """ - info = controller_info - try: - yaml.dump(controller_info) - except TypeError: - logging.warning('The info of controller %s in class "%s" is not ' - 'YAML serializable! Coercing it to string.', - controller_name, test_class) - info = str(controller_info) - self.controller_info.append( - ControllerInfoRecord(test_class, controller_name, info)) + self.controller_info.append(controller_info_record) def add_class_error(self, test_record): """Add a record to indicate a test class has failed before any test
Create a controller manager The management of controller object life cycles should probably be entirely self-contained. Moving registration mechanism from test runner to base test has improved the situation, but the core problem is still not solved. The management is loosely composed of class vars and methods in base class, which is convoluted with the base class's internal logic. This is difficult to manage. We should have a proper `ControllerManager`.
google/mobly
diff --git a/mobly/base_test.py b/mobly/base_test.py index 045fee8..5dc5e8f 100644 --- a/mobly/base_test.py +++ b/mobly/base_test.py @@ -21,6 +21,7 @@ import logging from future.utils import raise_with_traceback +from mobly import controller_manager from mobly import expects from mobly import records from mobly import runtime_test_info @@ -46,30 +47,6 @@ class Error(Exception): """Raised for exceptions that occured in BaseTestClass.""" -def _verify_controller_module(module): - """Verifies a module object follows the required interface for - controllers. - - Args: - module: An object that is a controller module. This is usually - imported with import statements or loaded by importlib. - - Raises: - ControllerError: if the module does not match the Mobly controller - interface, or one of the required members is null. - """ - required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME') - for attr in required_attributes: - if not hasattr(module, attr): - raise signals.ControllerError( - 'Module %s missing required controller module attribute' - ' %s.' % (module.__name__, attr)) - if not getattr(module, attr): - raise signals.ControllerError( - 'Controller interface %s in %s cannot be null.' % - (attr, module.__name__)) - - class BaseTestClass(object): """Base class for all test classes to inherit from. @@ -97,8 +74,6 @@ class BaseTestClass(object): log_path: string, specifies the root directory for all logs written by a test run. test_bed_name: string, the name of the test bed used by a test run. - controller_configs: dict, configs used for instantiating controller - objects. user_params: dict, custom parameters from user, to be consumed by the test logic. """ @@ -125,7 +100,6 @@ class BaseTestClass(object): self.TAG = self._class_name # Set params. self.log_path = configs.log_path - self.controller_configs = configs.controller_configs self.test_bed_name = configs.test_bed_name self.user_params = configs.user_params self.results = records.TestResult() @@ -133,10 +107,8 @@ class BaseTestClass(object): # Deprecated, use `self.current_test_info.name`. self.current_test_name = None self._generated_test_table = collections.OrderedDict() - # Controller object management. - self._controller_registry = collections.OrderedDict( - ) # controller_name: objects - self._controller_modules = {} # controller_name: module + self._controller_manager = controller_manager.ControllerManager( + class_name=self.TAG, controller_configs=configs.controller_configs) def __enter__(self): return self @@ -269,86 +241,15 @@ class BaseTestClass(object): * `required` is True and no corresponding config can be found. * Any other error occurred in the registration process. """ - _verify_controller_module(module) - # Use the module's name as the ref name - module_ref_name = module.__name__.split('.')[-1] - if module_ref_name in self._controller_registry: - raise signals.ControllerError( - 'Controller module %s has already been registered. It cannot ' - 'be registered again.' % module_ref_name) - # Create controller objects. - create = module.create - module_config_name = module.MOBLY_CONTROLLER_CONFIG_NAME - if module_config_name not in self.controller_configs: - if required: - raise signals.ControllerError( - 'No corresponding config found for %s' % - module_config_name) - logging.warning( - 'No corresponding config found for optional controller %s', - module_config_name) - return None - try: - # Make a deep copy of the config to pass to the controller module, - # in case the controller module modifies the config internally. - original_config = self.controller_configs[module_config_name] - controller_config = copy.deepcopy(original_config) - objects = create(controller_config) - except: - logging.exception( - 'Failed to initialize objects for controller %s, abort!', - module_config_name) - raise - if not isinstance(objects, list): - raise signals.ControllerError( - 'Controller module %s did not return a list of objects, abort.' - % module_ref_name) - # Check we got enough controller objects to continue. - actual_number = len(objects) - if actual_number < min_number: - module.destroy(objects) - raise signals.ControllerError( - 'Expected to get at least %d controller objects, got %d.' % - (min_number, actual_number)) - # Save a shallow copy of the list for internal usage, so tests can't - # affect internal registry by manipulating the object list. - self._controller_registry[module_ref_name] = copy.copy(objects) - logging.debug('Found %d objects for controller %s', len(objects), - module_config_name) - self._controller_modules[module_ref_name] = module - return objects - - def _unregister_controllers(self): - """Destroy controller objects and clear internal registry. - - This will be called after each test class. - """ - # TODO(xpconanfan): actually record these errors instead of just - # logging them. - for name, module in self._controller_modules.items(): - try: - logging.debug('Destroying %s.', name) - module.destroy(self._controller_registry[name]) - except: - logging.exception('Exception occurred destroying %s.', name) - self._controller_registry = collections.OrderedDict() - self._controller_modules = {} + return self._controller_manager.register_controller( + module, required, min_number) def _record_controller_info(self): # Collect controller information and write to test result. - for module_ref_name, objects in self._controller_registry.items(): - module = self._controller_modules[module_ref_name] - try: - controller_info = module.get_info(copy.copy(objects)) - except AttributeError: - logging.warning('No optional debug info found for controller ' - '%s. To provide it, implement `get_info`.', - module_ref_name) - continue - self.results.add_controller_info( - controller_name=module.MOBLY_CONTROLLER_CONFIG_NAME, - controller_info=controller_info, - test_class=self.TAG) + for record in self._controller_manager.get_controller_info_records(): + self.results.add_controller_info_record(record) + self.summary_writer.dump( + record.to_dict(), records.TestSummaryEntryType.CONTROLLER_INFO) def _setup_generated_tests(self): """Proxy function to guarantee the base implementation of @@ -423,6 +324,10 @@ class BaseTestClass(object): self.results.add_class_error(record) self.summary_writer.dump(record.to_dict(), records.TestSummaryEntryType.RECORD) + finally: + # Write controller info and summary to summary file. + self._record_controller_info() + self._controller_manager.unregister_controllers() def teardown_class(self): """Teardown function that will be called after all the selected tests in @@ -905,14 +810,7 @@ class BaseTestClass(object): setattr(e, 'results', self.results) raise e finally: - # Write controller info and summary to summary file. - self._record_controller_info() - for controller_info in self.results.controller_info: - self.summary_writer.dump( - controller_info.to_dict(), - records.TestSummaryEntryType.CONTROLLER_INFO) self._teardown_class() - self._unregister_controllers() logging.info('Summary for test class %s: %s', self.TAG, self.results.summary_str()) diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py index f6349ea..ff866bb 100755 --- a/tests/mobly/base_test_test.py +++ b/tests/mobly/base_test_test.py @@ -267,14 +267,25 @@ class BaseTestTest(unittest.TestCase): on_fail_call_check.assert_called_once_with("haha") def test_teardown_class_fail_by_exception(self): + mock_test_config = self.mock_test_cls_configs.copy() + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + mock_ctrlr_2_config_name = mock_second_controller.MOBLY_CONTROLLER_CONFIG_NAME + my_config = [{'serial': 'xxxx', 'magic': 'Magic'}] + mock_test_config.controller_configs[mock_ctrlr_config_name] = my_config + mock_test_config.controller_configs[ + mock_ctrlr_2_config_name] = copy.copy(my_config) + class MockBaseTest(base_test.BaseTestClass): + def setup_class(self): + self.register_controller(mock_controller) + def test_something(self): pass def teardown_class(self): raise Exception(MSG_EXPECTED_EXCEPTION) - bt_cls = MockBaseTest(self.mock_test_cls_configs) + bt_cls = MockBaseTest(mock_test_config) bt_cls.run() test_record = bt_cls.results.passed[0] class_record = bt_cls.results.error[0] @@ -287,6 +298,53 @@ class BaseTestTest(unittest.TestCase): expected_summary = ('Error 1, Executed 1, Failed 0, Passed 1, ' 'Requested 1, Skipped 0') self.assertEqual(bt_cls.results.summary_str(), expected_summary) + # Verify the controller info is recorded correctly. + info = bt_cls.results.controller_info[0] + self.assertEqual(info.test_class, 'MockBaseTest') + self.assertEqual(info.controller_name, 'MagicDevice') + self.assertEqual(info.controller_info, [{ + 'MyMagic': { + 'magic': 'Magic' + } + }]) + + def test_teardown_class_raise_abort_all(self): + mock_test_config = self.mock_test_cls_configs.copy() + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + mock_ctrlr_2_config_name = mock_second_controller.MOBLY_CONTROLLER_CONFIG_NAME + my_config = [{'serial': 'xxxx', 'magic': 'Magic'}] + mock_test_config.controller_configs[mock_ctrlr_config_name] = my_config + mock_test_config.controller_configs[ + mock_ctrlr_2_config_name] = copy.copy(my_config) + + class MockBaseTest(base_test.BaseTestClass): + def setup_class(self): + self.register_controller(mock_controller) + + def test_something(self): + pass + + def teardown_class(self): + raise asserts.abort_all(MSG_EXPECTED_EXCEPTION) + + bt_cls = MockBaseTest(mock_test_config) + with self.assertRaisesRegex(signals.TestAbortAll, + MSG_EXPECTED_EXCEPTION): + bt_cls.run() + test_record = bt_cls.results.passed[0] + self.assertTrue(bt_cls.results.is_all_pass) + expected_summary = ('Error 0, Executed 1, Failed 0, Passed 1, ' + 'Requested 1, Skipped 0') + self.assertEqual(bt_cls.results.summary_str(), expected_summary) + # Verify the controller info is recorded correctly. + info = bt_cls.results.controller_info[0] + self.assertEqual(info.test_class, 'MockBaseTest') + self.assertEqual(info.controller_name, 'MagicDevice') + self.assertEqual(info.controller_info, [{ + 'MyMagic': { + 'magic': 'Magic' + } + }]) def test_setup_test_fail_by_exception(self): mock_on_fail = mock.Mock() @@ -1836,113 +1894,6 @@ class BaseTestTest(unittest.TestCase): } }]) - def test_register_controller_no_config(self): - bt_cls = MockEmptyBaseTest(self.mock_test_cls_configs) - with self.assertRaisesRegex(signals.ControllerError, - 'No corresponding config found for'): - bt_cls.register_controller(mock_controller) - - def test_register_controller_no_config_for_not_required(self): - bt_cls = MockEmptyBaseTest(self.mock_test_cls_configs) - self.assertIsNone( - bt_cls.register_controller(mock_controller, required=False)) - - def test_register_controller_dup_register(self): - """Verifies correctness of registration, internal tally of controllers - objects, and the right error happen when a controller module is - registered twice. - """ - mock_test_config = self.mock_test_cls_configs.copy() - mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - mock_test_config.controller_configs = { - mock_ctrlr_config_name: ['magic1', 'magic2'] - } - bt_cls = MockEmptyBaseTest(mock_test_config) - bt_cls.register_controller(mock_controller) - registered_name = 'mock_controller' - self.assertTrue(registered_name in bt_cls._controller_registry) - mock_ctrlrs = bt_cls._controller_registry[registered_name] - self.assertEqual(mock_ctrlrs[0].magic, 'magic1') - self.assertEqual(mock_ctrlrs[1].magic, 'magic2') - self.assertTrue(bt_cls._controller_modules[registered_name]) - expected_msg = 'Controller module .* has already been registered.' - with self.assertRaisesRegex(signals.ControllerError, expected_msg): - bt_cls.register_controller(mock_controller) - - def test_register_controller_no_get_info(self): - mock_test_config = self.mock_test_cls_configs.copy() - mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - get_info = getattr(mock_controller, 'get_info') - delattr(mock_controller, 'get_info') - try: - mock_test_config.controller_configs = { - mock_ctrlr_config_name: ['magic1', 'magic2'] - } - bt_cls = MockEmptyBaseTest(mock_test_config) - bt_cls.register_controller(mock_controller) - self.assertEqual(bt_cls.results.controller_info, []) - finally: - setattr(mock_controller, 'get_info', get_info) - - def test_register_controller_return_value(self): - mock_test_config = self.mock_test_cls_configs.copy() - mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - mock_test_config.controller_configs = { - mock_ctrlr_config_name: ['magic1', 'magic2'] - } - bt_cls = MockEmptyBaseTest(mock_test_config) - magic_devices = bt_cls.register_controller(mock_controller) - self.assertEqual(magic_devices[0].magic, 'magic1') - self.assertEqual(magic_devices[1].magic, 'magic2') - - def test_register_controller_change_return_value(self): - mock_test_config = self.mock_test_cls_configs.copy() - mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - mock_test_config.controller_configs = { - mock_ctrlr_config_name: ['magic1', 'magic2'] - } - bt_cls = MockEmptyBaseTest(mock_test_config) - magic_devices = bt_cls.register_controller(mock_controller) - magic1 = magic_devices.pop(0) - self.assertIs(magic1, - bt_cls._controller_registry['mock_controller'][0]) - self.assertEqual( - len(bt_cls._controller_registry['mock_controller']), 2) - - def test_register_controller_less_than_min_number(self): - mock_test_config = self.mock_test_cls_configs.copy() - mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - mock_test_config.controller_configs = { - mock_ctrlr_config_name: ['magic1', 'magic2'] - } - bt_cls = MockEmptyBaseTest(mock_test_config) - expected_msg = 'Expected to get at least 3 controller objects, got 2.' - with self.assertRaisesRegex(signals.ControllerError, expected_msg): - bt_cls.register_controller(mock_controller, min_number=3) - - def test_verify_controller_module(self): - base_test._verify_controller_module(mock_controller) - - def test_verify_controller_module_null_attr(self): - try: - tmp = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - mock_controller.MOBLY_CONTROLLER_CONFIG_NAME = None - msg = 'Controller interface .* in .* cannot be null.' - with self.assertRaisesRegex(signals.ControllerError, msg): - base_test._verify_controller_module(mock_controller) - finally: - mock_controller.MOBLY_CONTROLLER_CONFIG_NAME = tmp - - def test_verify_controller_module_missing_attr(self): - try: - tmp = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME - delattr(mock_controller, 'MOBLY_CONTROLLER_CONFIG_NAME') - msg = 'Module .* missing required controller module attribute' - with self.assertRaisesRegex(signals.ControllerError, msg): - base_test._verify_controller_module(mock_controller) - finally: - setattr(mock_controller, 'MOBLY_CONTROLLER_CONFIG_NAME', tmp) - if __name__ == "__main__": unittest.main() diff --git a/tests/mobly/controller_manager_test.py b/tests/mobly/controller_manager_test.py new file mode 100755 index 0000000..7c9f1b6 --- /dev/null +++ b/tests/mobly/controller_manager_test.py @@ -0,0 +1,206 @@ +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for controller manager.""" +import mock + +from future.tests.base import unittest + +from mobly import controller_manager +from mobly import signals + +from tests.lib import mock_controller + + +class ControllerManagerTest(unittest.TestCase): + """Unit tests for Mobly's ControllerManager.""" + + def test_verify_controller_module(self): + controller_manager.verify_controller_module(mock_controller) + + def test_verify_controller_module_null_attr(self): + try: + tmp = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + mock_controller.MOBLY_CONTROLLER_CONFIG_NAME = None + msg = 'Controller interface .* in .* cannot be null.' + with self.assertRaisesRegex(signals.ControllerError, msg): + controller_manager.verify_controller_module(mock_controller) + finally: + mock_controller.MOBLY_CONTROLLER_CONFIG_NAME = tmp + + def test_verify_controller_module_missing_attr(self): + try: + tmp = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + delattr(mock_controller, 'MOBLY_CONTROLLER_CONFIG_NAME') + msg = 'Module .* missing required controller module attribute' + with self.assertRaisesRegex(signals.ControllerError, msg): + controller_manager.verify_controller_module(mock_controller) + finally: + setattr(mock_controller, 'MOBLY_CONTROLLER_CONFIG_NAME', tmp) + + def test_register_controller_no_config(self): + c_manager = controller_manager.ControllerManager('SomeClass', {}) + with self.assertRaisesRegex(signals.ControllerError, + 'No corresponding config found for'): + c_manager.register_controller(mock_controller) + + def test_register_controller_no_config_for_not_required(self): + c_manager = controller_manager.ControllerManager('SomeClass', {}) + self.assertIsNone( + c_manager.register_controller(mock_controller, required=False)) + + def test_register_controller_dup_register(self): + """Verifies correctness of registration, internal tally of controllers + objects, and the right error happen when a controller module is + registered twice. + """ + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + c_manager.register_controller(mock_controller) + registered_name = 'mock_controller' + self.assertTrue(registered_name in c_manager._controller_objects) + mock_ctrlrs = c_manager._controller_objects[registered_name] + self.assertEqual(mock_ctrlrs[0].magic, 'magic1') + self.assertEqual(mock_ctrlrs[1].magic, 'magic2') + self.assertTrue(c_manager._controller_modules[registered_name]) + expected_msg = 'Controller module .* has already been registered.' + with self.assertRaisesRegex(signals.ControllerError, expected_msg): + c_manager.register_controller(mock_controller) + + def test_register_controller_return_value(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + magic_devices = c_manager.register_controller(mock_controller) + self.assertEqual(magic_devices[0].magic, 'magic1') + self.assertEqual(magic_devices[1].magic, 'magic2') + + def test_register_controller_change_return_value(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + magic_devices = c_manager.register_controller(mock_controller) + magic1 = magic_devices.pop(0) + self.assertIs(magic1, + c_manager._controller_objects['mock_controller'][0]) + self.assertEqual( + len(c_manager._controller_objects['mock_controller']), 2) + + def test_register_controller_less_than_min_number(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + expected_msg = 'Expected to get at least 3 controller objects, got 2.' + with self.assertRaisesRegex(signals.ControllerError, expected_msg): + c_manager.register_controller(mock_controller, min_number=3) + + @mock.patch('yaml.dump', side_effect=TypeError('ha')) + def test_get_controller_info_record_not_serializable(self, _): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + c_manager.register_controller(mock_controller) + record = c_manager.get_controller_info_records()[0] + actual_controller_info = record.controller_info + self.assertEqual(actual_controller_info, + "[{'MyMagic': 'magic1'}, {'MyMagic': 'magic2'}]") + + def test_controller_record_exists_without_get_info(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + get_info = getattr(mock_controller, 'get_info') + delattr(mock_controller, 'get_info') + try: + c_manager.register_controller(mock_controller) + record = c_manager.get_controller_info_records()[0] + self.assertIsNone(record.controller_info) + self.assertEqual(record.test_class, 'SomeClass') + self.assertEqual(record.controller_name, 'MagicDevice') + finally: + setattr(mock_controller, 'get_info', get_info) + + @mock.patch('tests.lib.mock_controller.get_info') + def test_get_controller_info_records_empty(self, mock_get_info_func): + mock_get_info_func.return_value = None + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + c_manager.register_controller(mock_controller) + record = c_manager.get_controller_info_records()[0] + self.assertIsNone(record.controller_info) + self.assertEqual(record.test_class, 'SomeClass') + self.assertEqual(record.controller_name, 'MagicDevice') + + def test_get_controller_info_records(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + c_manager.register_controller(mock_controller) + record = c_manager.get_controller_info_records()[0] + record_dict = record.to_dict() + record_dict.pop('Timestamp') + self.assertEqual( + record_dict, { + 'Controller Info': [{ + 'MyMagic': 'magic1' + }, { + 'MyMagic': 'magic2' + }], + 'Controller Name': 'MagicDevice', + 'Test Class': 'SomeClass' + }) + + def test_get_controller_info_without_registration(self): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + self.assertFalse(c_manager.get_controller_info_records()) + + @mock.patch('tests.lib.mock_controller.destroy') + def test_unregister_controller(self, mock_destroy_func): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + objects = c_manager.register_controller(mock_controller) + c_manager.unregister_controllers() + mock_destroy_func.assert_called_once_with(objects) + self.assertFalse(c_manager._controller_objects) + self.assertFalse(c_manager._controller_modules) + + @mock.patch('tests.lib.mock_controller.destroy') + def test_unregister_controller_without_registration( + self, mock_destroy_func): + mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME + controller_configs = {mock_ctrlr_config_name: ['magic1', 'magic2']} + c_manager = controller_manager.ControllerManager( + 'SomeClass', controller_configs) + c_manager.unregister_controllers() + mock_destroy_func.assert_not_called() + self.assertFalse(c_manager._controller_objects) + self.assertFalse(c_manager._controller_modules) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/mobly/records_test.py b/tests/mobly/records_test.py index a967b8b..9648637 100755 --- a/tests/mobly/records_test.py +++ b/tests/mobly/records_test.py @@ -239,15 +239,18 @@ class RecordsTest(unittest.TestCase): record1.test_pass(s) tr1 = records.TestResult() tr1.add_record(record1) - tr1.add_controller_info('SomeClass', 'MockDevice', - ['magicA', 'magicB']) + controller_info = records.ControllerInfoRecord( + 'SomeClass', 'MockDevice', ['magicA', 'magicB']) + tr1.add_controller_info_record(controller_info) record2 = records.TestResultRecord(self.tn) record2.test_begin() s = signals.TestPass(self.details, self.json_extra) record2.test_pass(s) tr2 = records.TestResult() tr2.add_record(record2) - tr2.add_controller_info('SomeClass', 'MockDevice', ['magicC']) + controller_info = records.ControllerInfoRecord( + 'SomeClass', 'MockDevice', ['magicC']) + tr2.add_controller_info_record(controller_info) tr2 += tr1 self.assertTrue(tr2.passed, [tr1, tr2]) self.assertTrue(tr2.controller_info, {'MockDevice': ['magicC']}) @@ -413,25 +416,17 @@ class RecordsTest(unittest.TestCase): self.assertIsNot(er, new_er) self.assertDictEqual(er.to_dict(), new_er.to_dict()) - def test_add_controller_info(self): + def test_add_controller_info_record(self): tr = records.TestResult() self.assertFalse(tr.controller_info) - tr.add_controller_info('MockDevice', ['magicA', 'magicB'], 'MyTest') + controller_info = records.ControllerInfoRecord( + 'SomeClass', 'MockDevice', ['magicA', 'magicB']) + tr.add_controller_info_record(controller_info) self.assertTrue(tr.controller_info[0]) self.assertEqual(tr.controller_info[0].controller_name, 'MockDevice') self.assertEqual(tr.controller_info[0].controller_info, ['magicA', 'magicB']) - @mock.patch('yaml.dump', side_effect=TypeError('ha')) - def test_add_controller_info_not_serializable(self, mock_yaml_dump): - tr = records.TestResult() - self.assertFalse(tr.controller_info) - tr.add_controller_info('MockDevice', ['magicA', 'magicB'], 'MyTest') - self.assertTrue(tr.controller_info[0]) - self.assertEqual(tr.controller_info[0].controller_name, 'MockDevice') - self.assertEqual(tr.controller_info[0].controller_info, - "['magicA', 'magicB']") - if __name__ == '__main__': unittest.main()
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_added_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "pytest", "pytz" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 future==1.0.0 iniconfig==2.1.0 -e git+https://github.com/google/mobly.git@5fdd0397ec5b32ac61be7b47e1c35ce84943e87c#egg=mobly mock==5.2.0 packaging==24.2 pluggy==1.5.0 portpicker==1.6.0 psutil==7.0.0 pyserial==3.5 pytest==8.3.5 pytz==2025.2 PyYAML==6.0.2 timeout-decorator==0.5.0 tomli==2.2.1
name: mobly channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - future==1.0.0 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - portpicker==1.6.0 - psutil==7.0.0 - pyserial==3.5 - pytest==8.3.5 - pytz==2025.2 - pyyaml==6.0.2 - timeout-decorator==0.5.0 - tomli==2.2.1 prefix: /opt/conda/envs/mobly
[ "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail_from_setup_class", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_setup_class", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_setup_test", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_teardown_class", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_test", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_on_fail", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_setup_test", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test", "tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_setup_class", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_assert_true", "tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions", "tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention", "tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list", "tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info", "tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info_in_setup_class", "tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name", "tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests", "tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_equal", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_false", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_in_teardown_test", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_multiple_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_op", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_custom_msg", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_default_msg", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_true", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_true_and_assert_true", "tests/mobly/base_test_test.py::BaseTestTest::test_expect_two_tests", "tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_fail", "tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded", "tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded", "tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests", "tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name", "tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run", "tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run", "tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_setup_class_fails_by_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_setup_test_fails_by_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_triggered_by_setup_class_failure_then_fail_too", "tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record", "tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record", "tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal", "tests/mobly/base_test_test.py::BaseTestTest::test_record_controller_info", "tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list", "tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention", "tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count", "tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_setup_generated_tests_failure", "tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal", "tests/mobly/base_test_test.py::BaseTestTest::test_skip", "tests/mobly/base_test_test.py::BaseTestTest::test_skip_if", "tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_raise_abort_all", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass", "tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required", "tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_controller_record_exists_without_get_info", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_get_controller_info_record_not_serializable", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_get_controller_info_records", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_get_controller_info_records_empty", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_get_controller_info_without_registration", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_change_return_value", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_dup_register", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_less_than_min_number", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_no_config", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_no_config_for_not_required", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_register_controller_return_value", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_unregister_controller", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_unregister_controller_without_registration", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_verify_controller_module", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_verify_controller_module_missing_attr", "tests/mobly/controller_manager_test.py::ControllerManagerTest::test_verify_controller_module_null_attr", "tests/mobly/records_test.py::RecordsTest::test_add_controller_info_record", "tests/mobly/records_test.py::RecordsTest::test_exception_record_deepcopy", "tests/mobly/records_test.py::RecordsTest::test_is_all_pass", "tests/mobly/records_test.py::RecordsTest::test_is_all_pass_negative", "tests/mobly/records_test.py::RecordsTest::test_is_all_pass_with_add_class_error", "tests/mobly/records_test.py::RecordsTest::test_is_test_executed", "tests/mobly/records_test.py::RecordsTest::test_result_add_class_error_with_special_error", "tests/mobly/records_test.py::RecordsTest::test_result_add_class_error_with_test_signal", "tests/mobly/records_test.py::RecordsTest::test_result_add_operator_success", "tests/mobly/records_test.py::RecordsTest::test_result_add_operator_type_mismatch", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_none", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_stacktrace", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_float_extra", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_json_extra", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_unicode_exception", "tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_unicode_test_signal", "tests/mobly/records_test.py::RecordsTest::test_result_record_pass_none", "tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_float_extra", "tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_json_extra", "tests/mobly/records_test.py::RecordsTest::test_result_record_skip_none", "tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_float_extra", "tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_json_extra" ]
[ "tests/mobly/base_test_test.py::BaseTestTest::test_write_user_data", "tests/mobly/records_test.py::RecordsTest::test_summary_user_data", "tests/mobly/records_test.py::RecordsTest::test_summary_write_dump", "tests/mobly/records_test.py::RecordsTest::test_summary_write_dump_with_unicode" ]
[]
[]
Apache License 2.0
3,088
2,271
[ "mobly/records.py" ]
Rambatino__CHAID-88
17a4cbaed359b644e7ef34a93b44c38a2e24874e
2018-09-18 04:05:05
17a4cbaed359b644e7ef34a93b44c38a2e24874e
diff --git a/CHAID/tree.py b/CHAID/tree.py index 17e192a..86508e2 100644 --- a/CHAID/tree.py +++ b/CHAID/tree.py @@ -221,7 +221,7 @@ class Tree(object): def print_tree(self): """ prints the tree out """ - self.to_tree().show() + self.to_tree().show(line_type='ascii') def node_predictions(self): """ Determines which rows fall into which node """ @@ -264,7 +264,7 @@ class Tree(object): """ if isinstance(self.observed, ContinuousColumn): return ValueError("Cannot make model predictions on a continuous scale") - pred = np.zeros(self.data_size) + pred = np.zeros(self.data_size).astype('object') for node in self: if node.is_terminal: pred[node.indices] = max(node.members, key=node.members.get) @@ -275,4 +275,5 @@ class Tree(object): Calculates the fraction of risk associated with the model predictions """ - return 1 - float((self.model_predictions() == self.observed.arr).sum()) / self.data_size + sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr]) + return 1 - float((self.model_predictions() == sub_observed).sum()) / self.data_size
model_predictions fails with categorical dependant variables If the dependent variable is categorical, where categories are strings, the method model_predictions fails. The problem is that the the pred array is initialized as: pred = np.zeros(self.data_size) and that enforces predictions to be numerical. In order to solve that, the model_predictions could be rewritten to something like the following: pred = [None] * self.data_size for node in self: if node.is_terminal: max_val = max(node.members, key=node.members.get) for i in node.indices: pred[i] = max_val return pred Best regards
Rambatino/CHAID
diff --git a/tests/test_tree.py b/tests/test_tree.py index fcb5b60..776ab6c 100644 --- a/tests/test_tree.py +++ b/tests/test_tree.py @@ -570,3 +570,41 @@ class TestContinuousDependentVariable(TestCase): tree = CHAID.Tree.from_numpy(self.ndarr, self.normal_arr, alpha_merge=0.999, max_depth=5, min_child_node_size=11, dep_variable_type='continuous', weights=self.wt) assert round(tree.tree_store[0].p, 4) == 0.3681 assert len(tree.tree_store) == 5 + + +class TestStringCategoricalDependentVariableForModelPrediction(TestCase): + """ Test to make sure we can handle string categorical dependent varaibles """ + def setUp(self): + """ + Setup data for test case + """ + self.region = np.array([ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 2, 3, 2, 2, 2, + 3, 2, 4, 4, 2, 4, 4, 4, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 2, 2]) + self.age = np.array([ + 3, 4, 4, 3, 2, 4, 2, 3, 3, 2, 2, 3, 4, 3, 4, 2, 2, 3, 2, 3, + 2, 4, 4, 3, 2, 3, 1, 2, 4, 4, 3, 4, 4, 3, 2, 4, 2, 3, 3, 2, + 2, 3, 4, 3, 4, 2, 2, 3, 2, 3, 2, 4, 4, 3, 2, 3, 1, 2, 4, 4]) + self.gender = np.array([ + 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, + 2, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, + 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 2]) + self.lover = np.array(['lover'] * 25 + ['non-lover'] * 35) + self.tree = CHAID.Tree.from_numpy( + np.vstack([self.region, self.age, self.gender]).transpose(), + self.lover, + alpha_merge=0.05 + ) + + def test_string_dependent_categorical_variable_for_model_prediction(self): + assert (self.tree.model_predictions() == np.array(['lover'] * 30 + ['non-lover'] * 30)).all() + + def test_risk_still_works(self): + int_lover = np.array([1] * 25 + [0] * 35) + other_tree = CHAID.Tree.from_numpy( + np.vstack([self.region, self.age, self.gender]).transpose(), + int_lover, + alpha_merge=0.05 + ) + assert self.tree.risk() == other_tree.risk()
{ "commit_name": "merge_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
5.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "tox", "tox-pyenv", "detox" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 -e git+https://github.com/Rambatino/CHAID.git@17a4cbaed359b644e7ef34a93b44c38a2e24874e#egg=CHAID charset-normalizer==2.0.12 codecov==2.1.13 coverage==6.2 Cython==3.0.12 detox==0.19 distlib==0.3.9 dnspython==2.2.1 eventlet==0.33.3 filelock==3.4.1 greenlet==2.0.2 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work numpy==1.19.5 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 platformdirs==2.4.0 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 pytest-cov==4.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.27.1 savReaderWriter==3.4.2 scipy==1.5.4 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work tomli==1.2.3 tox==3.6.1 tox-pyenv==1.1.0 treelib==1.7.1 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 virtualenv==20.17.1 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: CHAID channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==2.0.12 - codecov==2.1.13 - coverage==6.2 - cython==3.0.12 - detox==0.19 - distlib==0.3.9 - dnspython==2.2.1 - eventlet==0.33.3 - filelock==3.4.1 - greenlet==2.0.2 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - numpy==1.19.5 - pandas==1.1.5 - platformdirs==2.4.0 - pytest-cov==4.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.27.1 - savreaderwriter==3.4.2 - scipy==1.5.4 - six==1.17.0 - tomli==1.2.3 - tox==3.6.1 - tox-pyenv==1.1.0 - treelib==1.7.1 - urllib3==1.26.20 - virtualenv==20.17.1 prefix: /opt/conda/envs/CHAID
[ "tests/test_tree.py::TestStringCategoricalDependentVariableForModelPrediction::test_risk_still_works", "tests/test_tree.py::TestStringCategoricalDependentVariableForModelPrediction::test_string_dependent_categorical_variable_for_model_prediction" ]
[]
[ "tests/test_tree.py::TestClassificationRules::test_all_paths", "tests/test_tree.py::TestClassificationRules::test_single_path", "tests/test_tree.py::test_best_split_unique_values", "tests/test_tree.py::test_spliting_identical_values", "tests/test_tree.py::test_best_split_with_combination", "tests/test_tree.py::test_best_split_with_combination_combining_if_too_small", "tests/test_tree.py::test_new_columns_constructor", "tests/test_tree.py::TestSurrogate::test_surrgate_detection", "tests/test_tree.py::TestSurrogate::test_surrogate_default_min_p", "tests/test_tree.py::test_p_and_chi_values", "tests/test_tree.py::test_p_and_chi_values_when_weighting_applied", "tests/test_tree.py::test_correct_dof", "tests/test_tree.py::test_zero_subbed_weighted_ndarry", "tests/test_tree.py::test_min_child_node_size_is_30", "tests/test_tree.py::test_to_tree_returns_a_tree", "tests/test_tree.py::test_max_depth_returns_correct_invalid_message", "tests/test_tree.py::test_node_predictions", "tests/test_tree.py::TestTreeGenerated::test_deletion", "tests/test_tree.py::TestTreeGenerated::test_iter", "tests/test_tree.py::TestTreeGenerated::test_modification", "tests/test_tree.py::TestComplexStructures::test_p_and_chi_values_selectivity", "tests/test_tree.py::TestBugFixes::test_incorrect_weighted_counts", "tests/test_tree.py::TestBugFixes::test_splits_shouldnt_carry_on_splitting_below_min_child_node_size", "tests/test_tree.py::TestBugFixes::test_unicode_printing", "tests/test_tree.py::TestStoppingRules::test_min_child_node_size_does_not_stop_for_unweighted_case", "tests/test_tree.py::TestStoppingRules::test_min_child_node_size_does_not_stop_for_weighted_case", "tests/test_tree.py::TestStoppingRules::test_min_child_node_size_does_stop_for_unweighted_case", "tests/test_tree.py::TestStoppingRules::test_min_child_node_size_does_stop_for_weighted_case", "tests/test_tree.py::TestContinuousDependentVariable::test_bartlett_significance", "tests/test_tree.py::TestContinuousDependentVariable::test_continuous_dependent_variable", "tests/test_tree.py::TestContinuousDependentVariable::test_continuous_dependent_variable_with_weighting" ]
[]
Apache License 2.0
3,090
326
[ "CHAID/tree.py" ]
spotify__cstar-22
a66272690de28df15cc3a455ec6b19aece34e617
2018-09-26 06:59:49
a66272690de28df15cc3a455ec6b19aece34e617
diff --git a/cstar/job.py b/cstar/job.py index 1dacab8..bfa60cc 100644 --- a/cstar/job.py +++ b/cstar/job.py @@ -29,7 +29,7 @@ import cstar.jobrunner import cstar.jobprinter import cstar.jobwriter from cstar.exceptions import BadSSHHost, NoHostsSpecified, HostIsDown, \ - NoDefaultKeyspace, UnknownHost + NoDefaultKeyspace, UnknownHost, FailedExecution from cstar.output import msg, debug, emph, info, error MAX_ATTEMPTS = 3 @@ -144,9 +144,9 @@ class Job(object): keyspaces = [self.key_space] else: keyspaces = self.get_keyspaces(conn) - + has_error = True for keyspace in keyspaces: - if keyspace != "system": + try: debug("Fetching endpoint mapping for keyspace", keyspace) res = conn.run(("nodetool", "describering", keyspace)) has_error = False @@ -157,6 +157,9 @@ class Job(object): describering = cstar.nodetoolparser.parse_nodetool_describering(res.out) range_mapping = cstar.nodetoolparser.convert_describering_to_range_mapping(describering) mappings.append(cstar.endpoint_mapping.parse(range_mapping, topology, lookup=ip_lookup)) + except Exception as e: + if not keyspace.startswith("system"): + raise FailedExecution(e) if not has_error: return cstar.endpoint_mapping.merge(mappings) diff --git a/cstar/nodetoolparser/simple.py b/cstar/nodetoolparser/simple.py index ff02d39..f9227bf 100644 --- a/cstar/nodetoolparser/simple.py +++ b/cstar/nodetoolparser/simple.py @@ -22,8 +22,7 @@ _ip_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") _token_re = re.compile(r"^\-?\d+$") _status_re = re.compile(r"^[A-Za-z]+$") _state_re = re.compile(r"^[A-Za-z]+$") -_keyspace_name_re = re.compile(r"^\s*Keyspace:\s*(.*)$", re.MULTILINE) - +_keyspace_name_re = re.compile(r"^\s*Keyspace\s*:\s*(.*)$", re.MULTILINE) def parse_describe_cluster(text): return _cluster_name_re.search(text).group(1)
local variable 'has_error' referenced before assignment hello when run the cstar by this command : `cstar run --command "nodetool status" --host 192.168.1.1 --ssh-username amirio --ssh-password foobar` receive this error : Generating endpoint mapping Traceback (most recent call last): File "/usr/local/bin/cstar", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.5/dist-packages/cstar/cstarcli.py", line 131, in main namespace.func(namespace) File "/usr/local/lib/python3.5/dist-packages/cstar/args.py", line 98, in <lambda> command_parser.set_defaults(func=lambda args: execute_command(args), command=command) File "/usr/local/lib/python3.5/dist-packages/cstar/cstarcli.py", line 115, in execute_command ssh_identity_file = args.ssh_identity_file) File "/usr/local/lib/python3.5/dist-packages/cstar/job.py", line 215, in setup endpoint_mapping = self.get_endpoint_mapping(current_topology) File "/usr/local/lib/python3.5/dist-packages/cstar/job.py", line 155, in get_endpoint_mapping if not has_error: UnboundLocalError: local variable 'has_error' referenced before assignment
spotify/cstar
diff --git a/tests/nodetoolparser_test.py b/tests/nodetoolparser_test.py index ee6bfa8..54661f8 100644 --- a/tests/nodetoolparser_test.py +++ b/tests/nodetoolparser_test.py @@ -152,7 +152,7 @@ class NodetoolParserTest(unittest.TestCase): self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'booya', 'system', 'system_distributed', 'system_auth']) with open("tests/resources/cfstats-3.11.txt", 'r') as f: keyspaces = cstar.nodetoolparser.extract_keyspaces_from_cfstats(f.read()) - self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'booya', 'system', 'system_distributed', 'system_auth']) + self.assertEqual(keyspaces, ['reaper_db', 'system_traces', 'system', 'system_distributed', 'system_schema', 'system_auth']) def test_convert_describering_to_json(self): with open("tests/resources/describering-2.2.txt", 'r') as f: diff --git a/tests/resources/cfstats-3.11.txt b/tests/resources/cfstats-3.11.txt index 322e02d..e905c1f 100644 --- a/tests/resources/cfstats-3.11.txt +++ b/tests/resources/cfstats-3.11.txt @@ -1,50 +1,19 @@ -Keyspace: reaper_db - Read Count: 61944 - Read Latency: 0.08025849154074648 ms. - Write Count: 51 - Write Latency: 0.11233333333333333 ms. +Total number of tables: 37 +---------------- +Keyspace : reaper_db + Read Count: 0 + Read Latency: NaN ms + Write Count: 0 + Write Latency: NaN ms Pending Flushes: 0 - Table: cluster - SSTable count: 1 - SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] - Space used (live): 4887 - Space used (total): 4887 - Space used by snapshots (total): 0 - Off heap memory used (total): 32 - SSTable Compression Ratio: 0.5714285714285714 - Number of keys (estimate): 1 - Memtable cell count: 0 - Memtable data size: 0 - Memtable off heap memory used: 0 - Memtable switch count: 0 - Local read count: 13935 - Local read latency: NaN ms - Local write count: 0 - Local write latency: NaN ms - Pending flushes: 0 - Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 16 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 259 - Compacted partition maximum bytes: 310 - Compacted partition mean bytes: 310 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 - - Table: leader + Table: test SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -54,8 +23,9 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -67,15 +37,23 @@ Keyspace: reaper_db Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: node_metrics_v1 +---------------- +Keyspace : system_traces + Read Count: 0 + Read Latency: NaN ms + Write Count: 0 + Write Latency: NaN ms + Pending Flushes: 0 + Table: events SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -85,8 +63,9 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -98,80 +77,89 @@ Keyspace: reaper_db Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: repair_run - SSTable count: 1 - SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] - Space used (live): 24880 - Space used (total): 24880 + Table: sessions + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 52 - SSTable Compression Ratio: 0.2806763962952568 - Number of keys (estimate): 3 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 Memtable switch count: 0 - Local read count: 44064 + Local read count: 0 Local read latency: NaN ms Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 28 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 20502 - Compacted partition maximum bytes: 29521 - Compacted partition mean bytes: 26241 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: repair_run_by_cluster - SSTable count: 1 - SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] - Space used (live): 4891 - Space used (total): 4891 +---------------- +Keyspace : system + Read Count: 35 + Read Latency: 3.5249142857142854 ms + Write Count: 86 + Write Latency: 0.46945348837209305 ms + Pending Flushes: 0 + Table: IndexInfo + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 32 - SSTable Compression Ratio: 0.9465648854961832 - Number of keys (estimate): 1 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 Memtable switch count: 0 - Local read count: 2001 + Local read count: 0 Local read latency: NaN ms Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 16 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 125 - Compacted partition maximum bytes: 149 - Compacted partition mean bytes: 149 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: repair_run_by_unit - SSTable count: 1 - SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] - Space used (live): 4939 - Space used (total): 4939 + Table: available_ranges + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 44 - SSTable Compression Ratio: 0.8741258741258742 - Number of keys (estimate): 1 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -181,29 +169,30 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 28 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 125 - Compacted partition maximum bytes: 149 - Compacted partition mean bytes: 149 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: repair_schedule_by_cluster_and_keyspace + Table: batches SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -213,8 +202,9 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -222,20 +212,20 @@ Keyspace: reaper_db Compacted partition minimum bytes: 0 Compacted partition maximum bytes: 0 Compacted partition mean bytes: 0 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: repair_schedule_v1 + Table: batchlog SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -245,8 +235,9 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -258,59 +249,61 @@ Keyspace: reaper_db Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: repair_unit_v1 - SSTable count: 1 - SSTables in each level: [1, 0, 0, 0, 0, 0, 0, 0, 0] - Space used (live): 4901 - Space used (total): 4901 + Table: built_views + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 44 - SSTable Compression Ratio: 0.782608695652174 - Number of keys (estimate): 1 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 Memtable switch count: 0 - Local read count: 1938 + Local read count: 0 Local read latency: NaN ms Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 28 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 150 - Compacted partition maximum bytes: 179 - Compacted partition mean bytes: 179 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: running_reapers + Table: compaction_history SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 1 - Memtable cell count: 150 - Memtable data size: 220 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 4 + Memtable cell count: 5 + Memtable data size: 988 Memtable off heap memory used: 0 Memtable switch count: 0 Local read count: 0 Local read latency: NaN ms - Local write count: 50 - Local write latency: NaN ms + Local write count: 5 + Local write latency: 0.081 ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -322,47 +315,16 @@ Keyspace: reaper_db Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: schema_migration - SSTable count: 2 - Space used (live): 13193 - Space used (total): 13193 - Space used by snapshots (total): 0 - Off heap memory used (total): 58 - SSTable Compression Ratio: 0.4748570349221942 - Number of keys (estimate): 2 - Memtable cell count: 4 - Memtable data size: 179 - Memtable off heap memory used: 0 - Memtable switch count: 0 - Local read count: 6 - Local read latency: NaN ms - Local write count: 1 - Local write latency: NaN ms - Pending flushes: 0 - Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 26 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 771 - Compacted partition maximum bytes: 11864 - Compacted partition mean bytes: 6394 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 - - Table: snapshot + Table: hints SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -372,8 +334,9 @@ Keyspace: reaper_db Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -385,53 +348,50 @@ Keyspace: reaper_db Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 ----------------- -Keyspace: system_traces - Read Count: 0 - Read Latency: NaN ms. - Write Count: 0 - Write Latency: NaN ms. - Pending Flushes: 0 - Table: events + Table: local SSTable count: 1 - Space used (live): 5059 - Space used (total): 5059 + Space used (live): 10947 + Space used (total): 10947 Space used by snapshots (total): 0 - Off heap memory used (total): 44 - SSTable Compression Ratio: 0.3553008595988539 - Number of keys (estimate): 1 - Memtable cell count: 0 - Memtable data size: 0 + Off heap memory used (total): 41 + SSTable Compression Ratio: 0.889298245614035 + Number of partitions (estimate): 2 + Memtable cell count: 3 + Memtable data size: 61 Memtable off heap memory used: 0 - Memtable switch count: 0 - Local read count: 0 - Local read latency: NaN ms - Local write count: 0 - Local write latency: NaN ms + Memtable switch count: 10 + Local read count: 33 + Local read latency: 1.258 ms + Local write count: 19 + Local write latency: 0.212 ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 16 Bloom filter off heap memory used: 8 - Index summary off heap memory used: 28 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 643 - Compacted partition maximum bytes: 770 - Compacted partition mean bytes: 770 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Index summary off heap memory used: 17 + Compression metadata off heap memory used: 16 + Compacted partition minimum bytes: 4769 + Compacted partition maximum bytes: 5722 + Compacted partition mean bytes: 5722 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.5454545454545454 + Maximum tombstones per slice (last five minutes): 7 + Dropped Mutations: 0 - Table: sessions - SSTable count: 1 - Space used (live): 4825 - Space used (total): 4825 + Table: paxos + SSTable count: 0 + SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 44 - SSTable Compression Ratio: 1.0 - Number of keys (estimate): 1 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -441,35 +401,30 @@ Keyspace: system_traces Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 28 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 43 - Compacted partition maximum bytes: 50 - Compacted partition mean bytes: 50 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 ----------------- -Keyspace: booya - Read Count: 0 - Read Latency: NaN ms. - Write Count: 0 - Write Latency: NaN ms. - Pending Flushes: 0 - Table: booya1 - SSTable count: 2 - Space used (live): 17705 - Space used (total): 17705 + Table: peer_events + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 304 - SSTable Compression Ratio: 0.3081875993640699 - Number of keys (estimate): 100 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -479,66 +434,63 @@ Keyspace: booya Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 272 - Bloom filter off heap memory used: 256 - Index summary off heap memory used: 32 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 61 - Compacted partition maximum bytes: 72 - Compacted partition mean bytes: 72 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: booya2 - SSTable count: 2 - Space used (live): 17741 - Space used (total): 17741 + Table: peers + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 304 - SSTable Compression Ratio: 0.31104928457869635 - Number of keys (estimate): 100 - Memtable cell count: 0 - Memtable data size: 0 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 1 + Memtable cell count: 30 + Memtable data size: 18516 Memtable off heap memory used: 0 Memtable switch count: 0 - Local read count: 0 + Local read count: 2 Local read latency: NaN ms - Local write count: 0 - Local write latency: NaN ms + Local write count: 30 + Local write latency: 0.289 ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 272 - Bloom filter off heap memory used: 256 - Index summary off heap memory used: 32 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 61 - Compacted partition maximum bytes: 72 - Compacted partition mean bytes: 72 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 + Average live cells per slice (last five minutes): 1.75 + Maximum live cells per slice (last five minutes): 2 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 ----------------- -Keyspace: system - Read Count: 380 - Read Latency: 0.9852842105263158 ms. - Write Count: 8887 - Write Latency: 0.0286327219534151 ms. - Pending Flushes: 0 - Table: IndexInfo + Table: prepared_statements SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -548,8 +500,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -561,15 +514,16 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: available_ranges + Table: range_xfers SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -579,8 +533,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -592,26 +547,28 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: batchlog + Table: size_estimates SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 - Memtable cell count: 0 - Memtable data size: 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 2 + Memtable cell count: 2322 + Memtable data size: 282495 Memtable off heap memory used: 0 Memtable switch count: 0 Local read count: 0 Local read latency: NaN ms - Local write count: 0 - Local write latency: NaN ms + Local write count: 9 + Local write latency: 1.778 ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -623,77 +580,82 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: compaction_history - SSTable count: 3 - Space used (live): 17681 - Space used (total): 17681 + Table: sstable_activity + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 156 - SSTable Compression Ratio: 0.377732675750636 - Number of keys (estimate): 22 - Memtable cell count: 0 - Memtable data size: 0 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 22 + Memtable cell count: 23 + Memtable data size: 184 Memtable off heap memory used: 0 - Memtable switch count: 9 + Memtable switch count: 0 Local read count: 0 Local read latency: NaN ms - Local write count: 41 - Local write latency: NaN ms + Local write count: 23 + Local write latency: 0.043 ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 72 - Bloom filter off heap memory used: 48 - Index summary off heap memory used: 84 - Compression metadata off heap memory used: 24 - Compacted partition minimum bytes: 259 - Compacted partition maximum bytes: 535 - Compacted partition mean bytes: 414 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: compactions_in_progress - SSTable count: 3 - Space used (live): 14709 - Space used (total): 14709 + Table: transferred_ranges + SSTable count: 0 + Space used (live): 0 + Space used (total): 0 Space used by snapshots (total): 0 - Off heap memory used (total): 132 - SSTable Compression Ratio: 0.934447128287708 - Number of keys (estimate): 2 + Off heap memory used (total): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 3 + Memtable switch count: 0 Local read count: 0 Local read latency: NaN ms - Local write count: 4 + Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 48 - Bloom filter off heap memory used: 24 - Index summary off heap memory used: 84 - Compression metadata off heap memory used: 24 - Compacted partition minimum bytes: 30 - Compacted partition maximum bytes: 372 - Compacted partition mean bytes: 188 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 0 + Bloom filter off heap memory used: 0 + Index summary off heap memory used: 0 + Compression metadata off heap memory used: 0 + Compacted partition minimum bytes: 0 + Compacted partition maximum bytes: 0 + Compacted partition mean bytes: 0 Average live cells per slice (last five minutes): NaN Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: hints + Table: views_builds_in_progress SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -703,8 +665,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -716,47 +679,23 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: local - SSTable count: 3 - Space used (live): 14921 - Space used (total): 14921 - Space used by snapshots (total): 0 - Off heap memory used (total): 99 - SSTable Compression Ratio: 0.7974873399233466 - Number of keys (estimate): 1 - Memtable cell count: 0 - Memtable data size: 0 - Memtable off heap memory used: 0 - Memtable switch count: 5 - Local read count: 244 - Local read latency: NaN ms - Local write count: 8 - Local write latency: NaN ms - Pending flushes: 0 - Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 48 - Bloom filter off heap memory used: 24 - Index summary off heap memory used: 51 - Compression metadata off heap memory used: 24 - Compacted partition minimum bytes: 87 - Compacted partition maximum bytes: 770 - Compacted partition mean bytes: 332 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 - - Table: paxos +---------------- +Keyspace : system_distributed + Read Count: 0 + Read Latency: NaN ms + Write Count: 0 + Write Latency: NaN ms + Pending Flushes: 0 + Table: parent_repair_history SSTable count: 0 - SSTables in each level: [0, 0, 0, 0, 0, 0, 0, 0, 0] Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -766,8 +705,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -779,15 +719,16 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: peer_events + Table: repair_history SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -797,8 +738,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -810,46 +752,16 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: peers - SSTable count: 1 - Space used (live): 5133 - Space used (total): 5133 - Space used by snapshots (total): 0 - Off heap memory used (total): 32 - SSTable Compression Ratio: 0.5971107544141252 - Number of keys (estimate): 2 - Memtable cell count: 0 - Memtable data size: 0 - Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 3 - Local read latency: NaN ms - Local write count: 57 - Local write latency: NaN ms - Pending flushes: 0 - Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 16 - Bloom filter off heap memory used: 8 - Index summary off heap memory used: 16 - Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 311 - Compacted partition maximum bytes: 372 - Compacted partition mean bytes: 372 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 - - Table: range_xfers + Table: view_build_status SSTable count: 0 Space used (live): 0 Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -859,8 +771,9 @@ Keyspace: system Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -872,361 +785,351 @@ Keyspace: system Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 - Table: schema_aggregates - SSTable count: 2 - Space used (live): 9534 - Space used (total): 9534 +---------------- +Keyspace : system_schema + Read Count: 100 + Read Latency: 0.29001 ms + Write Count: 39 + Write Latency: 0.3707179487179487 ms + Pending Flushes: 0 + Table: aggregates + SSTable count: 1 + Space used (live): 5065 + Space used (total): 5065 Space used by snapshots (total): 0 - Off heap memory used (total): 68 - SSTable Compression Ratio: 1.2727272727272727 - Number of keys (estimate): 1 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 8 - Local read latency: NaN ms + Memtable switch count: 1 + Local read count: 5 + Local read latency: 0.075 ms Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 36 - Compression metadata off heap memory used: 16 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 Compacted partition minimum bytes: 21 - Compacted partition maximum bytes: 24 - Compacted partition mean bytes: 24 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_columnfamilies + Table: columns SSTable count: 1 - Space used (live): 19414 - Space used (total): 19414 + Space used (live): 11087 + Space used (total): 11087 Space used by snapshots (total): 0 Off heap memory used (total): 55 - SSTable Compression Ratio: 0.1940360684817373 - Number of keys (estimate): 6 + SSTable Compression Ratio: 0.32196138039745537 + Number of partitions (estimate): 6 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 10 - Local read latency: NaN ms - Local write count: 5 - Local write latency: NaN ms + Memtable switch count: 4 + Local read count: 12 + Local read latency: 0.362 ms + Local write count: 8 + Local write latency: 0.379 ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 24 Bloom filter off heap memory used: 16 Index summary off heap memory used: 23 Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 2760 - Compacted partition maximum bytes: 42510 - Compacted partition mean bytes: 14457 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Compacted partition minimum bytes: 125 + Compacted partition maximum bytes: 8239 + Compacted partition mean bytes: 3234 + Average live cells per slice (last five minutes): 64.8 + Maximum live cells per slice (last five minutes): 258 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_columns + Table: dropped_columns SSTable count: 1 - Space used (live): 25837 - Space used (total): 25837 + Space used (live): 4979 + Space used (total): 4979 Space used by snapshots (total): 0 - Off heap memory used (total): 55 - SSTable Compression Ratio: 0.18518385489157277 - Number of keys (estimate): 6 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 37 - Local read latency: NaN ms - Local write count: 5 + Memtable switch count: 1 + Local read count: 10 + Local read latency: 0.096 ms + Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 24 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 23 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 925 - Compacted partition maximum bytes: 73457 - Compacted partition mean bytes: 20178 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 + Compacted partition minimum bytes: 21 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_functions - SSTable count: 2 - Space used (live): 9534 - Space used (total): 9534 + Table: functions + SSTable count: 1 + Space used (live): 5065 + Space used (total): 5065 Space used by snapshots (total): 0 - Off heap memory used (total): 68 - SSTable Compression Ratio: 1.2727272727272727 - Number of keys (estimate): 1 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 8 - Local read latency: NaN ms + Memtable switch count: 1 + Local read count: 5 + Local read latency: 0.067 ms Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 36 - Compression metadata off heap memory used: 16 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 Compacted partition minimum bytes: 21 - Compacted partition maximum bytes: 24 - Compacted partition mean bytes: 24 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_keyspaces + Table: indexes SSTable count: 1 - Space used (live): 5317 - Space used (total): 5317 + Space used (live): 4979 + Space used (total): 4979 Space used by snapshots (total): 0 - Off heap memory used (total): 47 - SSTable Compression Ratio: 0.3516988062442608 - Number of keys (estimate): 6 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 4 - Local read latency: NaN ms - Local write count: 5 + Memtable switch count: 1 + Local read count: 12 + Local read latency: 0.085 ms + Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 24 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 23 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 Compression metadata off heap memory used: 8 - Compacted partition minimum bytes: 150 - Compacted partition maximum bytes: 215 - Compacted partition mean bytes: 209 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Compacted partition minimum bytes: 21 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_triggers + Table: keyspaces SSTable count: 2 - Space used (live): 9534 - Space used (total): 9534 + Space used (live): 10676 + Space used (total): 10676 Space used by snapshots (total): 0 - Off heap memory used (total): 68 - SSTable Compression Ratio: 1.2727272727272727 - Number of keys (estimate): 1 + Off heap memory used (total): 92 + SSTable Compression Ratio: 0.5386533665835411 + Number of partitions (estimate): 6 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 35 - Local read latency: NaN ms - Local write count: 2 - Local write latency: NaN ms + Memtable switch count: 5 + Local read count: 12 + Local read latency: 0.729 ms + Local write count: 9 + Local write latency: 0.241 ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 - Bloom filter off heap memory used: 16 - Index summary off heap memory used: 36 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 21 - Compacted partition maximum bytes: 24 - Compacted partition mean bytes: 24 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 40 + Bloom filter off heap memory used: 24 + Index summary off heap memory used: 44 + Compression metadata off heap memory used: 24 + Compacted partition minimum bytes: 87 + Compacted partition maximum bytes: 149 + Compacted partition mean bytes: 122 + Average live cells per slice (last five minutes): 2.4285714285714284 + Maximum live cells per slice (last five minutes): 6 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: schema_usertypes - SSTable count: 2 - Space used (live): 9534 - Space used (total): 9534 + Table: tables + SSTable count: 1 + Space used (live): 9403 + Space used (total): 9403 Space used by snapshots (total): 0 - Off heap memory used (total): 68 - SSTable Compression Ratio: 1.2727272727272727 - Number of keys (estimate): 1 + Off heap memory used (total): 55 + SSTable Compression Ratio: 0.16976998904709747 + Number of partitions (estimate): 6 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 2 - Local read count: 8 - Local read latency: NaN ms - Local write count: 2 - Local write latency: NaN ms + Memtable switch count: 4 + Local read count: 20 + Local read latency: 0.356 ms + Local write count: 8 + Local write latency: 0.299 ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 24 Bloom filter off heap memory used: 16 - Index summary off heap memory used: 36 + Index summary off heap memory used: 23 Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 21 - Compacted partition maximum bytes: 24 - Compacted partition mean bytes: 24 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Compacted partition minimum bytes: 373 + Compacted partition maximum bytes: 8239 + Compacted partition mean bytes: 2982 + Average live cells per slice (last five minutes): 7.5 + Maximum live cells per slice (last five minutes): 42 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: size_estimates - SSTable count: 2 - Space used (live): 12369 - Space used (total): 12369 + Table: triggers + SSTable count: 1 + Space used (live): 4979 + Space used (total): 4979 Space used by snapshots (total): 0 - Off heap memory used (total): 94 - SSTable Compression Ratio: 0.16691314966847087 - Number of keys (estimate): 10 - Memtable cell count: 330 - Memtable data size: 5197 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 + Memtable cell count: 0 + Memtable data size: 0 Memtable off heap memory used: 0 - Memtable switch count: 20 - Local read count: 0 - Local read latency: NaN ms - Local write count: 5126 + Memtable switch count: 1 + Local read count: 12 + Local read latency: 0.073 ms + Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 48 - Bloom filter off heap memory used: 32 - Index summary off heap memory used: 46 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 536 - Compacted partition maximum bytes: 4768 - Compacted partition mean bytes: 1578 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 - - Table: sstable_activity - SSTable count: 2 - Space used (live): 13458 - Space used (total): 13458 - Space used by snapshots (total): 0 - Off heap memory used (total): 194 - SSTable Compression Ratio: 0.3279409178828908 - Number of keys (estimate): 38 - Memtable cell count: 135 - Memtable data size: 1335 - Memtable off heap memory used: 0 - Memtable switch count: 20 - Local read count: 23 - Local read latency: NaN ms - Local write count: 3628 - Local write latency: 0,017 ms - Pending flushes: 0 - Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 80 - Bloom filter off heap memory used: 64 - Index summary off heap memory used: 114 - Compression metadata off heap memory used: 16 - Compacted partition minimum bytes: 43 - Compacted partition maximum bytes: 179 - Compacted partition mean bytes: 152 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 + Compacted partition minimum bytes: 21 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 ----------------- -Keyspace: system_distributed - Read Count: 0 - Read Latency: NaN ms. - Write Count: 598 - Write Latency: 0.09190635451505016 ms. - Pending Flushes: 0 - Table: parent_repair_history + Table: types SSTable count: 1 - Space used (live): 43448 - Space used (total): 43448 + Space used (live): 4938 + Space used (total): 4938 Space used by snapshots (total): 0 - Off heap memory used (total): 296 - SSTable Compression Ratio: 0.20285498694969137 - Number of keys (estimate): 170 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 Memtable switch count: 1 - Local read count: 0 - Local read latency: NaN ms - Local write count: 46 + Local read count: 5 + Local read latency: 0.106 ms + Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 224 - Bloom filter off heap memory used: 216 - Index summary off heap memory used: 56 - Compression metadata off heap memory used: 24 - Compacted partition minimum bytes: 373 - Compacted partition maximum bytes: 1109 - Compacted partition mean bytes: 1099 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 + Compacted partition minimum bytes: 21 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 - Table: repair_history + Table: views SSTable count: 1 - Space used (live): 347020 - Space used (total): 347020 + Space used (live): 4938 + Space used (total): 4938 Space used by snapshots (total): 0 - Off heap memory used (total): 218 - SSTable Compression Ratio: 0.28505859645558396 - Number of keys (estimate): 14 + Off heap memory used (total): 41 + SSTable Compression Ratio: 1.0408163265306123 + Number of partitions (estimate): 2 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 Memtable switch count: 1 - Local read count: 0 - Local read latency: NaN ms - Local write count: 552 + Local read count: 7 + Local read latency: 0.147 ms + Local write count: 2 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 0.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 - Bloom filter space used: 32 - Bloom filter off heap memory used: 24 - Index summary off heap memory used: 42 - Compression metadata off heap memory used: 152 - Compacted partition minimum bytes: 643 - Compacted partition maximum bytes: 105778 - Compacted partition mean bytes: 86865 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 + Bloom filter false ratio: 0.00000 + Bloom filter space used: 16 + Bloom filter off heap memory used: 8 + Index summary off heap memory used: 25 + Compression metadata off heap memory used: 8 + Compacted partition minimum bytes: 21 + Compacted partition maximum bytes: 29 + Compacted partition mean bytes: 27 + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 ---------------- -Keyspace: system_auth +Keyspace : system_auth Read Count: 0 - Read Latency: NaN ms. + Read Latency: NaN ms Write Count: 0 - Write Latency: NaN ms. + Write Latency: NaN ms Pending Flushes: 0 Table: resource_role_permissons_index SSTable count: 0 @@ -1234,8 +1137,8 @@ Keyspace: system_auth Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -1245,8 +1148,9 @@ Keyspace: system_auth Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -1258,6 +1162,7 @@ Keyspace: system_auth Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 Table: role_members SSTable count: 0 @@ -1265,8 +1170,8 @@ Keyspace: system_auth Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -1276,8 +1181,9 @@ Keyspace: system_auth Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -1289,6 +1195,7 @@ Keyspace: system_auth Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 Table: role_permissions SSTable count: 0 @@ -1296,8 +1203,8 @@ Keyspace: system_auth Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -1307,8 +1214,9 @@ Keyspace: system_auth Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -1320,6 +1228,7 @@ Keyspace: system_auth Maximum live cells per slice (last five minutes): 0 Average tombstones per slice (last five minutes): NaN Maximum tombstones per slice (last five minutes): 0 + Dropped Mutations: 0 Table: roles SSTable count: 0 @@ -1327,8 +1236,8 @@ Keyspace: system_auth Space used (total): 0 Space used by snapshots (total): 0 Off heap memory used (total): 0 - SSTable Compression Ratio: 0.0 - Number of keys (estimate): 0 + SSTable Compression Ratio: -1.0 + Number of partitions (estimate): 0 Memtable cell count: 0 Memtable data size: 0 Memtable off heap memory used: 0 @@ -1338,8 +1247,9 @@ Keyspace: system_auth Local write count: 0 Local write latency: NaN ms Pending flushes: 0 + Percent repaired: 100.0 Bloom filter false positives: 0 - Bloom filter false ratio: 0,00000 + Bloom filter false ratio: 0.00000 Bloom filter space used: 0 Bloom filter off heap memory used: 0 Index summary off heap memory used: 0 @@ -1347,7 +1257,10 @@ Keyspace: system_auth Compacted partition minimum bytes: 0 Compacted partition maximum bytes: 0 Compacted partition mean bytes: 0 - Average live cells per slice (last five minutes): NaN - Maximum live cells per slice (last five minutes): 0 - Average tombstones per slice (last five minutes): NaN - Maximum tombstones per slice (last five minutes): 0 \ No newline at end of file + Average live cells per slice (last five minutes): 1.0 + Maximum live cells per slice (last five minutes): 1 + Average tombstones per slice (last five minutes): 1.0 + Maximum tombstones per slice (last five minutes): 1 + Dropped Mutations: 0 + +----------------
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 2 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pyflakes", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 bcrypt==4.0.1 certifi==2021.5.30 cffi==1.15.1 cryptography==40.0.2 -e git+https://github.com/spotify/cstar.git@a66272690de28df15cc3a455ec6b19aece34e617#egg=cstar importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 paramiko==2.3.2 pluggy==1.0.0 py==1.11.0 pyasn1==0.5.1 pycparser==2.21 pyflakes==3.0.1 PyNaCl==1.5.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: cstar channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - bcrypt==4.0.1 - cffi==1.15.1 - cryptography==40.0.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - paramiko==2.3.2 - pluggy==1.0.0 - py==1.11.0 - pyasn1==0.5.1 - pycparser==2.21 - pyflakes==3.0.1 - pynacl==1.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/cstar
[ "tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_keyspaces" ]
[]
[ "tests/nodetoolparser_test.py::NodetoolParserTest::test_bad_syntax", "tests/nodetoolparser_test.py::NodetoolParserTest::test_convert_describering_to_json", "tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_describecluster", "tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_describering", "tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_nodetool_ring", "tests/nodetoolparser_test.py::NodetoolParserTest::test_parse_nodetool_ring_with_vnodes", "tests/nodetoolparser_test.py::NodetoolParserTest::test_tokenize" ]
[]
Apache License 2.0
3,127
609
[ "cstar/job.py", "cstar/nodetoolparser/simple.py" ]
hugovk__pypistats-13
d36199f422c751e4dc9cf13bb409a94142121430
2018-09-26 09:36:29
d36199f422c751e4dc9cf13bb409a94142121430
diff --git a/pypistats/__init__.py b/pypistats/__init__.py index 9ebc7e6..79cbc13 100644 --- a/pypistats/__init__.py +++ b/pypistats/__init__.py @@ -4,8 +4,8 @@ Python interface to PyPI Stats API https://pypistats.org/api """ -import pytablewriter import requests +from pytablewriter import Align, MarkdownTableWriter from . import version @@ -47,12 +47,13 @@ def pypi_stats_api( return res # These only for table + data = res["data"] if sort: - res["data"] = _sort(res["data"]) + data = _sort(data) - res["data"] = _grand_total(res["data"]) + data = _percent(data) + data = _grand_total(data) - data = res["data"] return _tabulate(data) @@ -121,10 +122,25 @@ def _grand_total(data): return data +def _percent(data): + """Add a percent column""" + + # Only for lists of dicts, not a single dict + if isinstance(data, dict): + return data + + grand_total = sum(row["downloads"] for row in data) + + for row in data: + row["percent"] = "{:.2%}".format(row["downloads"] / grand_total) + + return data + + def _tabulate(data): """Return data in table""" - writer = pytablewriter.MarkdownTableWriter() + writer = MarkdownTableWriter() writer.margin = 1 if isinstance(data, dict): @@ -139,6 +155,13 @@ def _tabulate(data): header_list.remove("downloads") writer.header_list = header_list + # Custom alignment + writer.align_list = [Align.AUTO] * len(header_list) + try: + writer.align_list[header_list.index("percent")] = Align.RIGHT + except ValueError: + pass + return writer.dumps()
Add percent column to tables Put it before the downloads column.
hugovk/pypistats
diff --git a/tests/test_pypistats.py b/tests/test_pypistats.py index 1e3f8fe..feae931 100644 --- a/tests/test_pypistats.py +++ b/tests/test_pypistats.py @@ -127,7 +127,7 @@ class TestPypiStats(unittest.TestCase): def test__tabulate(self): # Arrange - data = SAMPLE_DATA + data = copy.deepcopy(SAMPLE_DATA) expected_output = """ | category | date | downloads | |----------|------------|----------:| @@ -151,7 +151,7 @@ class TestPypiStats(unittest.TestCase): def test__sort(self): # Arrange - data = SAMPLE_DATA + data = copy.deepcopy(SAMPLE_DATA) expected_output = [ {"category": "2.7", "date": "2018-08-15", "downloads": 63749}, {"category": "3.6", "date": "2018-08-15", "downloads": 35274}, @@ -225,3 +225,34 @@ class TestPypiStats(unittest.TestCase): # Assert self.assertEqual(output, data) + + def test__percent(self): + # Arrange + data = [ + {"category": "2.7", "downloads": 63749}, + {"category": "3.6", "downloads": 35274}, + {"category": "2.6", "downloads": 51}, + {"category": "3.2", "downloads": 2}, + ] + expected_output = [ + {"category": "2.7", "percent": "64.34%", "downloads": 63749}, + {"category": "3.6", "percent": "35.60%", "downloads": 35274}, + {"category": "2.6", "percent": "0.05%", "downloads": 51}, + {"category": "3.2", "percent": "0.00%", "downloads": 2}, + ] + + # Act + output = pypistats._percent(data) + + # Assert + self.assertEqual(output, expected_output) + + def test__percent_recent(self): + # Arrange + data = {"last_day": 123002, "last_month": 3254221, "last_week": 761649} + + # Act + output = pypistats._percent(data) + + # Assert + self.assertEqual(output, data)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-cov", "flake8" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 coverage==7.8.0 DataProperty==1.1.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mbstrdecoder==1.1.4 mccabe==0.7.0 packaging @ file:///croot/packaging_1734472117206/work pathvalidate==3.2.3 pluggy @ file:///croot/pluggy_1733169602837/work pycodestyle==2.13.0 pyflakes==3.3.2 -e git+https://github.com/hugovk/pypistats.git@d36199f422c751e4dc9cf13bb409a94142121430#egg=pypistats pytablewriter==1.2.1 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.32.3 six==1.17.0 tabledata==1.3.4 tcolorpy==0.1.7 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typepy==1.3.4 urllib3==2.3.0
name: pypistats channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - coverage==7.8.0 - dataproperty==1.1.0 - flake8==7.2.0 - idna==3.10 - mbstrdecoder==1.1.4 - mccabe==0.7.0 - pathvalidate==3.2.3 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytablewriter==1.2.1 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - tabledata==1.3.4 - tcolorpy==0.1.7 - typepy==1.3.4 - urllib3==2.3.0 prefix: /opt/conda/envs/pypistats
[ "tests/test_pypistats.py::TestPypiStats::test__percent", "tests/test_pypistats.py::TestPypiStats::test__percent_recent" ]
[ "tests/test_pypistats.py::TestPypiStats::test__tabulate" ]
[ "tests/test_pypistats.py::TestPypiStats::test__filter_end_date", "tests/test_pypistats.py::TestPypiStats::test__filter_no_filters_no_change", "tests/test_pypistats.py::TestPypiStats::test__filter_start_and_end_date", "tests/test_pypistats.py::TestPypiStats::test__filter_start_date", "tests/test_pypistats.py::TestPypiStats::test__grand_total", "tests/test_pypistats.py::TestPypiStats::test__grand_total_recent", "tests/test_pypistats.py::TestPypiStats::test__paramify_bool", "tests/test_pypistats.py::TestPypiStats::test__paramify_float", "tests/test_pypistats.py::TestPypiStats::test__paramify_int", "tests/test_pypistats.py::TestPypiStats::test__paramify_none", "tests/test_pypistats.py::TestPypiStats::test__paramify_string", "tests/test_pypistats.py::TestPypiStats::test__sort", "tests/test_pypistats.py::TestPypiStats::test__sort_recent", "tests/test_pypistats.py::TestPypiStats::test__total", "tests/test_pypistats.py::TestPypiStats::test__total_recent" ]
[]
MIT License
3,129
495
[ "pypistats/__init__.py" ]
pudo__dataset-265
7fc466479021992288feaa875088100b8b304af9
2018-09-26 15:37:14
43e9431865365d3c22a46ec15940ea22c0543b26
diff --git a/dataset/database.py b/dataset/database.py index 8662b81..9f4276f 100644 --- a/dataset/database.py +++ b/dataset/database.py @@ -221,10 +221,6 @@ class Database(object): """Get a given table.""" return self.get_table(table_name) - def _ipython_key_completions_(self): - """Completion for table names with IPython.""" - return self.tables - def query(self, query, *args, **kwargs): """Run a statement on the database directly. diff --git a/dataset/table.py b/dataset/table.py index 2bd5c55..bf829df 100644 --- a/dataset/table.py +++ b/dataset/table.py @@ -546,27 +546,23 @@ class Table(object): if not self.exists: return iter([]) - filters = [] - for column, value in _filter.items(): - if not self.has_column(column): - raise DatasetException("No such column: %s" % column) - filters.append(self.table.c[column] == value) - columns = [] + clauses = [] for column in args: if isinstance(column, ClauseElement): - filters.append(column) + clauses.append(column) else: if not self.has_column(column): raise DatasetException("No such column: %s" % column) columns.append(self.table.c[column]) + clause = self._args_to_clause(_filter, clauses=clauses) if not len(columns): return iter([]) q = expression.select(columns, distinct=True, - whereclause=and_(*filters), + whereclause=clause, order_by=[c.asc() for c in columns]) return self.db.query(q)
Distinct does not support advanced queries It looks like `.distinct` does not support advanced selections e.g. `table.distinct('key', key=[...])` like `.find` or `.count`. Is there a reason or is it just an oversight as it does not use `._args_to_clause` ?
pudo/dataset
diff --git a/test/test_dataset.py b/test/test_dataset.py index 4cd0645..6c5be07 100644 --- a/test/test_dataset.py +++ b/test/test_dataset.py @@ -360,6 +360,12 @@ class TableTestCase(unittest.TestCase): self.tbl.table.columns.date >= datetime(2011, 1, 2, 0, 0))) assert len(x) == 4, x + x = list(self.tbl.distinct('temperature', place='B€rkeley')) + assert len(x) == 3, x + x = list(self.tbl.distinct('temperature', + place=['B€rkeley', 'G€lway'])) + assert len(x) == 6, x + def test_insert_many(self): data = TEST_DATA * 100 self.tbl.insert_many(data, chunk_size=13)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "flake8", "psycopg2", "PyMySQL", "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alembic==1.7.7 attrs==22.2.0 banal==1.0.6 certifi==2021.5.30 chardet==5.0.0 charset-normalizer==3.0.1 -e git+https://github.com/pudo/dataset.git@7fc466479021992288feaa875088100b8b304af9#egg=dataset flake8==5.0.4 greenlet==2.0.2 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 Mako==1.1.6 MarkupSafe==2.0.1 mccabe==0.7.0 normality==2.5.0 nose==1.3.7 packaging==21.3 pluggy==1.0.0 psycopg2==2.7.7 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 PyMySQL==1.0.2 pyparsing==3.1.4 pytest==7.0.1 six==1.17.0 SQLAlchemy==1.4.54 text-unidecode==1.3 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: dataset channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alembic==1.7.7 - attrs==22.2.0 - banal==1.0.6 - chardet==5.0.0 - charset-normalizer==3.0.1 - flake8==5.0.4 - greenlet==2.0.2 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - mako==1.1.6 - markupsafe==2.0.1 - mccabe==0.7.0 - normality==2.5.0 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - psycopg2==2.7.7 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pymysql==1.0.2 - pyparsing==3.1.4 - pytest==7.0.1 - six==1.17.0 - sqlalchemy==1.4.54 - text-unidecode==1.3 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/dataset
[ "test/test_dataset.py::TableTestCase::test_distinct" ]
[]
[ "test/test_dataset.py::DatabaseTestCase::test_contains", "test/test_dataset.py::DatabaseTestCase::test_create_table", "test/test_dataset.py::DatabaseTestCase::test_create_table_custom_id1", "test/test_dataset.py::DatabaseTestCase::test_create_table_custom_id2", "test/test_dataset.py::DatabaseTestCase::test_create_table_custom_id3", "test/test_dataset.py::DatabaseTestCase::test_create_table_no_ids", "test/test_dataset.py::DatabaseTestCase::test_create_table_shorthand1", "test/test_dataset.py::DatabaseTestCase::test_create_table_shorthand2", "test/test_dataset.py::DatabaseTestCase::test_database_url_query_string", "test/test_dataset.py::DatabaseTestCase::test_invalid_values", "test/test_dataset.py::DatabaseTestCase::test_load_table", "test/test_dataset.py::DatabaseTestCase::test_query", "test/test_dataset.py::DatabaseTestCase::test_table_cache_updates", "test/test_dataset.py::DatabaseTestCase::test_tables", "test/test_dataset.py::DatabaseTestCase::test_valid_database_url", "test/test_dataset.py::DatabaseTestCase::test_with", "test/test_dataset.py::TableTestCase::test_columns", "test/test_dataset.py::TableTestCase::test_count", "test/test_dataset.py::TableTestCase::test_create_column", "test/test_dataset.py::TableTestCase::test_delete", "test/test_dataset.py::TableTestCase::test_delete_nonexist_entry", "test/test_dataset.py::TableTestCase::test_drop_column", "test/test_dataset.py::TableTestCase::test_drop_operations", "test/test_dataset.py::TableTestCase::test_empty_query", "test/test_dataset.py::TableTestCase::test_ensure_column", "test/test_dataset.py::TableTestCase::test_find", "test/test_dataset.py::TableTestCase::test_find_dsl", "test/test_dataset.py::TableTestCase::test_find_one", "test/test_dataset.py::TableTestCase::test_insert", "test/test_dataset.py::TableTestCase::test_insert_ignore", "test/test_dataset.py::TableTestCase::test_insert_ignore_all_key", "test/test_dataset.py::TableTestCase::test_insert_many", "test/test_dataset.py::TableTestCase::test_invalid_column_names", "test/test_dataset.py::TableTestCase::test_iter", "test/test_dataset.py::TableTestCase::test_key_order", "test/test_dataset.py::TableTestCase::test_offset", "test/test_dataset.py::TableTestCase::test_repr", "test/test_dataset.py::TableTestCase::test_streamed", "test/test_dataset.py::TableTestCase::test_table_drop", "test/test_dataset.py::TableTestCase::test_table_drop_then_create", "test/test_dataset.py::TableTestCase::test_update", "test/test_dataset.py::TableTestCase::test_update_while_iter", "test/test_dataset.py::TableTestCase::test_upsert", "test/test_dataset.py::TableTestCase::test_upsert_all_key", "test/test_dataset.py::TableTestCase::test_upsert_single_column", "test/test_dataset.py::TableTestCase::test_weird_column_names", "test/test_dataset.py::RowTypeTestCase::test_distinct", "test/test_dataset.py::RowTypeTestCase::test_find", "test/test_dataset.py::RowTypeTestCase::test_find_one", "test/test_dataset.py::RowTypeTestCase::test_iter" ]
[]
MIT License
3,130
424
[ "dataset/database.py", "dataset/table.py" ]
box__box-python-sdk-343
567ea528c8e757fe77399b21a68ccfc94341b68b
2018-09-28 05:06:45
8e192566e678490f540e3ece5ccb7eced975aa89
boxcla: Verified that @mattwiller has signed the CLA. Thanks for the pull request! coveralls: ## Pull Request Test Coverage Report for [Build 1093](https://coveralls.io/builds/19377329) * **3** of **3** **(100.0%)** changed or added relevant lines in **2** files are covered. * No unchanged relevant lines lost coverage. * Overall coverage increased (+**0.005%**) to **94.528%** --- | Totals | [![Coverage Status](https://coveralls.io/builds/19377329/badge)](https://coveralls.io/builds/19377329) | | :-- | --: | | Change from base [Build 1084](https://coveralls.io/builds/19316485): | 0.005% | | Covered Lines: | 2073 | | Relevant Lines: | 2193 | --- ##### 💛 - [Coveralls](https://coveralls.io)
diff --git a/boxsdk/config.py b/boxsdk/config.py index 203cfc2..371117d 100644 --- a/boxsdk/config.py +++ b/boxsdk/config.py @@ -2,6 +2,8 @@ from __future__ import unicode_literals, absolute_import +from sys import version_info as py_version + from . import version @@ -17,3 +19,9 @@ class Client(object): """Configuration object containing the user agent string.""" VERSION = version.__version__ USER_AGENT_STRING = 'box-python-sdk-{0}'.format(VERSION) + BOX_UA_STRING = 'agent=box-python-sdk/{0}; env=python/{1}.{2}.{3}'.format( + VERSION, + py_version.major, + py_version.minor, + py_version.micro, + ) diff --git a/boxsdk/session/session.py b/boxsdk/session/session.py index e9c0b14..d8a41ba 100644 --- a/boxsdk/session/session.py +++ b/boxsdk/session/session.py @@ -64,7 +64,10 @@ def __init__( self._client_config = client_config or Client() super(Session, self).__init__() self._network_layer = network_layer or DefaultNetwork() - self._default_headers = {'User-Agent': self._client_config.USER_AGENT_STRING} + self._default_headers = { + 'User-Agent': self._client_config.USER_AGENT_STRING, + 'X-Box-UA': self._client_config.BOX_UA_STRING, + } self._translator = translator self._default_network_request_kwargs = {} if default_headers:
Add Box SDK headers to API calls We should definitely send headers for SDK name and SDK version. Other nice-to-haves to consider: - Python version - Requests version
box/box-python-sdk
diff --git a/test/integration/test_as_user.py b/test/integration/test_as_user.py index 45cff68..372de7d 100644 --- a/test/integration/test_as_user.py +++ b/test/integration/test_as_user.py @@ -14,6 +14,7 @@ def as_user_headers(mock_user_id, access_token): 'Authorization': 'Bearer {0}'.format(access_token), 'As-User': mock_user_id, 'User-Agent': Client.USER_AGENT_STRING, + 'X-Box-UA': Client.BOX_UA_STRING, } diff --git a/test/integration/test_retry_and_refresh.py b/test/integration/test_retry_and_refresh.py index 057ed43..f27858c 100644 --- a/test/integration/test_retry_and_refresh.py +++ b/test/integration/test_retry_and_refresh.py @@ -29,7 +29,7 @@ def test_automatic_refresh( 'POST', '{0}/token'.format(API.OAUTH2_API_URL), data=ANY, - headers={'content-type': 'application/x-www-form-urlencoded', 'User-Agent': ANY}, + headers={'content-type': 'application/x-www-form-urlencoded', 'User-Agent': ANY, 'X-Box-UA': ANY}, ), call( 'GET', diff --git a/test/integration/test_with_shared_link.py b/test/integration/test_with_shared_link.py index c4a74d9..6d2af45 100644 --- a/test/integration/test_with_shared_link.py +++ b/test/integration/test_with_shared_link.py @@ -26,6 +26,7 @@ def box_api_headers(shared_link, shared_link_password, access_token): 'Authorization': 'Bearer {0}'.format(access_token), 'BoxApi': box_api_header, 'User-Agent': Client.USER_AGENT_STRING, + 'X-Box-UA': Client.BOX_UA_STRING, }
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
2.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-xdist", "mock", "sqlalchemy", "bottle", "jsonpatch" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 bottle==0.13.2 -e git+https://github.com/box/box-python-sdk.git@567ea528c8e757fe77399b21a68ccfc94341b68b#egg=boxsdk certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup==1.2.2 execnet==2.1.1 greenlet==3.1.1 idna==3.10 iniconfig==2.1.0 jsonpatch==1.33 jsonpointer==3.0.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-xdist==3.6.1 requests==2.32.3 requests-toolbelt==1.0.0 six==1.17.0 SQLAlchemy==2.0.40 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0 wrapt==1.17.2
name: box-python-sdk channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - bottle==0.13.2 - certifi==2025.1.31 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - greenlet==3.1.1 - idna==3.10 - iniconfig==2.1.0 - jsonpatch==1.33 - jsonpointer==3.0.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-xdist==3.6.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - six==1.17.0 - sqlalchemy==2.0.40 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - wrapt==1.17.2 prefix: /opt/conda/envs/box-python-sdk
[ "test/integration/test_as_user.py::test_client_as_user_causes_as_user_header_to_be_added", "test/integration/test_as_user.py::test_folder_object_as_user_causes_as_user_header_to_be_added", "test/integration/test_as_user.py::test_group_membership_object_as_user_causes_as_user_header_to_be_added", "test/integration/test_as_user.py::test_events_endpoint_as_user_causes_as_user_header_to_be_added", "test/integration/test_as_user.py::test_metadata_endpoint_as_user_causes_as_user_header_to_be_added", "test/integration/test_retry_and_refresh.py::test_automatic_refresh", "test/integration/test_with_shared_link.py::test_client_with_shared_link_causes_box_api_header_to_be_added[None]", "test/integration/test_with_shared_link.py::test_client_with_shared_link_causes_box_api_header_to_be_added[shared_link_password]", "test/integration/test_with_shared_link.py::test_folder_object_with_shared_link_causes_box_api_header_to_be_added[None]", "test/integration/test_with_shared_link.py::test_folder_object_with_shared_link_causes_box_api_header_to_be_added[shared_link_password]", "test/integration/test_with_shared_link.py::test_group_membership_object_with_shared_link_causes_box_api_header_to_be_added[None]", "test/integration/test_with_shared_link.py::test_group_membership_object_with_shared_link_causes_box_api_header_to_be_added[shared_link_password]", "test/integration/test_with_shared_link.py::test_events_endpoint_with_shared_link_causes_box_api_header_to_be_added[None]", "test/integration/test_with_shared_link.py::test_events_endpoint_with_shared_link_causes_box_api_header_to_be_added[shared_link_password]", "test/integration/test_with_shared_link.py::test_metadata_endpoint_with_shared_link_causes_box_api_header_to_be_added[None]", "test/integration/test_with_shared_link.py::test_metadata_endpoint_with_shared_link_causes_box_api_header_to_be_added[shared_link_password]" ]
[]
[]
[]
Apache License 2.0
3,143
388
[ "boxsdk/config.py", "boxsdk/session/session.py" ]
iterative__dvc-1173
04b3cd40e0e8f5373cace8621a0024584010cabe
2018-09-28 10:12:55
0ee7d5a7f823822445514dae1dc1db8bb4daec99
diff --git a/dvc/cli.py b/dvc/cli.py index 06c76809e..71ee097c5 100644 --- a/dvc/cli.py +++ b/dvc/cli.py @@ -439,6 +439,12 @@ def parse_args(argv=None): default=False, help='Reproduce the whole pipeline that the ' 'specified stage file belongs to.') + repro_parser.add_argument( + '-P', + '--all-pipelines', + action='store_true', + default=False, + help='Reproduce all pipelines in the project.') repro_parser.set_defaults(func=CmdRepro) # Remove @@ -838,7 +844,9 @@ def parse_args(argv=None): if (issubclass(args.func, CmdRepro) or issubclass(args.func, CmdPipelineShow)) \ and hasattr(args, 'targets') \ - and len(args.targets) == 0: + and len(args.targets) == 0 \ + and not (hasattr(args, 'all_pipelines') + and args.all_pipelines): if hasattr(args, 'cwd'): cwd = args.cwd else: diff --git a/dvc/command/repro.py b/dvc/command/repro.py index 7efa6c5ef..1d1f9c42d 100644 --- a/dvc/command/repro.py +++ b/dvc/command/repro.py @@ -21,7 +21,8 @@ class CmdRepro(CmdBase): force=self.args.force, dry=self.args.dry, interactive=self.args.interactive, - pipeline=self.args.pipeline) + pipeline=self.args.pipeline, + all_pipelines=self.args.all_pipelines) if len(stages) == 0: self.project.logger.info(CmdDataStatus.UP_TO_DATE_MSG) diff --git a/dvc/project.py b/dvc/project.py index e1fbb2f0c..91d92fca2 100644 --- a/dvc/project.py +++ b/dvc/project.py @@ -306,12 +306,16 @@ class Project(object): return [stage] def reproduce(self, - target, + target=None, recursive=True, force=False, dry=False, interactive=False, - pipeline=False): + pipeline=False, + all_pipelines=False): + + if target is None and not all_pipelines: + raise ValueError() if not interactive: config = self.config @@ -319,13 +323,18 @@ class Project(object): interactive = core.get(config.SECTION_CORE_INTERACTIVE, False) targets = [] - if pipeline: - stage = Stage.load(self, target) - node = os.path.relpath(stage.path, self.root_dir) - G = self._get_pipeline(node) - for node in G.nodes(): - if G.in_degree(node) == 0: - targets.append(os.path.join(self.root_dir, node)) + if pipeline or all_pipelines: + if pipeline: + stage = Stage.load(self, target) + node = os.path.relpath(stage.path, self.root_dir) + pipelines = [self._get_pipeline(node)] + else: + pipelines = self.pipelines() + + for G in pipelines: + for node in G.nodes(): + if G.in_degree(node) == 0: + targets.append(os.path.join(self.root_dir, node)) else: targets.append(target)
repro: CLI option to reproduce all pipelines https://github.com/iterative/dvc/issues/1107#issuecomment-424420783
iterative/dvc
diff --git a/tests/test_repro.py b/tests/test_repro.py index 75d2e026c..bfe14b9fd 100644 --- a/tests/test_repro.py +++ b/tests/test_repro.py @@ -217,6 +217,49 @@ class TestReproPipeline(TestReproChangedDeepData): self.assertEqual(ret, 0) +class TestReproPipelines(TestDvc): + def setUp(self): + super(TestReproPipelines, self).setUp() + + stages = self.dvc.add(self.FOO) + self.assertEqual(len(stages), 1) + self.foo_stage = stages[0] + self.assertTrue(self.foo_stage is not None) + + stages = self.dvc.add(self.BAR) + self.assertEqual(len(stages), 1) + self.bar_stage = stages[0] + self.assertTrue(self.bar_stage is not None) + + self.file1 = 'file1' + self.file1_stage = self.file1 + '.dvc' + self.dvc.run(fname=self.file1_stage, + outs=[self.file1], + deps=[self.FOO, self.CODE], + cmd='python {} {} {}'.format(self.CODE, self.FOO, self.file1)) + + self.file2 = 'file2' + self.file2_stage = self.file2 + '.dvc' + self.dvc.run(fname=self.file2_stage, + outs=[self.file2], + deps=[self.BAR, self.CODE], + cmd='python {} {} {}'.format(self.CODE, self.BAR, self.file2)) + + + def test(self): + stages = self.dvc.reproduce(all_pipelines=True, force=True) + self.assertEqual(len(stages), 4) + names = [stage.relpath for stage in stages] + self.assertTrue(self.foo_stage.relpath in names) + self.assertTrue(self.bar_stage.relpath in names) + self.assertTrue(self.file1_stage in names) + self.assertTrue(self.file2_stage in names) + + def test_cli(self): + ret = main(['repro', '-f', '-P']) + self.assertEqual(ret, 0) + + class TestReproLocked(TestReproChangedData): def test(self): file2 = 'file2'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 3 }
0.19
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=3.3.1", "nose>=1.3.7", "mock>=2.0.0", "coverage", "codecov", "xmltodict>=0.11.0", "awscli>=1.14.18", "google-compute-engine", "Pygments", "collective.checkdocs", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
altgraph==0.17.4 asciicanvas==0.0.3 attrs==22.2.0 awscli==1.24.10 azure-common==1.1.28 azure-nspkg==3.0.2 azure-storage-blob==1.3.0 azure-storage-common==1.3.0 azure-storage-nspkg==3.1.0 bcrypt==4.0.1 boto==2.49.0 boto3==1.7.4 botocore==1.10.84 cachetools==4.2.4 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 codecov==2.1.13 collective.checkdocs==0.2 colorama==0.4.4 configobj==5.0.8 configparser==5.2.0 coverage==6.2 cryptography==40.0.2 decorator==5.1.1 distro==1.9.0 docutils==0.16 -e git+https://github.com/iterative/dvc.git@04b3cd40e0e8f5373cace8621a0024584010cabe#egg=dvc future==1.0.0 gitdb==4.0.9 GitPython==3.1.18 google-api-core==1.32.0 google-auth==1.35.0 google-cloud-core==0.28.1 google-cloud-storage==1.12.0 google-compute-engine==2.8.13 google-crc32c==1.3.0 google-resumable-media==2.3.3 googleapis-common-protos==1.56.3 grandalf==0.6 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 jmespath==0.10.0 jsonpath-rw==1.4.0 macholib==1.16.3 mock==5.2.0 nanotime==0.5.2 networkx==2.1 nose==1.3.7 ntfsutils==0.1.5 packaging==21.3 paramiko==3.5.1 pefile==2024.8.26 pluggy==1.0.0 ply==3.11 protobuf==3.19.6 py==1.11.0 pyasn1==0.5.1 pyasn1-modules==0.3.0 pycparser==2.21 pydot==1.4.2 Pygments==2.14.0 PyInstaller==3.3.1 PyNaCl==1.5.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==5.4.1 requests==2.27.1 rsa==4.7.2 s3transfer==0.1.13 schema==0.7.7 six==1.17.0 smmap==5.0.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 xmltodict==0.14.2 zc.lockfile==2.0 zipp==3.6.0
name: dvc channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - altgraph==0.17.4 - asciicanvas==0.0.3 - attrs==22.2.0 - awscli==1.24.10 - azure-common==1.1.28 - azure-nspkg==3.0.2 - azure-storage-blob==1.3.0 - azure-storage-common==1.3.0 - azure-storage-nspkg==3.1.0 - bcrypt==4.0.1 - boto==2.49.0 - boto3==1.7.4 - botocore==1.10.84 - cachetools==4.2.4 - cffi==1.15.1 - charset-normalizer==2.0.12 - codecov==2.1.13 - collective-checkdocs==0.2 - colorama==0.4.4 - configobj==5.0.8 - configparser==5.2.0 - coverage==6.2 - cryptography==40.0.2 - decorator==5.1.1 - distro==1.9.0 - docutils==0.16 - future==1.0.0 - gitdb==4.0.9 - gitpython==3.1.18 - google-api-core==1.32.0 - google-auth==1.35.0 - google-cloud-core==0.28.1 - google-cloud-storage==1.12.0 - google-compute-engine==2.8.13 - google-crc32c==1.3.0 - google-resumable-media==2.3.3 - googleapis-common-protos==1.56.3 - grandalf==0.6 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jmespath==0.10.0 - jsonpath-rw==1.4.0 - macholib==1.16.3 - mock==5.2.0 - nanotime==0.5.2 - networkx==2.1 - nose==1.3.7 - ntfsutils==0.1.5 - packaging==21.3 - paramiko==3.5.1 - pefile==2024.8.26 - pluggy==1.0.0 - ply==3.11 - protobuf==3.19.6 - py==1.11.0 - pyasn1==0.5.1 - pyasn1-modules==0.3.0 - pycparser==2.21 - pydot==1.4.2 - pygments==2.14.0 - pyinstaller==3.3.1 - pynacl==1.5.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==5.4.1 - requests==2.27.1 - rsa==4.7.2 - s3transfer==0.1.13 - schema==0.7.7 - six==1.17.0 - smmap==5.0.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - xmltodict==0.14.2 - zc-lockfile==2.0 - zipp==3.6.0 prefix: /opt/conda/envs/dvc
[ "tests/test_repro.py::TestReproPipelines::test", "tests/test_repro.py::TestReproPipelines::test_cli" ]
[ "tests/test_repro.py::TestReproShell::test" ]
[ "tests/test_repro.py::TestReproFail::test", "tests/test_repro.py::TestReproDepUnderDir::test", "tests/test_repro.py::TestReproNoDeps::test", "tests/test_repro.py::TestReproForce::test", "tests/test_repro.py::TestReproChangedCode::test", "tests/test_repro.py::TestReproChangedData::test", "tests/test_repro.py::TestReproDry::test", "tests/test_repro.py::TestReproDryNoExec::test", "tests/test_repro.py::TestReproChangedDeepData::test", "tests/test_repro.py::TestReproPipeline::test", "tests/test_repro.py::TestReproPipeline::test_cli", "tests/test_repro.py::TestReproLocked::test", "tests/test_repro.py::TestReproLocked::test_non_existing", "tests/test_repro.py::TestReproPhony::test", "tests/test_repro.py::TestNonExistingOutput::test", "tests/test_repro.py::TestReproDataSource::test", "tests/test_repro.py::TestReproChangedDir::test", "tests/test_repro.py::TestReproChangedDirData::test", "tests/test_repro.py::TestReproMissingMd5InStageFile::test", "tests/test_repro.py::TestCmdRepro::test", "tests/test_repro.py::TestCmdReproChdir::test", "tests/test_repro.py::TestReproExternalBase::test", "tests/test_repro.py::TestReproExternalS3::test", "tests/test_repro.py::TestReproExternalGS::test", "tests/test_repro.py::TestReproExternalHDFS::test", "tests/test_repro.py::TestReproExternalSSH::test", "tests/test_repro.py::TestReproExternalLOCAL::test" ]
[]
Apache License 2.0
3,144
807
[ "dvc/cli.py", "dvc/command/repro.py", "dvc/project.py" ]
ipython__ipython-11350
194d1d7fe2fcc8547205bd7f54fcf63bee9df4e3
2018-10-01 12:39:06
f0ac04900b586a080b61a2f9ea00c8e9d3a3163b
diff --git a/IPython/core/display.py b/IPython/core/display.py index ca5c3aa5b..4a2e28179 100644 --- a/IPython/core/display.py +++ b/IPython/core/display.py @@ -666,6 +666,11 @@ def _repr_pretty_(self, pp, cycle): class HTML(TextDisplayObject): + def __init__(self, data=None, url=None, filename=None, metadata=None): + if data and "<iframe " in data and "</iframe>" in data: + warnings.warn("Consider using IPython.display.IFrame instead") + super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata) + def _repr_html_(self): return self._data_and_metadata()
HTML vs Iframe I was again the witness of people miss-using HTML to display IFrames, and having issues. Could we detect in HTML the usage of `<iframe>....</iframe>` and warn user that there is an iframe object ?
ipython/ipython
diff --git a/IPython/core/tests/test_display.py b/IPython/core/tests/test_display.py index 3851d6757..7c1f978b4 100644 --- a/IPython/core/tests/test_display.py +++ b/IPython/core/tests/test_display.py @@ -195,6 +195,14 @@ def test_displayobject_repr(): j._show_mem_addr = False nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>') [email protected]('warnings.warn') +def test_encourage_iframe_over_html(m_warn): + display.HTML('<br />') + m_warn.assert_not_called() + + display.HTML('<iframe src="http://a.com"></iframe>') + m_warn.assert_called_with('Consider using IPython.display.IFrame instead') + def test_progress(): p = display.ProgressBar(10) nt.assert_in('0/10',repr(p))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
7.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 backcall==0.2.0 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 decorator==5.2.1 exceptiongroup==1.2.2 execnet==2.1.1 fastjsonschema==2.21.1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==5.5.6 -e git+https://github.com/ipython/ipython.git@194d1d7fe2fcc8547205bd7f54fcf63bee9df4e3#egg=ipython ipython-genutils==0.2.0 jedi==0.19.2 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter_client==8.6.3 jupyter_core==5.7.2 nbformat==5.10.4 nose==1.3.7 numpy==2.0.2 packaging==24.2 parso==0.8.4 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==4.3.7 pluggy==1.5.0 prompt-toolkit==2.0.10 ptyprocess==0.7.0 Pygments==2.19.1 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 pyzmq==26.3.0 referencing==0.36.2 requests==2.32.3 rpds-py==0.24.0 simplegeneric==0.8.1 six==1.17.0 testpath==0.6.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 typing_extensions==4.13.0 urllib3==2.3.0 wcwidth==0.2.13 zipp==3.21.0
name: ipython channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - backcall==0.2.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - decorator==5.2.1 - exceptiongroup==1.2.2 - execnet==2.1.1 - fastjsonschema==2.21.1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==5.5.6 - ipython-genutils==0.2.0 - jedi==0.19.2 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - nbformat==5.10.4 - nose==1.3.7 - numpy==2.0.2 - packaging==24.2 - parso==0.8.4 - pexpect==4.9.0 - pickleshare==0.7.5 - platformdirs==4.3.7 - pluggy==1.5.0 - prompt-toolkit==2.0.10 - ptyprocess==0.7.0 - pygments==2.19.1 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rpds-py==0.24.0 - simplegeneric==0.8.1 - six==1.17.0 - testpath==0.6.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - typing-extensions==4.13.0 - urllib3==2.3.0 - wcwidth==0.2.13 - zipp==3.21.0 prefix: /opt/conda/envs/ipython
[ "IPython/core/tests/test_display.py::test_encourage_iframe_over_html" ]
[ "IPython/core/tests/test_display.py::test_image_mimes", "IPython/core/tests/test_display.py::test_display_available", "IPython/core/tests/test_display.py::test_display_id", "IPython/core/tests/test_display.py::test_update_display", "IPython/core/tests/test_display.py::test_display_handle" ]
[ "IPython/core/tests/test_display.py::test_image_size", "IPython/core/tests/test_display.py::test_geojson", "IPython/core/tests/test_display.py::test_retina_png", "IPython/core/tests/test_display.py::test_retina_jpeg", "IPython/core/tests/test_display.py::test_base64image", "IPython/core/tests/test_display.py::test_image_filename_defaults", "IPython/core/tests/test_display.py::test_textdisplayobj_pretty_repr", "IPython/core/tests/test_display.py::test_displayobject_repr", "IPython/core/tests/test_display.py::test_progress", "IPython/core/tests/test_display.py::test_progress_iter", "IPython/core/tests/test_display.py::test_json", "IPython/core/tests/test_display.py::test_video_embedding", "IPython/core/tests/test_display.py::test_html_metadata" ]
[]
BSD 3-Clause "New" or "Revised" License
3,153
186
[ "IPython/core/display.py" ]
sendgrid__sendgrid-python-618
56a0ad09e7343e0c95321931bea0745927ad61ed
2018-10-01 13:04:52
56a0ad09e7343e0c95321931bea0745927ad61ed
codecov[bot]: # [Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=h1) Report > Merging [#618](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=desc) into [master](https://codecov.io/gh/sendgrid/sendgrid-python/commit/84f7cf258f77f179dce0ef3bee8dc3b90f4af2f3?src=pr&el=desc) will **decrease** coverage by `0.23%`. > The diff coverage is `66.66%`. [![Impacted file tree graph](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618/graphs/tree.svg?width=650&token=Yq0yTs1Nfq&height=150&src=pr)](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #618 +/- ## ========================================== - Coverage 84.77% 84.54% -0.24% ========================================== Files 35 35 Lines 1156 1171 +15 Branches 172 175 +3 ========================================== + Hits 980 990 +10 - Misses 90 93 +3 - Partials 86 88 +2 ``` | [Impacted Files](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [sendgrid/helpers/mail/email.py](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618/diff?src=pr&el=tree#diff-c2VuZGdyaWQvaGVscGVycy9tYWlsL2VtYWlsLnB5) | `88.46% <66.66%> (-8.84%)` | :arrow_down: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=footer). Last update [84f7cf2...dc9b241](https://codecov.io/gh/sendgrid/sendgrid-python/pull/618?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments). thinkingserious: @cmccandless, Could you please merge this agains [this branch](https://github.com/sendgrid/sendgrid-python/tree/v4)? Thanks! With Best Regards, Elmer
diff --git a/sendgrid/helpers/mail/email.py b/sendgrid/helpers/mail/email.py index 0cc6339..432c980 100644 --- a/sendgrid/helpers/mail/email.py +++ b/sendgrid/helpers/mail/email.py @@ -3,6 +3,20 @@ try: except ImportError: import email.utils as rfc822 +import sys +if sys.version_info[:3] >= (3, 5, 0): + import html + html_entity_decode = html.unescape +else: + try: + # Python 2.6-2.7 + from HTMLParser import HTMLParser + except ImportError: + # Python < 3.5 + from html.parser import HTMLParser + __html_parser__ = HTMLParser() + html_entity_decode = __html_parser__.unescape + class Email(object): """An email address with an optional name.""" @@ -35,6 +49,14 @@ class Email(object): @name.setter def name(self, value): + if not (value is None or isinstance(value, str)): + raise TypeError('name must be of type string.') + + # Escape common CSV delimiters as workaround for + # https://github.com/sendgrid/sendgrid-python/issues/578 + if value is not None and (',' in value or ';' in value): + value = html_entity_decode(value) + value = '"' + value + '"' self._name = value @property
JSON quoted comma not ignored #### Issue Summary I'm using a python script to send emails. It mostly works. Comma embedded in quotes are causing the submission to fail. #### Steps to Reproduce The input is a CSV file. "Joe User",[email protected],54321 "User, Joe",[email protected],55555 The second line fails. Python correctly parses the line and formats it as JSON, but it fails on submission. Apparently the quotes on name field are ignored and sees the embedded comma as a delimiter. It then uses User as the name and Joe as the email address and fails. Is this a known bug? Is there a work-around? #### Technical details: * sendgrid-python 5.3.0 * Python Version: 2.7.3
sendgrid/sendgrid-python
diff --git a/test/test_email.py b/test/test_email.py index 902c59d..0604ef2 100644 --- a/test/test_email.py +++ b/test/test_email.py @@ -58,3 +58,10 @@ class TestEmailObject(unittest.TestCase): email.email = address self.assertEqual(email.email, address) + + def test_add_name_with_comma(self): + email = Email() + name = "Name, Some" + email.name = name + + self.assertEqual(email.name, '"' + name + '"')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
5.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 dataclasses==0.8 execnet==1.9.0 Flask==0.10.1 importlib-metadata==4.8.3 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 python-http-client==3.3.7 PyYAML==3.11 -e git+https://github.com/sendgrid/sendgrid-python.git@56a0ad09e7343e0c95321931bea0745927ad61ed#egg=sendgrid six==1.10.0 tomli==1.2.3 typing_extensions==4.1.1 Werkzeug==2.0.3 zipp==3.6.0
name: sendgrid-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - dataclasses==0.8 - execnet==1.9.0 - flask==0.10.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - markupsafe==2.0.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - python-http-client==3.3.7 - pyyaml==3.11 - six==1.10.0 - tomli==1.2.3 - typing-extensions==4.1.1 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/sendgrid-python
[ "test/test_email.py::TestEmailObject::test_add_name_with_comma" ]
[]
[ "test/test_email.py::TestEmailObject::test_add_email_address", "test/test_email.py::TestEmailObject::test_add_name", "test/test_email.py::TestEmailObject::test_add_name_email", "test/test_email.py::TestEmailObject::test_add_rfc_email", "test/test_email.py::TestEmailObject::test_add_rfc_function_finds_name_not_email", "test/test_email.py::TestEmailObject::test_empty_obj_add_email", "test/test_email.py::TestEmailObject::test_empty_obj_add_name" ]
[]
MIT License
3,154
350
[ "sendgrid/helpers/mail/email.py" ]
python-cmd2__cmd2-559
9ca3476df3857cd5c89a5179e0e2578f95cb4425
2018-10-01 21:33:03
60a212c1c585f0c4c06ffcfeb9882520af8dbf35
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 03c71a91..e04138fa 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -2982,6 +2982,8 @@ class Cmd(cmd.Cmd): if self.locals_in_py: self.pystate['self'] = self + elif 'self' in self.pystate: + del self.pystate['self'] localvars = self.pystate from code import InteractiveConsole
py command doesn't properly respect locals_in_py=False if it was ever True Currently the **py** command will have ``self`` accessible forevermore if the ``locals_in_py`` attribute ever gets set to True - changing it back to False will have no effect. Either setting it to False should make ``self`` no longer accessible within **py** OR ``locals_in_py`` should not be a runtime settable parameter.
python-cmd2/cmd2
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index a382a940..3d57a105 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -216,18 +216,35 @@ def test_base_shell(base_app, monkeypatch): assert m.called def test_base_py(base_app, capsys): + # Create a variable and make sure we can see it run_cmd(base_app, 'py qqq=3') out, err = capsys.readouterr() assert out == '' - run_cmd(base_app, 'py print(qqq)') out, err = capsys.readouterr() assert out.rstrip() == '3' + # Add a more complex statement run_cmd(base_app, 'py print("spaces" + " in this " + "command")') out, err = capsys.readouterr() assert out.rstrip() == 'spaces in this command' + # Set locals_in_py to True and make sure we see self + out = run_cmd(base_app, 'set locals_in_py True') + assert 'now: True' in out + + run_cmd(base_app, 'py print(self)') + out, err = capsys.readouterr() + assert 'cmd2.cmd2.Cmd object' in out + + # Set locals_in_py to False and make sure we can't see self + out = run_cmd(base_app, 'set locals_in_py False') + assert 'now: False' in out + + run_cmd(base_app, 'py print(self)') + out, err = capsys.readouterr() + assert "name 'self' is not defined" in err + @pytest.mark.skipif(sys.platform == 'win32', reason="Unit test doesn't work on win32, but feature does")
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "pytest-mock", "pytest-cov", "codecov" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 anyio==4.9.0 astroid==3.3.9 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 -e git+https://github.com/python-cmd2/cmd2.git@9ca3476df3857cd5c89a5179e0e2578f95cb4425#egg=cmd2 codecov==2.1.13 colorama==0.4.6 coverage==7.8.0 cryptography==44.0.2 dill==0.3.9 distlib==0.3.9 docutils==0.21.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 h11==0.14.0 id==1.5.0 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work invoke==2.2.0 isort==6.0.1 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 Jinja2==3.1.6 keyring==25.6.0 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mccabe==0.7.0 mdurl==0.1.2 more-itertools==10.6.0 nh3==0.2.21 packaging @ file:///croot/packaging_1734472117206/work platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work pycparser==2.22 Pygments==2.19.1 pylint==3.3.6 pyperclip==1.9.0 pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work pytest-cov==6.0.0 pytest-mock==3.14.0 readme_renderer==44.0 requests==2.32.3 requests-toolbelt==1.0.0 rfc3986==2.0.0 rich==14.0.0 SecretStorage==3.3.3 sniffio==1.3.1 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-autobuild==2024.10.3 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 starlette==0.46.1 tomli==2.2.1 tomlkit==0.13.2 tox==4.25.0 twine==6.1.0 typing_extensions==4.13.0 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 watchfiles==1.0.4 wcwidth==0.2.13 websockets==15.0.1 zipp==3.21.0
name: cmd2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - anyio==4.9.0 - astroid==3.3.9 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - codecov==2.1.13 - colorama==0.4.6 - coverage==7.8.0 - cryptography==44.0.2 - dill==0.3.9 - distlib==0.3.9 - docutils==0.21.2 - filelock==3.18.0 - h11==0.14.0 - id==1.5.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - invoke==2.2.0 - isort==6.0.1 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - jinja2==3.1.6 - keyring==25.6.0 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mccabe==0.7.0 - mdurl==0.1.2 - more-itertools==10.6.0 - nh3==0.2.21 - platformdirs==4.3.7 - pycparser==2.22 - pygments==2.19.1 - pylint==3.3.6 - pyperclip==1.9.0 - pyproject-api==1.9.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - readme-renderer==44.0 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3986==2.0.0 - rich==14.0.0 - secretstorage==3.3.3 - sniffio==1.3.1 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-autobuild==2024.10.3 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - starlette==0.46.1 - tomli==2.2.1 - tomlkit==0.13.2 - tox==4.25.0 - twine==6.1.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - watchfiles==1.0.4 - wcwidth==0.2.13 - websockets==15.0.1 - zipp==3.21.0 prefix: /opt/conda/envs/cmd2
[ "tests/test_cmd2.py::test_base_py" ]
[ "tests/test_cmd2.py::test_which_editor_good" ]
[ "tests/test_cmd2.py::test_version", "tests/test_cmd2.py::test_empty_statement", "tests/test_cmd2.py::test_base_help", "tests/test_cmd2.py::test_base_help_verbose", "tests/test_cmd2.py::test_base_help_history", "tests/test_cmd2.py::test_base_argparse_help", "tests/test_cmd2.py::test_base_invalid_option", "tests/test_cmd2.py::test_base_shortcuts", "tests/test_cmd2.py::test_base_show", "tests/test_cmd2.py::test_base_show_long", "tests/test_cmd2.py::test_base_show_readonly", "tests/test_cmd2.py::test_cast", "tests/test_cmd2.py::test_cast_problems", "tests/test_cmd2.py::test_base_set", "tests/test_cmd2.py::test_set_not_supported", "tests/test_cmd2.py::test_set_quiet", "tests/test_cmd2.py::test_set_onchange_hook", "tests/test_cmd2.py::test_base_shell", "tests/test_cmd2.py::test_base_run_python_script", "tests/test_cmd2.py::test_base_run_pyscript", "tests/test_cmd2.py::test_recursive_pyscript_not_allowed", "tests/test_cmd2.py::test_pyscript_with_nonexist_file", "tests/test_cmd2.py::test_pyscript_with_exception", "tests/test_cmd2.py::test_pyscript_requires_an_argument", "tests/test_cmd2.py::test_base_error", "tests/test_cmd2.py::test_history_span", "tests/test_cmd2.py::test_history_get", "tests/test_cmd2.py::test_base_history", "tests/test_cmd2.py::test_history_script_format", "tests/test_cmd2.py::test_history_with_string_argument", "tests/test_cmd2.py::test_history_with_integer_argument", "tests/test_cmd2.py::test_history_with_integer_span", "tests/test_cmd2.py::test_history_with_span_start", "tests/test_cmd2.py::test_history_with_span_end", "tests/test_cmd2.py::test_history_with_span_index_error", "tests/test_cmd2.py::test_history_output_file", "tests/test_cmd2.py::test_history_edit", "tests/test_cmd2.py::test_history_run_all_commands", "tests/test_cmd2.py::test_history_run_one_command", "tests/test_cmd2.py::test_history_clear", "tests/test_cmd2.py::test_base_load", "tests/test_cmd2.py::test_load_with_empty_args", "tests/test_cmd2.py::test_load_with_nonexistent_file", "tests/test_cmd2.py::test_load_with_directory", "tests/test_cmd2.py::test_load_with_empty_file", "tests/test_cmd2.py::test_load_with_binary_file", "tests/test_cmd2.py::test_load_with_utf8_file", "tests/test_cmd2.py::test_load_nested_loads", "tests/test_cmd2.py::test_base_runcmds_plus_hooks", "tests/test_cmd2.py::test_base_relative_load", "tests/test_cmd2.py::test_relative_load_requires_an_argument", "tests/test_cmd2.py::test_output_redirection", "tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory", "tests/test_cmd2.py::test_output_redirection_to_too_long_filename", "tests/test_cmd2.py::test_feedback_to_output_true", "tests/test_cmd2.py::test_feedback_to_output_false", "tests/test_cmd2.py::test_allow_redirection", "tests/test_cmd2.py::test_pipe_to_shell", "tests/test_cmd2.py::test_pipe_to_shell_error", "tests/test_cmd2.py::test_base_timing", "tests/test_cmd2.py::test_base_debug", "tests/test_cmd2.py::test_base_colorize", "tests/test_cmd2.py::test_edit_no_editor", "tests/test_cmd2.py::test_edit_file", "tests/test_cmd2.py::test_edit_file_with_spaces", "tests/test_cmd2.py::test_edit_blank", "tests/test_cmd2.py::test_base_py_interactive", "tests/test_cmd2.py::test_exclude_from_history", "tests/test_cmd2.py::test_base_cmdloop_with_queue", "tests/test_cmd2.py::test_base_cmdloop_without_queue", "tests/test_cmd2.py::test_cmdloop_without_rawinput", "tests/test_cmd2.py::test_precmd_hook_success", "tests/test_cmd2.py::test_precmd_hook_failure", "tests/test_cmd2.py::test_interrupt_quit", "tests/test_cmd2.py::test_interrupt_noquit", "tests/test_cmd2.py::test_default_to_shell_unknown", "tests/test_cmd2.py::test_default_to_shell_good", "tests/test_cmd2.py::test_default_to_shell_failure", "tests/test_cmd2.py::test_ansi_prompt_not_esacped", "tests/test_cmd2.py::test_ansi_prompt_escaped", "tests/test_cmd2.py::test_custom_command_help", "tests/test_cmd2.py::test_custom_help_menu", "tests/test_cmd2.py::test_help_undocumented", "tests/test_cmd2.py::test_help_overridden_method", "tests/test_cmd2.py::test_help_cat_base", "tests/test_cmd2.py::test_help_cat_verbose", "tests/test_cmd2.py::test_select_options", "tests/test_cmd2.py::test_select_invalid_option", "tests/test_cmd2.py::test_select_list_of_strings", "tests/test_cmd2.py::test_select_list_of_tuples", "tests/test_cmd2.py::test_select_uneven_list_of_tuples", "tests/test_cmd2.py::test_help_with_no_docstring", "tests/test_cmd2.py::test_which_editor_bad", "tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception", "tests/test_cmd2.py::test_multiline_complete_statement_without_terminator", "tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes", "tests/test_cmd2.py::test_clipboard_failure", "tests/test_cmd2.py::test_commandresult_truthy", "tests/test_cmd2.py::test_commandresult_falsy", "tests/test_cmd2.py::test_is_text_file_bad_input", "tests/test_cmd2.py::test_eof", "tests/test_cmd2.py::test_eos", "tests/test_cmd2.py::test_echo", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false", "tests/test_cmd2.py::test_raw_input", "tests/test_cmd2.py::test_stdin_input", "tests/test_cmd2.py::test_empty_stdin_input", "tests/test_cmd2.py::test_poutput_string", "tests/test_cmd2.py::test_poutput_zero", "tests/test_cmd2.py::test_poutput_empty_string", "tests/test_cmd2.py::test_poutput_none", "tests/test_cmd2.py::test_poutput_color_always", "tests/test_cmd2.py::test_poutput_color_never", "tests/test_cmd2.py::test_get_alias_names", "tests/test_cmd2.py::test_get_macro_names", "tests/test_cmd2.py::test_alias_no_subcommand", "tests/test_cmd2.py::test_alias_create", "tests/test_cmd2.py::test_alias_quoted_name", "tests/test_cmd2.py::test_alias_create_with_quoted_value", "tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]", "tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"no", "tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]", "tests/test_cmd2.py::test_alias_create_with_macro_name", "tests/test_cmd2.py::test_alias_list_invalid_alias", "tests/test_cmd2.py::test_alias_delete", "tests/test_cmd2.py::test_alias_delete_all", "tests/test_cmd2.py::test_alias_delete_non_existing", "tests/test_cmd2.py::test_alias_delete_no_name", "tests/test_cmd2.py::test_multiple_aliases", "tests/test_cmd2.py::test_macro_no_subcommand", "tests/test_cmd2.py::test_macro_create", "tests/test_cmd2.py::test_macro_create_quoted_name", "tests/test_cmd2.py::test_macro_create_with_quoted_value", "tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]", "tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"no", "tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]", "tests/test_cmd2.py::test_macro_create_with_alias_name", "tests/test_cmd2.py::test_macro_create_with_command_name", "tests/test_cmd2.py::test_macro_create_with_args", "tests/test_cmd2.py::test_macro_create_with_escaped_args", "tests/test_cmd2.py::test_macro_create_with_missing_arg_nums", "tests/test_cmd2.py::test_macro_create_with_invalid_arg_num", "tests/test_cmd2.py::test_macro_create_with_wrong_arg_count", "tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg", "tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums", "tests/test_cmd2.py::test_macro_list_invalid_macro", "tests/test_cmd2.py::test_macro_delete", "tests/test_cmd2.py::test_macro_delete_all", "tests/test_cmd2.py::test_macro_delete_non_existing", "tests/test_cmd2.py::test_macro_delete_no_name", "tests/test_cmd2.py::test_multiple_macros", "tests/test_cmd2.py::test_nonexistent_macro", "tests/test_cmd2.py::test_ppaged", "tests/test_cmd2.py::test_parseline_empty", "tests/test_cmd2.py::test_parseline", "tests/test_cmd2.py::test_readline_remove_history_item", "tests/test_cmd2.py::test_onecmd_raw_str_continue", "tests/test_cmd2.py::test_onecmd_raw_str_quit", "tests/test_cmd2.py::test_existing_history_file", "tests/test_cmd2.py::test_new_history_file", "tests/test_cmd2.py::test_bad_history_file_path", "tests/test_cmd2.py::test_get_all_commands", "tests/test_cmd2.py::test_get_help_topics", "tests/test_cmd2.py::test_exit_code_default", "tests/test_cmd2.py::test_exit_code_nonzero", "tests/test_cmd2.py::test_colors_default", "tests/test_cmd2.py::test_colors_pouterr_always_tty", "tests/test_cmd2.py::test_colors_pouterr_always_notty", "tests/test_cmd2.py::test_colors_terminal_tty", "tests/test_cmd2.py::test_colors_terminal_notty", "tests/test_cmd2.py::test_colors_never_tty", "tests/test_cmd2.py::test_colors_never_notty" ]
[]
MIT License
3,156
133
[ "cmd2/cmd2.py" ]
zopefoundation__RestrictedPython-135
ecf62c5116663990c78795ab8b0969874e1bdb3c
2018-10-02 17:59:09
42b4be0237f0990f5a2121d0ca7035be53b87305
diff --git a/src/RestrictedPython/Utilities.py b/src/RestrictedPython/Utilities.py index ad6a1eb..2abb2db 100644 --- a/src/RestrictedPython/Utilities.py +++ b/src/RestrictedPython/Utilities.py @@ -37,8 +37,8 @@ def same_type(arg1, *args): t = getattr(arg1, '__class__', type(arg1)) for arg in args: if getattr(arg, '__class__', type(arg)) is not t: - return 0 - return 1 + return False + return True utility_builtins['same_type'] = same_type
`same_type` should return True resp. False There is no need to return `1` resp. `0` since Python 2.3 we have `True` and `False`.
zopefoundation/RestrictedPython
diff --git a/tests/builtins/test_utilities.py b/tests/builtins/test_utilities.py index d6b0426..e35d1a6 100644 --- a/tests/builtins/test_utilities.py +++ b/tests/builtins/test_utilities.py @@ -76,7 +76,7 @@ def test_sametype_only_two_args_different(): class Foo(object): pass - assert same_type(object(), Foo()) is 0 + assert same_type(object(), Foo()) is False def test_sametype_only_multiple_args_same(): @@ -89,7 +89,7 @@ def test_sametype_only_multipe_args_one_different(): class Foo(object): pass - assert same_type(object(), object(), Foo()) is 0 + assert same_type(object(), object(), Foo()) is False def test_test_single_value_true():
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
4.05
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytest-mock==3.6.1 -e git+https://github.com/zopefoundation/RestrictedPython.git@ecf62c5116663990c78795ab8b0969874e1bdb3c#egg=RestrictedPython tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: RestrictedPython channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/RestrictedPython
[ "tests/builtins/test_utilities.py::test_sametype_only_two_args_different", "tests/builtins/test_utilities.py::test_sametype_only_multipe_args_one_different" ]
[]
[ "tests/builtins/test_utilities.py::test_string_in_utility_builtins", "tests/builtins/test_utilities.py::test_math_in_utility_builtins", "tests/builtins/test_utilities.py::test_whrandom_in_utility_builtins", "tests/builtins/test_utilities.py::test_random_in_utility_builtins", "tests/builtins/test_utilities.py::test_set_in_utility_builtins", "tests/builtins/test_utilities.py::test_frozenset_in_utility_builtins", "tests/builtins/test_utilities.py::test_DateTime_in_utility_builtins_if_importable", "tests/builtins/test_utilities.py::test_same_type_in_utility_builtins", "tests/builtins/test_utilities.py::test_test_in_utility_builtins", "tests/builtins/test_utilities.py::test_reorder_in_utility_builtins", "tests/builtins/test_utilities.py::test_sametype_only_one_arg", "tests/builtins/test_utilities.py::test_sametype_only_two_args_same", "tests/builtins/test_utilities.py::test_sametype_only_multiple_args_same", "tests/builtins/test_utilities.py::test_test_single_value_true", "tests/builtins/test_utilities.py::test_test_single_value_False", "tests/builtins/test_utilities.py::test_test_even_values_first_true", "tests/builtins/test_utilities.py::test_test_even_values_not_first_true", "tests/builtins/test_utilities.py::test_test_odd_values_first_true", "tests/builtins/test_utilities.py::test_test_odd_values_not_first_true", "tests/builtins/test_utilities.py::test_test_odd_values_last_true", "tests/builtins/test_utilities.py::test_test_odd_values_last_false", "tests/builtins/test_utilities.py::test_reorder_with__None", "tests/builtins/test_utilities.py::test_reorder_with__not_None" ]
[]
Zope Public License 2.1
3,164
150
[ "src/RestrictedPython/Utilities.py" ]
oasis-open__cti-taxii-server-44
c99f8dcd93ad5f06174fc2767771acd491bedaaa
2018-10-04 01:26:04
c99f8dcd93ad5f06174fc2767771acd491bedaaa
diff --git a/medallion/backends/memory_backend.py b/medallion/backends/memory_backend.py index 8da67b0..b07ae14 100644 --- a/medallion/backends/memory_backend.py +++ b/medallion/backends/memory_backend.py @@ -163,22 +163,23 @@ class MemoryBackend(Backend): try: for new_obj in objs["objects"]: id_and_version_already_present = False - if new_obj["id"] in collection["objects"]: - current_obj = collection["objects"][new_obj["id"]] - if "modified" in new_obj: - if new_obj["modified"] == current_obj["modified"]: + for obj in collection["objects"]: + id_and_version_already_present = False + + if new_obj['id'] == obj['id']: + if "modified" in new_obj: + if new_obj["modified"] == obj["modified"]: + id_and_version_already_present = True + else: + # There is no modified field, so this object is immutable id_and_version_already_present = True - else: - # There is no modified field, so this object is immutable - id_and_version_already_present = True if not id_and_version_already_present: collection["objects"].append(new_obj) self._update_manifest(new_obj, api_root, collection["id"]) successes.append(new_obj["id"]) succeeded += 1 else: - failures.append({"id": new_obj["id"], - "message": "Unable to process object"}) + failures.append({"id": new_obj["id"], "message": "Unable to process object"}) failed += 1 except Exception as e: raise ProcessingError("While processing supplied content, an error occured", e)
BUG: checking new object IDs as existing already always fail https://github.com/oasis-open/cti-taxii-server/blob/f6398926d866989201e754dca0fec1e1a041acdf/medallion/backends/memory_backend.py#L166 This line will always fail, you're checking that the ID of the object belongs in the array of objects instead of checking if the ID of the object exists as the ID of _any_ of the objects
oasis-open/cti-taxii-server
diff --git a/medallion/test/test_memory_backend.py b/medallion/test/test_memory_backend.py index a23b9f1..7c9f982 100644 --- a/medallion/test/test_memory_backend.py +++ b/medallion/test/test_memory_backend.py @@ -207,6 +207,54 @@ class TestTAXIIServerWithMemoryBackend(unittest.TestCase): assert manifests["objects"][0]["id"] == new_id # ------------- BEGIN: end manifest section ------------- # + def test_add_existing_objects(self): + new_bundle = copy.deepcopy(API_OBJECTS_2) + new_id = "indicator--%s" % uuid.uuid4() + new_bundle["objects"][0]["id"] = new_id + + # ------------- BEGIN: add object section ------------- # + + post_header = copy.deepcopy(self.auth) + post_header["Content-Type"] = MEDIA_TYPE_STIX_V20 + post_header["Accept"] = MEDIA_TYPE_TAXII_V20 + + r_post = self.client.post( + test.ADD_OBJECTS_EP, + data=json.dumps(new_bundle), + headers=post_header + ) + self.assertEqual(r_post.status_code, 202) + self.assertEqual(r_post.content_type, MEDIA_TYPE_TAXII_V20) + + # ------------- END: add object section ------------- # + # ------------- BEGIN: add object again section ------------- # + + r_post = self.client.post( + test.ADD_OBJECTS_EP, + data=json.dumps(new_bundle), + headers=post_header + ) + status_response2 = self.load_json_response(r_post.data) + self.assertEqual(r_post.status_code, 202) + self.assertEqual(status_response2["success_count"], 0) + self.assertEqual(status_response2["failures"][0]["message"], + "Unable to process object") + + # ------------- END: add object again section ------------- # + # ------------- BEGIN: get object section ------------- # + + get_header = copy.deepcopy(self.auth) + get_header["Accept"] = MEDIA_TYPE_STIX_V20 + + r_get = self.client.get( + test.GET_OBJECTS_EP + "?match[id]=%s" % new_id, + headers=get_header + ) + self.assertEqual(r_get.status_code, 200) + objs = self.load_json_response(r_get.data) + self.assertEqual(len(objs["objects"]), 1) + self.assertEqual(objs["objects"][0]["id"], new_id) + def test_client_object_versioning(self): new_id = "indicator--%s" % uuid.uuid4() new_bundle = copy.deepcopy(API_OBJECTS_2)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[docs,test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "responses" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 dataclasses==0.8 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 Flask==2.0.3 Flask-HTTPAuth==4.8.0 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 itsdangerous==2.0.1 Jinja2==3.0.3 MarkupSafe==2.0.1 -e git+https://github.com/oasis-open/cti-taxii-server.git@c99f8dcd93ad5f06174fc2767771acd491bedaaa#egg=medallion packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytz==2025.2 requests==2.27.1 responses==0.17.0 six==1.17.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 Werkzeug==2.0.3 zipp==3.6.0
name: cti-taxii-server channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - dataclasses==0.8 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - flask==2.0.3 - flask-httpauth==4.8.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - itsdangerous==2.0.1 - jinja2==3.0.3 - markupsafe==2.0.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytz==2025.2 - requests==2.27.1 - responses==0.17.0 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - werkzeug==2.0.3 - zipp==3.6.0 prefix: /opt/conda/envs/cti-taxii-server
[ "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_add_existing_objects" ]
[]
[ "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_add_objects", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_added_after_filtering", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_client_object_versioning", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_api_root_information", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_api_root_information_not_existent", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_collection", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_collection_not_existent", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_collections", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_collections_401", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_collections_404", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_401", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_403", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_404", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_manifest_401", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_manifest_403", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_object_manifest_404", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_objects", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_or_add_objects_401", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_or_add_objects_403", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_or_add_objects_404", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_or_add_objects_422", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_status_401", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_get_status_404", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_saving_data_file", "medallion/test/test_memory_backend.py::TestTAXIIServerWithMemoryBackend::test_server_discovery" ]
[]
BSD 3-Clause "New" or "Revised" License
3,170
410
[ "medallion/backends/memory_backend.py" ]
iterait__emloop-23
1aa92eccfce433e0e7b7a156ebe850cd2e3a607e
2018-10-04 07:19:12
1aa92eccfce433e0e7b7a156ebe850cd2e3a607e
diff --git a/emloop/constants.py b/emloop/constants.py index 0249a86..5ebf78b 100644 --- a/emloop/constants.py +++ b/emloop/constants.py @@ -33,9 +33,9 @@ EL_NA_STR = 'N/A' EL_BUFFER_SLEEP = 0.02 """The duration for which the buffer sleeps before it starts to process the next batch.""" -EL_TRAIN_STREAM = 'train' +EL_DEFAULT_TRAIN_STREAM = 'train' """The stream to be used for training.""" __all__ = ['EL_LOG_FORMAT', 'EL_LOG_DATE_FORMAT', 'EL_FULL_DATE_FORMAT', 'EL_HOOKS_MODULE', 'EL_CONFIG_FILE', - 'EL_LOG_FILE', 'EL_TRACE_FILE', 'EL_TRAIN_STREAM', 'EL_PREDICT_STREAM', 'EL_DEFAULT_LOG_DIR', + 'EL_LOG_FILE', 'EL_TRACE_FILE', 'EL_DEFAULT_TRAIN_STREAM', 'EL_PREDICT_STREAM', 'EL_DEFAULT_LOG_DIR', 'EL_NA_STR', 'EL_BUFFER_SLEEP'] diff --git a/emloop/hooks/abstract_hook.py b/emloop/hooks/abstract_hook.py index 039f3cd..7ecb928 100644 --- a/emloop/hooks/abstract_hook.py +++ b/emloop/hooks/abstract_hook.py @@ -81,7 +81,7 @@ class AbstractHook: """ pass - def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, extra_streams: Iterable[str]) -> None: + def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None: """ After epoch profile event. diff --git a/emloop/hooks/log_profile.py b/emloop/hooks/log_profile.py index 028bb61..dd77b55 100644 --- a/emloop/hooks/log_profile.py +++ b/emloop/hooks/log_profile.py @@ -24,13 +24,13 @@ class LogProfile(AbstractHook): """ - def after_epoch_profile(self, epoch_id, profile: TimeProfile, extra_streams: Iterable[str]) -> None: + def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None: """ Summarize and log the given epoch profile. The profile is expected to contain at least: - ``read_data_train``, ``eval_batch_train`` and ``after_batch_hooks_train`` entries produced by the train - stream + stream (if train stream name is `train`) - ``after_epoch_hooks`` entry :param profile: epoch timings profile @@ -39,13 +39,13 @@ class LogProfile(AbstractHook): read_data_total = 0 eval_total = 0 - train_total = sum(profile.get('eval_batch_train', [])) + train_total = sum(profile.get('eval_batch_{}'.format(train_stream_name), [])) hooks_total = sum(profile.get('after_epoch_hooks', [])) - for stream_name in chain(extra_streams, ['train']): + for stream_name in chain(extra_streams, [train_stream_name]): read_data_total += sum(profile.get('read_batch_' + stream_name, [])) hooks_total += sum(profile.get('after_batch_hooks_' + stream_name, [])) - if stream_name != 'train': + if stream_name != train_stream_name: eval_total += sum(profile.get('eval_batch_' + stream_name, [])) logging.info('\tT read data:\t%f', read_data_total) diff --git a/emloop/hooks/stop_after.py b/emloop/hooks/stop_after.py index c0d821f..d2c2348 100644 --- a/emloop/hooks/stop_after.py +++ b/emloop/hooks/stop_after.py @@ -6,7 +6,7 @@ from datetime import datetime from typing import Optional from . import AbstractHook, TrainingTerminated -from ..constants import EL_TRAIN_STREAM +from ..constants import EL_DEFAULT_TRAIN_STREAM from ..types import EpochData, Batch @@ -32,7 +32,7 @@ class StopAfter(AbstractHook): """ def __init__(self, epochs: Optional[int]=None, iterations: Optional[int]=None, minutes: Optional[float]=None, - **kwargs): + train_stream_name: str=EL_DEFAULT_TRAIN_STREAM, **kwargs): """ Create new StopAfter hook. @@ -67,6 +67,7 @@ class StopAfter(AbstractHook): self._minutes = minutes self._iters_done = 0 self._training_start = None + self._train_stream_name = train_stream_name def _check_train_time(self) -> None: """ @@ -91,7 +92,7 @@ class StopAfter(AbstractHook): :raise TrainingTerminated: if the number of iterations reaches ``self._iters`` """ self._check_train_time() - if self._iters is not None and stream_name == EL_TRAIN_STREAM: + if self._iters is not None and stream_name == self._train_stream_name: self._iters_done += 1 if self._iters_done >= self._iters: raise TrainingTerminated('Training terminated after iteration {}'.format(self._iters_done)) diff --git a/emloop/main_loop.py b/emloop/main_loop.py index ba8fcce..a0d906b 100644 --- a/emloop/main_loop.py +++ b/emloop/main_loop.py @@ -14,7 +14,7 @@ from .hooks.abstract_hook import AbstractHook, TrainingTerminated from .utils import Timer, TrainingTrace, TrainingTraceKeys from .utils.misc import CaughtInterrupts from .datasets.stream_wrapper import StreamWrapper -from .constants import EL_TRAIN_STREAM, EL_PREDICT_STREAM +from .constants import EL_DEFAULT_TRAIN_STREAM, EL_PREDICT_STREAM from .types import EpochData @@ -29,6 +29,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut def __init__(self, # pylint: disable=too-many-arguments model: AbstractModel, dataset: AbstractDataset, hooks: Iterable[AbstractHook]=(), + train_stream_name: str=EL_DEFAULT_TRAIN_STREAM, extra_streams: List[str]=(), # pylint: disable=invalid-sequence-index buffer: int=0, on_empty_batch: str='error', @@ -41,6 +42,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut :param model: trained model :param dataset: loaded dataset :param hooks: training hooks + :param train_stream_name: name of the training stream :param extra_streams: additional stream names to be evaluated between epochs :param buffer: size of the batch buffer, 0 means no buffer :param on_empty_batch: action to take when batch is empty; one of :py:attr:`MainLoop.EMPTY_ACTIONS` @@ -68,6 +70,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut self._fixed_epoch_size = fixed_epoch_size self._extra_sources_warned = False self._epoch_profile = {} + self._train_stream_name = train_stream_name self._extra_streams = list(extra_streams) self._skip_zeroth_epoch = skip_zeroth_epoch self._streams = {} @@ -93,7 +96,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData: """Create empty epoch data double dict.""" if streams is None: - streams = [EL_TRAIN_STREAM] + self._extra_streams + streams = [self._train_stream_name] + self._extra_streams return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) def _check_sources(self, batch: Dict[str, object]) -> None: @@ -206,7 +209,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut try: stream_fn = getattr(self._dataset, stream_fn_name) stream_epoch_limit = -1 - if self._fixed_epoch_size is not None and stream_name == EL_TRAIN_STREAM: + if self._fixed_epoch_size is not None and stream_name == self._train_stream_name: stream_epoch_limit = self._fixed_epoch_size self._streams[stream_name] = StreamWrapper(stream_fn, buffer_size=self._buffer, epoch_size=stream_epoch_limit, name=stream_name, @@ -264,7 +267,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut - :py:meth:`emloop.hooks.AbstractHook.after_epoch` - :py:meth:`emloop.hooks.AbstractHook.after_epoch_profile` """ - for stream_name in [EL_TRAIN_STREAM] + self._extra_streams: + for stream_name in [self._train_stream_name] + self._extra_streams: self.get_stream(stream_name) def training(): @@ -274,7 +277,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut # Zeroth epoch: after_epoch if not self._skip_zeroth_epoch: logging.info('Evaluating 0th epoch') - self._run_zeroth_epoch([EL_TRAIN_STREAM] + self._extra_streams) + self._run_zeroth_epoch([self._train_stream_name] + self._extra_streams) logging.info('0th epoch done\n\n') # Training loop: after_epoch, after_epoch_profile @@ -284,7 +287,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut self._epoch_profile.clear() epoch_data = self._create_epoch_data() - with self.get_stream(EL_TRAIN_STREAM) as stream: + with self.get_stream(self._train_stream_name) as stream: self.train_by_stream(stream) for stream_name in self._extra_streams: @@ -297,6 +300,7 @@ class MainLoop(CaughtInterrupts): # pylint: disable=too-many-instance-attribut for hook in self._hooks: hook.after_epoch_profile(epoch_id=epoch_id, profile=self._epoch_profile, + train_stream_name=self._train_stream_name, extra_streams=self._extra_streams) self._epochs_done = epoch_id if trace is not None:
Specify the name of the training stream in the config Migrated from [https://github.com/Cognexa/cxflow/issues/190](https://github.com/Cognexa/cxflow/issues/190). It would be pretty nice to have a single dataset with let's say two trainign streams (generative and regular one). One would be able to pre-train the model on the generated data and then (in the separate training) finetune it on the real data. Implementing this would make cxflow be more consistent with other streams that are easily configurable. Config suggestion: ``` main_loop: train_stream: train # or generative_train ```
iterait/emloop
diff --git a/emloop/tests/hooks/log_profile_test.py b/emloop/tests/hooks/log_profile_test.py index 0d79e1f..e767f4b 100644 --- a/emloop/tests/hooks/log_profile_test.py +++ b/emloop/tests/hooks/log_profile_test.py @@ -2,6 +2,7 @@ Module with profile hook test case (see :py:class:`emloop.hooks.LogProfile`). """ import logging +from emloop.constants import EL_DEFAULT_TRAIN_STREAM from emloop.hooks import LogProfile @@ -45,7 +46,7 @@ class TestLogProfile: """Test KeyError raised on missing profile entries.""" caplog.set_level(logging.INFO) - self._hook.after_epoch_profile(0, {}, []) + self._hook.after_epoch_profile(0, {}, EL_DEFAULT_TRAIN_STREAM, []) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t0.000000'), ('root', logging.INFO, '\tT train:\t0.000000'), @@ -54,7 +55,7 @@ class TestLogProfile: ] caplog.clear() - self._hook.after_epoch_profile(0, {'some_contents': 1}, []) + self._hook.after_epoch_profile(0, {'some_contents': 1}, EL_DEFAULT_TRAIN_STREAM, []) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t0.000000'), ('root', logging.INFO, '\tT train:\t0.000000'), @@ -66,7 +67,7 @@ class TestLogProfile: """Test profile handling with only train stream.""" caplog.set_level(logging.INFO) - self._hook.after_epoch_profile(1, _TRAIN_ONLY_PROFILE, []) + self._hook.after_epoch_profile(1, _TRAIN_ONLY_PROFILE, EL_DEFAULT_TRAIN_STREAM, []) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t6.120000'), ('root', logging.INFO, '\tT train:\t21.900000'), @@ -78,7 +79,7 @@ class TestLogProfile: """Test extra streams handling.""" caplog.set_level(logging.INFO) - self._hook.after_epoch_profile(0, _TRAIN_ONLY_PROFILE, ['valid']) + self._hook.after_epoch_profile(0, _TRAIN_ONLY_PROFILE, EL_DEFAULT_TRAIN_STREAM, ['valid']) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t6.120000'), ('root', logging.INFO, '\tT train:\t21.900000'), @@ -88,7 +89,7 @@ class TestLogProfile: # test additional entries being ignored if the extra stream was not specified caplog.clear() - self._hook.after_epoch_profile(1, _TRAIN_AND_VALID_PROFILE, []) + self._hook.after_epoch_profile(1, _TRAIN_AND_VALID_PROFILE, EL_DEFAULT_TRAIN_STREAM, []) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t6.001000'), ('root', logging.INFO, '\tT train:\t21.540000'), @@ -98,7 +99,7 @@ class TestLogProfile: # test one additional stream caplog.clear() - self._hook.after_epoch_profile(1, _TRAIN_AND_VALID_PROFILE, ['valid']) + self._hook.after_epoch_profile(1, _TRAIN_AND_VALID_PROFILE, EL_DEFAULT_TRAIN_STREAM, ['valid']) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t20.001000'), ('root', logging.INFO, '\tT train:\t21.540000'), @@ -108,7 +109,7 @@ class TestLogProfile: # test two additional streams caplog.clear() - self._hook.after_epoch_profile(1, _TRAIN_TEST_AND_VALID_PROFILE, ['valid', 'test']) + self._hook.after_epoch_profile(1, _TRAIN_TEST_AND_VALID_PROFILE, EL_DEFAULT_TRAIN_STREAM, ['valid', 'test']) assert caplog.record_tuples == [ ('root', logging.INFO, '\tT read data:\t23.322000'), ('root', logging.INFO, '\tT train:\t21.540000'), diff --git a/emloop/tests/hooks/stop_after_test.py b/emloop/tests/hooks/stop_after_test.py index 22c3daa..80f806f 100644 --- a/emloop/tests/hooks/stop_after_test.py +++ b/emloop/tests/hooks/stop_after_test.py @@ -6,11 +6,11 @@ import time from emloop.main_loop import MainLoop from emloop.hooks.stop_after import StopAfter from emloop.hooks.abstract_hook import TrainingTerminated -from emloop.constants import EL_TRAIN_STREAM +from emloop.constants import EL_DEFAULT_TRAIN_STREAM import pytest NOTRAIN_STREAM_NAME = 'valid' -assert EL_TRAIN_STREAM is not NOTRAIN_STREAM_NAME +assert EL_DEFAULT_TRAIN_STREAM != NOTRAIN_STREAM_NAME def test_no_conditions_raise(): @@ -41,13 +41,13 @@ def test_stop_after_iters(): hook.after_batch(stream_name=NOTRAIN_STREAM_NAME, batch_data=None) for i in range(9): - hook.after_batch(stream_name=EL_TRAIN_STREAM, batch_data=None) + hook.after_batch(stream_name=EL_DEFAULT_TRAIN_STREAM, batch_data=None) hook.after_batch(stream_name=NOTRAIN_STREAM_NAME, batch_data=None) # Test hook does terminate the training correctly with pytest.raises(TrainingTerminated): - hook.after_batch(stream_name=EL_TRAIN_STREAM, batch_data=None) + hook.after_batch(stream_name=EL_DEFAULT_TRAIN_STREAM, batch_data=None) def test_stop_after_minutes(): diff --git a/emloop/tests/main_loop_test.py b/emloop/tests/main_loop_test.py index 0e30fdc..32a3210 100644 --- a/emloop/tests/main_loop_test.py +++ b/emloop/tests/main_loop_test.py @@ -10,7 +10,7 @@ import logging import numpy as np import emloop as el -from emloop.constants import EL_BUFFER_SLEEP, EL_PREDICT_STREAM +from emloop.constants import EL_BUFFER_SLEEP, EL_PREDICT_STREAM, EL_DEFAULT_TRAIN_STREAM from emloop.datasets import StreamWrapper from emloop.hooks import StopAfter from emloop.types import EpochData, Batch, Stream, TimeProfile @@ -124,6 +124,17 @@ class AllEmptyBatchDataset(SimpleDataset): yield {'input': [], 'target': []} +class GeneratedStreamDataset(SimpleDataset): + """SimpleDataset with generated stream instead of train stream.""" + + def generated_stream(self) -> Stream: + for _ in range(self.iters): + yield {'input': np.ones(self.shape), 'target': np.zeros(self.shape)} + + def train_stream(self) -> Stream: + assert False + + class EventRecordingHook(el.AbstractHook): """EventRecordingHook records all the events and store their count and order.""" @@ -148,7 +159,8 @@ class EventRecordingHook(el.AbstractHook): self.after_epoch_events.append(self._event_id) self._event_id += 1 - def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, extra_streams: Iterable[str]) -> None: + def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, + extra_streams: Iterable[str]) -> None: self.after_epoch_profile_events.append(self._event_id) self._event_id += 1 @@ -189,7 +201,8 @@ class SaveProfileHook(el.AbstractHook): super().__init__() self.profile = None - def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, extra_streams: Iterable[str]) -> None: + def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, + extra_streams: Iterable[str]) -> None: """Save the profile to self.profile.""" self.profile = profile @@ -280,7 +293,7 @@ class RecordingModel(TrainableModel): def create_main_loop(tmpdir): def _create_main_loop(epochs=1, extra_hooks=(), dataset=None, model_class=None, skip_zeroth_epoch=True, - **main_loop_kwargs): + train_stream_name=EL_DEFAULT_TRAIN_STREAM, **main_loop_kwargs): """ Create and return a model, dataset and mainloop. @@ -291,6 +304,7 @@ def create_main_loop(tmpdir): :param dataset: dataset to be passed to the main loop, SimpleDataset() is created if None :param model_class: model class to be created and passed to the main loop, TrainableModel if None :param skip_zeroth_epoch: skip zeroth epoch flag passed to the main loop + :param train_stream_name: name of the training stream :return: a tuple of the created model, dataset and mainloop """ hooks = list(extra_hooks) + [StopAfter(epochs=epochs)] @@ -300,8 +314,8 @@ def create_main_loop(tmpdir): model_class = TrainableModel model = model_class(dataset=dataset, log_dir=tmpdir, # pylint: disable=redefined-variable-type io={'in': ['input', 'target'], 'out': ['output']}) - mainloop = el.MainLoop(model=model, dataset=dataset, hooks=hooks, - skip_zeroth_epoch=skip_zeroth_epoch, **main_loop_kwargs) + mainloop = el.MainLoop(model=model, dataset=dataset, hooks=hooks, skip_zeroth_epoch=skip_zeroth_epoch, + train_stream_name=train_stream_name, **main_loop_kwargs) return model, dataset, mainloop return _create_main_loop @@ -578,3 +592,31 @@ def test_stream_check(create_main_loop, caplog): 'with `main_loop.fixed_size` = 47'), ('root', logging.INFO, 'Prediction done\n\n') ] + + +def test_configurable_train_stream(create_main_loop, caplog): + caplog.set_level(logging.DEBUG) + + caplog.clear() + _, _, mainloop = create_main_loop(dataset=EmptyStreamDataset(), train_stream_name='valid', on_empty_stream='warn') + mainloop.run_training() + + assert caplog.record_tuples == [ + ('root', logging.DEBUG, 'Training started'), + ('root', logging.INFO, 'Training epoch 1'), + ('root', logging.WARNING, 'Stream `valid` appears to be empty. Set `main_loop.on_empty_stream` to ' + '`ignore` in order to suppress this warning.'), + ('root', logging.INFO, 'EpochStopperHook triggered'), + ('root', logging.INFO, 'Training terminated: Training terminated after epoch 1') + ] + + caplog.clear() + _, _, mainloop = create_main_loop(dataset=GeneratedStreamDataset(), train_stream_name='generated') + mainloop.run_training() + + assert caplog.record_tuples == [ + ('root', logging.DEBUG, 'Training started'), + ('root', logging.INFO, 'Training epoch 1'), + ('root', logging.INFO, 'EpochStopperHook triggered'), + ('root', logging.INFO, 'Training terminated: Training terminated after epoch 1') + ]
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 5 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 cycler==0.11.0 -e git+https://github.com/iterait/emloop.git@1aa92eccfce433e0e7b7a156ebe850cd2e3a607e#egg=emloop idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 kiwisolver==1.3.1 matplotlib==3.3.4 numpy==1.19.5 packaging==21.3 Pillow==8.4.0 pluggy==1.0.0 py==1.11.0 pyaml==23.5.8 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.1 requests==2.27.1 ruamel.yaml==0.18.3 ruamel.yaml.clib==0.2.8 six==1.17.0 tabulate==0.8.10 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: emloop channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - cycler==0.11.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - kiwisolver==1.3.1 - matplotlib==3.3.4 - numpy==1.19.5 - packaging==21.3 - pillow==8.4.0 - pluggy==1.0.0 - py==1.11.0 - pyaml==23.5.8 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.1 - requests==2.27.1 - ruamel-yaml==0.18.3 - ruamel-yaml-clib==0.2.8 - six==1.17.0 - tabulate==0.8.10 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/emloop
[ "emloop/tests/hooks/log_profile_test.py::TestLogProfile::test_missing_train", "emloop/tests/hooks/log_profile_test.py::TestLogProfile::test_train_only", "emloop/tests/hooks/log_profile_test.py::TestLogProfile::test_extra_streams", "emloop/tests/hooks/stop_after_test.py::test_no_conditions_raise", "emloop/tests/hooks/stop_after_test.py::test_stop_after_epochs", "emloop/tests/hooks/stop_after_test.py::test_stop_after_iters", "emloop/tests/hooks/stop_after_test.py::test_stop_after_minutes", "emloop/tests/main_loop_test.py::test_events", "emloop/tests/main_loop_test.py::test_event_data", "emloop/tests/main_loop_test.py::test_stream_usage", "emloop/tests/main_loop_test.py::test_profiling", "emloop/tests/main_loop_test.py::test_zeroth_epoch", "emloop/tests/main_loop_test.py::test_on_unused_sources", "emloop/tests/main_loop_test.py::test_epoch_data", "emloop/tests/main_loop_test.py::test_epoch_data_predict", "emloop/tests/main_loop_test.py::test_predict", "emloop/tests/main_loop_test.py::test_buffer", "emloop/tests/main_loop_test.py::test_stream_check", "emloop/tests/main_loop_test.py::test_configurable_train_stream" ]
[]
[]
[]
MIT License
3,172
2,429
[ "emloop/constants.py", "emloop/hooks/abstract_hook.py", "emloop/hooks/log_profile.py", "emloop/hooks/stop_after.py", "emloop/main_loop.py" ]
jupyter__nbgrader-1019
fa75fcb2fb7fa24451966b5ae2a44480f88d508b
2018-10-04 08:30:30
5bc6f37c39c8b10b8f60440b2e6d9487e63ef3f1
diff --git a/nbgrader/apps/quickstartapp.py b/nbgrader/apps/quickstartapp.py index 462e1cd7..62d57441 100644 --- a/nbgrader/apps/quickstartapp.py +++ b/nbgrader/apps/quickstartapp.py @@ -79,6 +79,14 @@ class QuickStartApp(NbGrader): classes.append(QuickStartApp) return classes + def _course_folder_content_exists(self, course_path): + course_folder_content = { + "source_dir": os.path.join(course_path, "source"), + "config_file": os.path.join(course_path, "nbgrader_config.py") + } + exists = os.path.isdir(course_folder_content['source_dir']) or os.path.isfile(course_folder_content['config_file']) + return exists + def start(self): super(QuickStartApp, self).start() @@ -89,19 +97,23 @@ class QuickStartApp(NbGrader): # make sure it doesn't exist course_id = self.extra_args[0] course_path = os.path.abspath(course_id) + if os.path.exists(course_path): if self.force: self.log.warning("Removing existing directory '%s'", course_path) utils.rmtree(course_path) else: - self.fail( - "Directory '{}' already exists! Rerun with --force to remove " - "this directory first (warning: this will remove the ENTIRE " - "directory and all files in it.) ".format(course_path)) + if self._course_folder_content_exists(course_path): + self.fail( + "Directory '{}' and it's content already exists! Rerun with --force to remove " + "this directory first (warning: this will remove the ENTIRE " + "directory and all files in it.) ".format(course_path)) # create the directory self.log.info("Creating directory '%s'...", course_path) - os.mkdir(course_path) + + if not os.path.isdir(course_path): + os.mkdir(course_path) # populating it with an example self.log.info("Copying example from the user guide...")
Allow nbgrader quickstart to work on an existing directory Rather than refusing to run if the directory exists, quickstart should check if it is going to overwrite any files and if it is only then throw an error. cc @ncclementi
jupyter/nbgrader
diff --git a/nbgrader/tests/apps/test_nbgrader_quickstart.py b/nbgrader/tests/apps/test_nbgrader_quickstart.py index d9a9f705..f8257119 100644 --- a/nbgrader/tests/apps/test_nbgrader_quickstart.py +++ b/nbgrader/tests/apps/test_nbgrader_quickstart.py @@ -1,5 +1,5 @@ import os -import sys +import shutil from .. import run_nbgrader from .base import BaseTestApp @@ -39,6 +39,61 @@ class TestNbGraderQuickStart(BaseTestApp): # nbgrader assign should work run_nbgrader(["assign", "ps1"]) + def test_quickstart_overwrite_course_folder_if_structure_not_present(self): + """Is the quickstart example properly generated?""" + + run_nbgrader(["quickstart", "example_without_folder_and_config_file"]) + + # it should fail if it already exists + run_nbgrader(["quickstart", "example_without_folder_and_config_file"], retcode=1) + + # should succeed if both source folder and config file are not present. + shutil.rmtree(os.path.join("example_without_folder_and_config_file", "source")) + os.remove(os.path.join("example_without_folder_and_config_file", "nbgrader_config.py")) + + run_nbgrader(["quickstart", "example_without_folder_and_config_file"]) + assert os.path.exists(os.path.join("example_without_folder_and_config_file", "nbgrader_config.py")) + assert os.path.exists(os.path.join("example_without_folder_and_config_file", "source")) + + # nbgrader validate should work + os.chdir("example_without_folder_and_config_file") + for nb in os.listdir(os.path.join("source", "ps1")): + if not nb.endswith(".ipynb"): + continue + output = run_nbgrader(["validate", os.path.join("source", "ps1", nb)], stdout=True) + assert output.strip() == "Success! Your notebook passes all the tests." + + # nbgrader assign should work + run_nbgrader(["assign", "ps1"]) + + def test_quickstart_fails_with_source_folder_removed(self): + """Is the quickstart example properly generated if source folder removed?""" + + run_nbgrader(["quickstart", "example_source_folder_fail"]) + + # it should fail if it already exists + run_nbgrader(["quickstart", "example_source_folder_fail"], retcode=1) + + # it should succeed if source folder not present and create it + shutil.rmtree(os.path.join("example_source_folder_fail", "source")) + + # it should fail if it already source folder or config file exists + run_nbgrader(["quickstart", "example_source_folder_fail"], retcode=1) + + def test_quickstart_fails_with_config_file_removed(self): + """Is the quickstart example properly generated if source folder removed?""" + + run_nbgrader(["quickstart", "example_source_folder_fail"]) + + # it should fail if it already exists + run_nbgrader(["quickstart", "example_source_folder_fail"], retcode=1) + + # it should succeed if source folder not present and create it + os.remove(os.path.join("example_source_folder_fail", "nbgrader_config.py")) + + # it should fail if it already source folder or config file exists + run_nbgrader(["quickstart", "example_source_folder_fail"], retcode=1) + def test_quickstart_f(self): """Is the quickstart example properly generated?"""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -r dev-requirements.txt -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-rerunfailures", "coverage", "selenium", "invoke", "sphinx", "codecov", "cov-core", "nbval" ], "pre_install": [ "pip install -U pip wheel setuptools" ], "python": "3.5", "reqs_path": [ "dev-requirements.txt", "dev-requirements-windows.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 alembic==1.7.7 anyio==3.6.2 argon2-cffi==21.3.0 argon2-cffi-bindings==21.2.0 async-generator==1.10 attrs==22.2.0 Babel==2.11.0 backcall==0.2.0 bleach==4.1.0 certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 codecov==2.1.13 comm==0.1.4 contextvars==2.4 cov-core==1.15.0 coverage==6.2 dataclasses==0.8 decorator==5.1.1 defusedxml==0.7.1 docutils==0.18.1 entrypoints==0.4 fuzzywuzzy==0.18.0 greenlet==2.0.2 idna==3.10 imagesize==1.4.1 immutables==0.19 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 invoke==2.2.0 ipykernel==5.5.6 ipython==7.16.3 ipython-genutils==0.2.0 ipywidgets==7.8.5 jedi==0.17.2 Jinja2==3.0.3 json5==0.9.16 jsonschema==3.2.0 jupyter==1.1.1 jupyter-client==7.1.2 jupyter-console==6.4.3 jupyter-core==4.9.2 jupyter-server==1.13.1 jupyterlab==3.2.9 jupyterlab-pygments==0.1.2 jupyterlab-server==2.10.3 jupyterlab_widgets==1.1.11 Mako==1.1.6 MarkupSafe==2.0.1 mistune==0.8.4 nbclassic==0.3.5 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 -e git+https://github.com/jupyter/nbgrader.git@fa75fcb2fb7fa24451966b5ae2a44480f88d508b#egg=nbgrader nbval==0.10.0 nest-asyncio==1.6.0 notebook==6.4.10 packaging==21.3 pandocfilters==1.5.1 parso==0.7.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prometheus-client==0.17.1 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pycparser==2.21 pyenchant==3.2.2 Pygments==2.14.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 pytest-cov==4.0.0 pytest-rerunfailures==10.3 python-dateutil==2.9.0.post0 pytz==2025.2 pyzmq==25.1.2 requests==2.27.1 selenium==3.141.0 Send2Trash==1.8.3 six==1.17.0 sniffio==1.2.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-rtd-theme==2.0.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 sphinxcontrib-spelling==7.7.0 SQLAlchemy==1.4.54 terminado==0.12.1 testpath==0.6.0 tomli==1.2.3 tornado==6.1 traitlets==4.3.3 typing_extensions==4.1.1 urllib3==1.26.20 wcwidth==0.2.13 webencodings==0.5.1 websocket-client==1.3.1 widgetsnbextension==3.6.10 zipp==3.6.0
name: nbgrader channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - alembic==1.7.7 - anyio==3.6.2 - argon2-cffi==21.3.0 - argon2-cffi-bindings==21.2.0 - async-generator==1.10 - attrs==22.2.0 - babel==2.11.0 - backcall==0.2.0 - bleach==4.1.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - codecov==2.1.13 - comm==0.1.4 - contextvars==2.4 - cov-core==1.15.0 - coverage==6.2 - dataclasses==0.8 - decorator==5.1.1 - defusedxml==0.7.1 - docutils==0.18.1 - entrypoints==0.4 - fuzzywuzzy==0.18.0 - greenlet==2.0.2 - idna==3.10 - imagesize==1.4.1 - immutables==0.19 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - invoke==2.2.0 - ipykernel==5.5.6 - ipython==7.16.3 - ipython-genutils==0.2.0 - ipywidgets==7.8.5 - jedi==0.17.2 - jinja2==3.0.3 - json5==0.9.16 - jsonschema==3.2.0 - jupyter==1.1.1 - jupyter-client==7.1.2 - jupyter-console==6.4.3 - jupyter-core==4.9.2 - jupyter-server==1.13.1 - jupyterlab==3.2.9 - jupyterlab-pygments==0.1.2 - jupyterlab-server==2.10.3 - jupyterlab-widgets==1.1.11 - mako==1.1.6 - markupsafe==2.0.1 - mistune==0.8.4 - nbclassic==0.3.5 - nbclient==0.5.9 - nbconvert==6.0.7 - nbformat==5.1.3 - nbval==0.10.0 - nest-asyncio==1.6.0 - notebook==6.4.10 - packaging==21.3 - pandocfilters==1.5.1 - parso==0.7.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pip==21.3.1 - pluggy==1.0.0 - prometheus-client==0.17.1 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pycparser==2.21 - pyenchant==3.2.2 - pygments==2.14.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pytest-cov==4.0.0 - pytest-rerunfailures==10.3 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyzmq==25.1.2 - requests==2.27.1 - selenium==3.141.0 - send2trash==1.8.3 - setuptools==59.6.0 - six==1.17.0 - sniffio==1.2.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-rtd-theme==2.0.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - sphinxcontrib-spelling==7.7.0 - sqlalchemy==1.4.54 - terminado==0.12.1 - testpath==0.6.0 - tomli==1.2.3 - tornado==6.1 - traitlets==4.3.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - wcwidth==0.2.13 - webencodings==0.5.1 - websocket-client==1.3.1 - widgetsnbextension==3.6.10 - zipp==3.6.0 prefix: /opt/conda/envs/nbgrader
[ "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_quickstart_overwrite_course_folder_if_structure_not_present" ]
[]
[ "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_help", "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_no_course_id", "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_quickstart", "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_quickstart_fails_with_source_folder_removed", "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_quickstart_fails_with_config_file_removed", "nbgrader/tests/apps/test_nbgrader_quickstart.py::TestNbGraderQuickStart::test_quickstart_f" ]
[]
BSD 3-Clause "New" or "Revised" License
3,173
496
[ "nbgrader/apps/quickstartapp.py" ]
sendgrid__sendgrid-python-631
33a35765cffee71c56fd91a5561f39934b107cab
2018-10-04 12:55:39
265b9848834f3a2ff2c3d92fb1b711cd7f33f438
codecov[bot]: # [Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=h1) Report > Merging [#631](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=desc) into [master](https://codecov.io/gh/sendgrid/sendgrid-python/commit/f132e5ba71391f2390d94fb8743e5cb2aed0beb9?src=pr&el=desc) will **increase** coverage by `0.09%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631/graphs/tree.svg?width=650&token=Yq0yTs1Nfq&height=150&src=pr)](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #631 +/- ## ========================================== + Coverage 84.77% 84.86% +0.09% ========================================== Files 35 35 Lines 1156 1163 +7 Branches 172 173 +1 ========================================== + Hits 980 987 +7 Misses 90 90 Partials 86 86 ``` | [Impacted Files](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [sendgrid/helpers/mail/mail.py](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631/diff?src=pr&el=tree#diff-c2VuZGdyaWQvaGVscGVycy9tYWlsL21haWwucHk=) | `93.97% <100%> (+0.26%)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=footer). Last update [f132e5b...bb417a1](https://codecov.io/gh/sendgrid/sendgrid-python/pull/631?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
diff --git a/sendgrid/helpers/mail/mail.py b/sendgrid/helpers/mail/mail.py index f374e6a..c27fc72 100644 --- a/sendgrid/helpers/mail/mail.py +++ b/sendgrid/helpers/mail/mail.py @@ -1,6 +1,8 @@ """v3/mail/send response body builder""" from .personalization import Personalization from .header import Header +from .email import Email +from .content import Content class Mail(object): @@ -141,3 +143,28 @@ class Mail(object): return {key: value for key, value in mail.items() if value is not None and value != [] and value != {}} + + @classmethod + def from_EmailMessage(cls, message): + """Create a Mail object from an instance of + email.message.EmailMessage. + :type message: email.message.EmailMessage + :rtype: Mail + """ + mail = cls( + from_email=Email(message.get('From')), + subject=message.get('Subject'), + to_email=Email(message.get('To')), + ) + try: + body = message.get_content() + except AttributeError: + # Python2 + body = message.get_payload() + mail.add_content(Content( + message.get_content_type(), + body.strip() + )) + for k, v in message.items(): + mail.add_header(Header(k, v)) + return mail
Feature request: Support for sending email.message.EmailMessage I am working on integrating SendGrid into an application where I already have email messages as [email.message.EmailMessage](https://docs.python.org/3.6/library/email.message.html#email.message.EmailMessage), it would be really awesome if there was a way for me to send an `EmailMessage` directly rather than having to reconstruct .
sendgrid/sendgrid-python
diff --git a/test/test_mail.py b/test/test_mail.py index 98af29a..8ebe3eb 100644 --- a/test/test_mail.py +++ b/test/test_mail.py @@ -2,6 +2,13 @@ import json import unittest +try: + from email.message import EmailMessage +except ImportError: + # Python2 + from email import message + EmailMessage = message.Message + from sendgrid.helpers.mail import ( ASM, APIKeyIncludedException, @@ -557,3 +564,26 @@ class UnitTests(unittest.TestCase): def test_directly_setting_substitutions(self): personalization = Personalization() personalization.substitutions = [{'a': 0}] + + def test_from_emailmessage(self): + message = EmailMessage() + body = 'message that is not urgent' + try: + message.set_content(body) + except AttributeError: + # Python2 + message.set_payload(body) + message.set_default_type('text/plain') + message['Subject'] = 'URGENT TITLE' + message['From'] = '[email protected]' + message['To'] = '[email protected]' + mail = Mail.from_EmailMessage(message) + self.assertEqual(mail.subject, 'URGENT TITLE') + self.assertEqual(mail.from_email.email, '[email protected]') + self.assertEqual(len(mail.personalizations), 1) + self.assertEqual(len(mail.personalizations[0].tos), 1) + self.assertEqual(mail.personalizations[0].tos[0], {'email': '[email protected]'}) + self.assertEqual(len(mail.contents), 1) + content = mail.contents[0] + self.assertEqual(content.type, 'text/plain') + self.assertEqual(content.value, 'message that is not urgent')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 1 }
5.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest>=6.0.0", "numpy>=1.16.0", "pandas>=1.0.0" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 numpy==2.0.2 packaging==24.2 pandas==2.2.3 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 python-http-client==3.3.7 pytz==2025.2 -e git+https://github.com/sendgrid/sendgrid-python.git@33a35765cffee71c56fd91a5561f39934b107cab#egg=sendgrid six==1.17.0 tomli==2.2.1 tzdata==2025.2
name: sendgrid-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-http-client==3.3.7 - pytz==2025.2 - six==1.17.0 - tomli==2.2.1 - tzdata==2025.2 prefix: /opt/conda/envs/sendgrid-python
[ "test/test_mail.py::UnitTests::test_from_emailmessage" ]
[]
[ "test/test_mail.py::UnitTests::test_asm_display_group_limit", "test/test_mail.py::UnitTests::test_directly_setting_substitutions", "test/test_mail.py::UnitTests::test_disable_tracking", "test/test_mail.py::UnitTests::test_helloEmail", "test/test_mail.py::UnitTests::test_helloEmailAdditionalContent", "test/test_mail.py::UnitTests::test_kitchenSink", "test/test_mail.py::UnitTests::test_sendgridAPIKey", "test/test_mail.py::UnitTests::test_unicode_values_in_substitutions_helper" ]
[]
MIT License
3,176
334
[ "sendgrid/helpers/mail/mail.py" ]
ownaginatious__mixpanel-jql-18
cad22fecf6220e3857dec5de122c8df8810c9737
2018-10-05 00:15:01
cad22fecf6220e3857dec5de122c8df8810c9737
codecov-io: # [Codecov](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=h1) Report > Merging [#18](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=desc) into [master](https://codecov.io/gh/ownaginatious/mixpanel-jql/commit/cad22fecf6220e3857dec5de122c8df8810c9737?src=pr&el=desc) will **increase** coverage by `0.04%`. > The diff coverage is `100%`. [![Impacted file tree graph](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18/graphs/tree.svg?width=650&token=xJsxO2WgJp&height=150&src=pr)](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=tree) ```diff @@ Coverage Diff @@ ## master #18 +/- ## ========================================== + Coverage 87.08% 87.13% +0.04% ========================================== Files 2 2 Lines 271 272 +1 Branches 71 70 -1 ========================================== + Hits 236 237 +1 Misses 24 24 Partials 11 11 ``` | [Impacted Files](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=tree) | Coverage Δ | | |---|---|---| | [mixpanel\_jql/query.py](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18/diff?src=pr&el=tree#diff-bWl4cGFuZWxfanFsL3F1ZXJ5LnB5) | `86.94% <100%> (+0.04%)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=continue). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=footer). Last update [cad22fe...cc5066a](https://codecov.io/gh/ownaginatious/mixpanel-jql/pull/18?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
diff --git a/mixpanel_jql/query.py b/mixpanel_jql/query.py index 919894f..768da83 100644 --- a/mixpanel_jql/query.py +++ b/mixpanel_jql/query.py @@ -394,19 +394,19 @@ class JQL(object): return jql def group_by(self, keys, accumulator): - if not isinstance(keys, (tuple, set, list)): - keys = [keys] - jql = self._clone() - jql.operations += ("groupBy([%s], %s)" - % (", ".join(_f(k) for k in keys), _f(accumulator)),) - return jql + return self._group_by(False, keys, accumulator) def group_by_user(self, keys, accumulator): + return self._group_by(True, keys, accumulator) + + def _group_by(self, user, keys, accumulator): if not isinstance(keys, (tuple, set, list)): keys = [keys] + if not isinstance(accumulator, Reducer): + accumulator = _f(accumulator) jql = self._clone() - jql.operations += ("groupByUser([%s], %s)" - % (", ".join(_f(k) for k in keys), _f(accumulator)),) + op = "groupByUser" if user else "groupBy" + jql.operations += ("%s([%s], %s)" % (op, ", ".join(_f(k) for k in keys), accumulator),) return jql def query_plan(self):
mixpanel_jql.exceptions.InvalidJavaScriptText Hi, first of all thanks for this project! I'm trying to run the first example and I'm getting: `mixpanel_jql.exceptions.InvalidJavaScriptText: Must be a text type (str, unicode) or wrapped as raw(str||unicode)` I'm runnning Python 3.6.5 on Ubuntu 18.04
ownaginatious/mixpanel-jql
diff --git a/tests/test_transformations.py b/tests/test_transformations.py index f66c218..e7f3dfc 100644 --- a/tests/test_transformations.py +++ b/tests/test_transformations.py @@ -63,6 +63,12 @@ class TestGroupTransformations(unittest.TestCase): 'function main() { return Events({}).' '%s([e.a, e.b, e.c], e.properties.some_accessor); }' % expected_function) + self.assertEqual( + str(grouper([ + raw('e.a'), raw('e.b'), raw('e.c')], Reducer.count())), + 'function main() { return Events({}).' + '%s([e.a, e.b, e.c], mixpanel.reducer.count()); }' % expected_function) + # Non iterable key. self.assertEqual( str(grouper(raw('e.a'), raw('e.properties.some_accessor'))),
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 EditorConfig==0.17.0 idna==3.10 ijson==3.3.0 importlib-metadata==4.8.3 iniconfig==1.1.1 jsbeautifier==1.15.4 -e git+https://github.com/ownaginatious/mixpanel-jql.git@cad22fecf6220e3857dec5de122c8df8810c9737#egg=mixpanel_jql packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.27.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: mixpanel-jql channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - editorconfig==0.17.0 - idna==3.10 - ijson==3.3.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jsbeautifier==1.15.4 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.27.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/mixpanel-jql
[ "tests/test_transformations.py::TestGroupTransformations::test_group_by", "tests/test_transformations.py::TestGroupTransformations::test_group_by_user" ]
[]
[ "tests/test_transformations.py::TestAccessorOnlyTransformations::test_filter", "tests/test_transformations.py::TestAccessorOnlyTransformations::test_map", "tests/test_transformations.py::TestAccessorOnlyTransformations::test_reduce", "tests/test_transformations.py::TestAccessorOnlyTransformations::test_sort_asc", "tests/test_transformations.py::TestAccessorOnlyTransformations::test_sort_desc" ]
[]
MIT License
3,180
370
[ "mixpanel_jql/query.py" ]
python-cmd2__cmd2-569
9fee6105210b36201b5d2edc610f20bd67eac9f2
2018-10-05 19:51:27
60a212c1c585f0c4c06ffcfeb9882520af8dbf35
diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py index 2002ca6d..7c09aab0 100644 --- a/cmd2/pyscript_bridge.py +++ b/cmd2/pyscript_bridge.py @@ -33,9 +33,16 @@ class CommandResult(namedtuple_with_defaults('CommandResult', ['stdout', 'stderr NOTE: Named tuples are immutable. So the contents are there for access, not for modification. """ - def __bool__(self): - """If stderr is None and data is not None the command is considered a success""" - return not self.stderr and self.data is not None + def __bool__(self) -> bool: + """Returns True if the command succeeded, otherwise False""" + + # If data has a __bool__ method, then call it to determine success of command + if self.data is not None and callable(getattr(self.data, '__bool__', None)): + return bool(self.data) + + # Otherwise check if stderr was filled out + else: + return not self.stderr def _exec_cmd(cmd2_app, func: Callable, echo: bool) -> CommandResult:
CommandResult is False for cmd2 built-ins Since no built-in **cmd2** command fills out `self._last_result`, `CommandResult` is always **False** when running these commands in `pyscript`.
python-cmd2/cmd2
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index a64f21e4..a2bd6197 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -1576,8 +1576,14 @@ class CommandResultApp(cmd2.Cmd): self._last_result = cmd2.CommandResult(arg, data=True) def do_negative(self, arg): + self._last_result = cmd2.CommandResult(arg, data=False) + + def do_affirmative_no_data(self, arg): self._last_result = cmd2.CommandResult(arg) + def do_negative_no_data(self, arg): + self._last_result = cmd2.CommandResult('', arg) + @pytest.fixture def commandresult_app(): app = CommandResultApp() @@ -1590,11 +1596,19 @@ def test_commandresult_truthy(commandresult_app): assert commandresult_app._last_result assert commandresult_app._last_result == cmd2.CommandResult(arg, data=True) + run_cmd(commandresult_app, 'affirmative_no_data {}'.format(arg)) + assert commandresult_app._last_result + assert commandresult_app._last_result == cmd2.CommandResult(arg) + def test_commandresult_falsy(commandresult_app): arg = 'bar' run_cmd(commandresult_app, 'negative {}'.format(arg)) assert not commandresult_app._last_result - assert commandresult_app._last_result == cmd2.CommandResult(arg) + assert commandresult_app._last_result == cmd2.CommandResult(arg, data=False) + + run_cmd(commandresult_app, 'negative_no_data {}'.format(arg)) + assert not commandresult_app._last_result + assert commandresult_app._last_result == cmd2.CommandResult('', arg) def test_is_text_file_bad_input(base_app):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 anyio==4.9.0 astroid==3.3.9 attrs==25.3.0 babel==2.17.0 backports.tarfile==1.2.0 cachetools==5.5.2 certifi==2025.1.31 cffi==1.17.1 chardet==5.2.0 charset-normalizer==3.4.1 click==8.1.8 -e git+https://github.com/python-cmd2/cmd2.git@9fee6105210b36201b5d2edc610f20bd67eac9f2#egg=cmd2 codecov==2.1.13 colorama==0.4.6 coverage==7.8.0 cryptography==44.0.2 dill==0.3.9 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 filelock==3.18.0 h11==0.14.0 id==1.5.0 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 invoke==2.2.0 isort==6.0.1 jaraco.classes==3.4.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jeepney==0.9.0 Jinja2==3.1.6 keyring==25.6.0 markdown-it-py==3.0.0 MarkupSafe==3.0.2 mccabe==0.7.0 mdurl==0.1.2 more-itertools==10.6.0 nh3==0.2.21 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pycparser==2.22 Pygments==2.19.1 pylint==3.3.6 pyperclip==1.9.0 pyproject-api==1.9.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 readme_renderer==44.0 requests==2.32.3 requests-toolbelt==1.0.0 rfc3986==2.0.0 rich==14.0.0 SecretStorage==3.3.3 sniffio==1.3.1 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinx-autobuild==2024.10.3 sphinx-rtd-theme==3.0.2 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jquery==4.1 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 starlette==0.46.1 tomli==2.2.1 tomlkit==0.13.2 tox==4.25.0 twine==6.1.0 typing_extensions==4.13.0 urllib3==2.3.0 uvicorn==0.34.0 virtualenv==20.29.3 watchfiles==1.0.4 wcwidth==0.2.13 websockets==15.0.1 zipp==3.21.0
name: cmd2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - anyio==4.9.0 - astroid==3.3.9 - attrs==25.3.0 - babel==2.17.0 - backports-tarfile==1.2.0 - cachetools==5.5.2 - certifi==2025.1.31 - cffi==1.17.1 - chardet==5.2.0 - charset-normalizer==3.4.1 - click==8.1.8 - codecov==2.1.13 - colorama==0.4.6 - coverage==7.8.0 - cryptography==44.0.2 - dill==0.3.9 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - filelock==3.18.0 - h11==0.14.0 - id==1.5.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - invoke==2.2.0 - isort==6.0.1 - jaraco-classes==3.4.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jeepney==0.9.0 - jinja2==3.1.6 - keyring==25.6.0 - markdown-it-py==3.0.0 - markupsafe==3.0.2 - mccabe==0.7.0 - mdurl==0.1.2 - more-itertools==10.6.0 - nh3==0.2.21 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pycparser==2.22 - pygments==2.19.1 - pylint==3.3.6 - pyperclip==1.9.0 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - readme-renderer==44.0 - requests==2.32.3 - requests-toolbelt==1.0.0 - rfc3986==2.0.0 - rich==14.0.0 - secretstorage==3.3.3 - sniffio==1.3.1 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinx-autobuild==2024.10.3 - sphinx-rtd-theme==3.0.2 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jquery==4.1 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - starlette==0.46.1 - tomli==2.2.1 - tomlkit==0.13.2 - tox==4.25.0 - twine==6.1.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - uvicorn==0.34.0 - virtualenv==20.29.3 - watchfiles==1.0.4 - wcwidth==0.2.13 - websockets==15.0.1 - zipp==3.21.0 prefix: /opt/conda/envs/cmd2
[ "tests/test_cmd2.py::test_commandresult_truthy", "tests/test_cmd2.py::test_commandresult_falsy" ]
[ "tests/test_cmd2.py::test_which_editor_good" ]
[ "tests/test_cmd2.py::test_version", "tests/test_cmd2.py::test_empty_statement", "tests/test_cmd2.py::test_base_help", "tests/test_cmd2.py::test_base_help_verbose", "tests/test_cmd2.py::test_base_help_history", "tests/test_cmd2.py::test_base_argparse_help", "tests/test_cmd2.py::test_base_invalid_option", "tests/test_cmd2.py::test_base_shortcuts", "tests/test_cmd2.py::test_base_show", "tests/test_cmd2.py::test_base_show_long", "tests/test_cmd2.py::test_base_show_readonly", "tests/test_cmd2.py::test_cast", "tests/test_cmd2.py::test_cast_problems", "tests/test_cmd2.py::test_base_set", "tests/test_cmd2.py::test_set_not_supported", "tests/test_cmd2.py::test_set_quiet", "tests/test_cmd2.py::test_set_onchange_hook", "tests/test_cmd2.py::test_base_shell", "tests/test_cmd2.py::test_base_py", "tests/test_cmd2.py::test_base_run_python_script", "tests/test_cmd2.py::test_base_run_pyscript", "tests/test_cmd2.py::test_recursive_pyscript_not_allowed", "tests/test_cmd2.py::test_pyscript_with_nonexist_file", "tests/test_cmd2.py::test_pyscript_with_exception", "tests/test_cmd2.py::test_pyscript_requires_an_argument", "tests/test_cmd2.py::test_base_error", "tests/test_cmd2.py::test_history_span", "tests/test_cmd2.py::test_history_get", "tests/test_cmd2.py::test_base_history", "tests/test_cmd2.py::test_history_script_format", "tests/test_cmd2.py::test_history_with_string_argument", "tests/test_cmd2.py::test_history_with_integer_argument", "tests/test_cmd2.py::test_history_with_integer_span", "tests/test_cmd2.py::test_history_with_span_start", "tests/test_cmd2.py::test_history_with_span_end", "tests/test_cmd2.py::test_history_with_span_index_error", "tests/test_cmd2.py::test_history_output_file", "tests/test_cmd2.py::test_history_edit", "tests/test_cmd2.py::test_history_run_all_commands", "tests/test_cmd2.py::test_history_run_one_command", "tests/test_cmd2.py::test_history_clear", "tests/test_cmd2.py::test_base_load", "tests/test_cmd2.py::test_load_with_empty_args", "tests/test_cmd2.py::test_load_with_nonexistent_file", "tests/test_cmd2.py::test_load_with_directory", "tests/test_cmd2.py::test_load_with_empty_file", "tests/test_cmd2.py::test_load_with_binary_file", "tests/test_cmd2.py::test_load_with_utf8_file", "tests/test_cmd2.py::test_load_nested_loads", "tests/test_cmd2.py::test_base_runcmds_plus_hooks", "tests/test_cmd2.py::test_base_relative_load", "tests/test_cmd2.py::test_relative_load_requires_an_argument", "tests/test_cmd2.py::test_output_redirection", "tests/test_cmd2.py::test_output_redirection_to_nonexistent_directory", "tests/test_cmd2.py::test_output_redirection_to_too_long_filename", "tests/test_cmd2.py::test_feedback_to_output_true", "tests/test_cmd2.py::test_feedback_to_output_false", "tests/test_cmd2.py::test_allow_redirection", "tests/test_cmd2.py::test_pipe_to_shell", "tests/test_cmd2.py::test_pipe_to_shell_error", "tests/test_cmd2.py::test_base_timing", "tests/test_cmd2.py::test_base_debug", "tests/test_cmd2.py::test_base_colorize", "tests/test_cmd2.py::test_edit_no_editor", "tests/test_cmd2.py::test_edit_file", "tests/test_cmd2.py::test_edit_file_with_spaces", "tests/test_cmd2.py::test_edit_blank", "tests/test_cmd2.py::test_base_py_interactive", "tests/test_cmd2.py::test_exclude_from_history", "tests/test_cmd2.py::test_base_cmdloop_with_queue", "tests/test_cmd2.py::test_base_cmdloop_without_queue", "tests/test_cmd2.py::test_cmdloop_without_rawinput", "tests/test_cmd2.py::test_precmd_hook_success", "tests/test_cmd2.py::test_precmd_hook_failure", "tests/test_cmd2.py::test_interrupt_quit", "tests/test_cmd2.py::test_interrupt_noquit", "tests/test_cmd2.py::test_default_to_shell_unknown", "tests/test_cmd2.py::test_default_to_shell_good", "tests/test_cmd2.py::test_default_to_shell_failure", "tests/test_cmd2.py::test_ansi_prompt_not_esacped", "tests/test_cmd2.py::test_ansi_prompt_escaped", "tests/test_cmd2.py::test_custom_command_help", "tests/test_cmd2.py::test_custom_help_menu", "tests/test_cmd2.py::test_help_undocumented", "tests/test_cmd2.py::test_help_overridden_method", "tests/test_cmd2.py::test_help_cat_base", "tests/test_cmd2.py::test_help_cat_verbose", "tests/test_cmd2.py::test_select_options", "tests/test_cmd2.py::test_select_invalid_option", "tests/test_cmd2.py::test_select_list_of_strings", "tests/test_cmd2.py::test_select_list_of_tuples", "tests/test_cmd2.py::test_select_uneven_list_of_tuples", "tests/test_cmd2.py::test_help_with_no_docstring", "tests/test_cmd2.py::test_which_editor_bad", "tests/test_cmd2.py::test_multiline_complete_empty_statement_raises_exception", "tests/test_cmd2.py::test_multiline_complete_statement_without_terminator", "tests/test_cmd2.py::test_multiline_complete_statement_with_unclosed_quotes", "tests/test_cmd2.py::test_clipboard_failure", "tests/test_cmd2.py::test_is_text_file_bad_input", "tests/test_cmd2.py::test_eof", "tests/test_cmd2.py::test_eos", "tests/test_cmd2.py::test_echo", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_true", "tests/test_cmd2.py::test_pseudo_raw_input_tty_rawinput_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_true_echo_false", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_true", "tests/test_cmd2.py::test_pseudo_raw_input_piped_rawinput_false_echo_false", "tests/test_cmd2.py::test_raw_input", "tests/test_cmd2.py::test_stdin_input", "tests/test_cmd2.py::test_empty_stdin_input", "tests/test_cmd2.py::test_poutput_string", "tests/test_cmd2.py::test_poutput_zero", "tests/test_cmd2.py::test_poutput_empty_string", "tests/test_cmd2.py::test_poutput_none", "tests/test_cmd2.py::test_poutput_color_always", "tests/test_cmd2.py::test_poutput_color_never", "tests/test_cmd2.py::test_get_alias_names", "tests/test_cmd2.py::test_get_macro_names", "tests/test_cmd2.py::test_alias_no_subcommand", "tests/test_cmd2.py::test_alias_create", "tests/test_cmd2.py::test_alias_create_with_quoted_value", "tests/test_cmd2.py::test_alias_create_invalid_name[\"\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[!no_shortcut]", "tests/test_cmd2.py::test_alias_create_invalid_name[\">\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"no>pe\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"no", "tests/test_cmd2.py::test_alias_create_invalid_name[\"nopipe|\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[\"noterm;\"]", "tests/test_cmd2.py::test_alias_create_invalid_name[noembedded\"quotes]", "tests/test_cmd2.py::test_alias_create_with_macro_name", "tests/test_cmd2.py::test_alias_list_invalid_alias", "tests/test_cmd2.py::test_alias_delete", "tests/test_cmd2.py::test_alias_delete_all", "tests/test_cmd2.py::test_alias_delete_non_existing", "tests/test_cmd2.py::test_alias_delete_no_name", "tests/test_cmd2.py::test_multiple_aliases", "tests/test_cmd2.py::test_macro_no_subcommand", "tests/test_cmd2.py::test_macro_create", "tests/test_cmd2.py::test_macro_create_with_quoted_value", "tests/test_cmd2.py::test_macro_create_invalid_name[\"\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[!no_shortcut]", "tests/test_cmd2.py::test_macro_create_invalid_name[\">\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"no>pe\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"no", "tests/test_cmd2.py::test_macro_create_invalid_name[\"nopipe|\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[\"noterm;\"]", "tests/test_cmd2.py::test_macro_create_invalid_name[noembedded\"quotes]", "tests/test_cmd2.py::test_macro_create_with_alias_name", "tests/test_cmd2.py::test_macro_create_with_command_name", "tests/test_cmd2.py::test_macro_create_with_args", "tests/test_cmd2.py::test_macro_create_with_escaped_args", "tests/test_cmd2.py::test_macro_create_with_missing_arg_nums", "tests/test_cmd2.py::test_macro_create_with_invalid_arg_num", "tests/test_cmd2.py::test_macro_create_with_wrong_arg_count", "tests/test_cmd2.py::test_macro_create_with_unicode_numbered_arg", "tests/test_cmd2.py::test_macro_create_with_missing_unicode_arg_nums", "tests/test_cmd2.py::test_macro_list_invalid_macro", "tests/test_cmd2.py::test_macro_delete", "tests/test_cmd2.py::test_macro_delete_all", "tests/test_cmd2.py::test_macro_delete_non_existing", "tests/test_cmd2.py::test_macro_delete_no_name", "tests/test_cmd2.py::test_multiple_macros", "tests/test_cmd2.py::test_nonexistent_macro", "tests/test_cmd2.py::test_ppaged", "tests/test_cmd2.py::test_parseline_empty", "tests/test_cmd2.py::test_parseline", "tests/test_cmd2.py::test_readline_remove_history_item", "tests/test_cmd2.py::test_onecmd_raw_str_continue", "tests/test_cmd2.py::test_onecmd_raw_str_quit", "tests/test_cmd2.py::test_existing_history_file", "tests/test_cmd2.py::test_new_history_file", "tests/test_cmd2.py::test_bad_history_file_path", "tests/test_cmd2.py::test_get_all_commands", "tests/test_cmd2.py::test_get_help_topics", "tests/test_cmd2.py::test_exit_code_default", "tests/test_cmd2.py::test_exit_code_nonzero", "tests/test_cmd2.py::test_colors_default", "tests/test_cmd2.py::test_colors_pouterr_always_tty", "tests/test_cmd2.py::test_colors_pouterr_always_notty", "tests/test_cmd2.py::test_colors_terminal_tty", "tests/test_cmd2.py::test_colors_terminal_notty", "tests/test_cmd2.py::test_colors_never_tty", "tests/test_cmd2.py::test_colors_never_notty" ]
[]
MIT License
3,184
274
[ "cmd2/pyscript_bridge.py" ]
pri22296__beautifultable-37
d3e55f597be47dbfb245768d23a0176c1b059f1e
2018-10-06 22:06:17
d3e55f597be47dbfb245768d23a0176c1b059f1e
coveralls: [![Coverage Status](https://coveralls.io/builds/19388578/badge)](https://coveralls.io/builds/19388578) Coverage increased (+0.1%) to 78.662% when pulling **978717442ecec309e869354ad98254032368ca67 on Sideboard:master** into **d3e55f597be47dbfb245768d23a0176c1b059f1e on pri22296:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/19388578/badge)](https://coveralls.io/builds/19388578) Coverage increased (+0.1%) to 78.662% when pulling **978717442ecec309e869354ad98254032368ca67 on Sideboard:master** into **d3e55f597be47dbfb245768d23a0176c1b059f1e on pri22296:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/19388578/badge)](https://coveralls.io/builds/19388578) Coverage increased (+0.1%) to 78.662% when pulling **978717442ecec309e869354ad98254032368ca67 on Sideboard:master** into **d3e55f597be47dbfb245768d23a0176c1b059f1e on pri22296:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/19388578/badge)](https://coveralls.io/builds/19388578) Coverage increased (+0.1%) to 78.662% when pulling **978717442ecec309e869354ad98254032368ca67 on Sideboard:master** into **d3e55f597be47dbfb245768d23a0176c1b059f1e on pri22296:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/19388578/badge)](https://coveralls.io/builds/19388578) Coverage increased (+0.1%) to 78.662% when pulling **978717442ecec309e869354ad98254032368ca67 on Sideboard:master** into **d3e55f597be47dbfb245768d23a0176c1b059f1e on pri22296:master**. pri22296: Thanks for the Pull Request. Can you just squash the 2 commits into a single one? Other than that this looks good to me.
diff --git a/beautifultable/beautifultable.py b/beautifultable/beautifultable.py index 0835eca..804e7a6 100644 --- a/beautifultable/beautifultable.py +++ b/beautifultable/beautifultable.py @@ -622,7 +622,8 @@ class BeautifulTable(object): actual_space = sum_ - temp_sum for i, _ in enumerate(widths): if not flag[i]: - widths[i] = int(round(widths[i] * avail_space / actual_space)) + new_width = int(round(widths[i] * avail_space / actual_space)) + widths[i] = min(widths[i], new_width) self.column_widths = widths def set_padding_widths(self, pad_width):
Incorrect calculation of column width Minimal example: ```py table = beautifultable.BeautifulTable(max_width=150) table.column_headers = ['t', 'u', 'v', 'w', 'x', 'y', 'z'] table.append_row(['q123456789012345678', 'a', 'b', 'c', 'd', 'e', 'f']) print(table) ``` Output: ``` +----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+ | t | u | v | w | x | y | z | +----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+ | q123456789012345678 | a | b | c | d | e | f | +----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+ ``` The first column is too wide. If I omit the last character, it works as expected: ```py table.append_row(['q12345678901234567', 'a', 'b', 'c', 'd', 'e', 'f']) ``` ``` +--------------------+---+---+---+---+---+---+ | t | u | v | w | x | y | z | +--------------------+---+---+---+---+---+---+ | q12345678901234567 | a | b | c | d | e | f | +--------------------+---+---+---+---+---+---+ ``` It also seems to work as expected if I change the `max_width`, or if I use fewer columns.
pri22296/beautifultable
diff --git a/test.py b/test.py index a02b6bc..edc0c45 100644 --- a/test.py +++ b/test.py @@ -371,6 +371,18 @@ class TableOperationsTestCase(unittest.TestCase): width = self.table.get_table_width() self.assertEqual(width, 0) + def test_table_auto_width(self): + row_list = ['abcdefghijklmopqrstuvwxyz', 1234, 'none'] + + self.create_table(200) + self.table.append_row(row_list) + len_for_max_width_200 = len(str(self.table)) + + self.create_table(80) + self.table.append_row(row_list) + len_for_max_width_80 = len(str(self.table)) + + self.assertEqual(len_for_max_width_80, len_for_max_width_200) if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work -e git+https://github.com/pri22296/beautifultable.git@d3e55f597be47dbfb245768d23a0176c1b059f1e#egg=beautifultable certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: beautifultable channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/beautifultable
[ "test.py::TableOperationsTestCase::test_table_auto_width" ]
[]
[ "test.py::TableOperationsTestCase::test_access_column_by_header", "test.py::TableOperationsTestCase::test_access_row_by_index", "test.py::TableOperationsTestCase::test_access_row_element_by_header", "test.py::TableOperationsTestCase::test_access_row_element_by_index", "test.py::TableOperationsTestCase::test_append_column", "test.py::TableOperationsTestCase::test_append_row", "test.py::TableOperationsTestCase::test_column_count", "test.py::TableOperationsTestCase::test_contains", "test.py::TableOperationsTestCase::test_delitem_int", "test.py::TableOperationsTestCase::test_delitem_slice", "test.py::TableOperationsTestCase::test_delitem_str", "test.py::TableOperationsTestCase::test_empty_header", "test.py::TableOperationsTestCase::test_empty_table_by_column", "test.py::TableOperationsTestCase::test_empty_table_by_row", "test.py::TableOperationsTestCase::test_get_column_header", "test.py::TableOperationsTestCase::test_get_column_index", "test.py::TableOperationsTestCase::test_get_string", "test.py::TableOperationsTestCase::test_getitem_slice", "test.py::TableOperationsTestCase::test_insert_column", "test.py::TableOperationsTestCase::test_insert_row", "test.py::TableOperationsTestCase::test_left_align", "test.py::TableOperationsTestCase::test_mixed_align", "test.py::TableOperationsTestCase::test_pop_column_by_header", "test.py::TableOperationsTestCase::test_pop_column_by_position", "test.py::TableOperationsTestCase::test_pop_row", "test.py::TableOperationsTestCase::test_right_align", "test.py::TableOperationsTestCase::test_row_count", "test.py::TableOperationsTestCase::test_serialno", "test.py::TableOperationsTestCase::test_setitem_int", "test.py::TableOperationsTestCase::test_setitem_slice", "test.py::TableOperationsTestCase::test_setitem_str", "test.py::TableOperationsTestCase::test_signmode_plus", "test.py::TableOperationsTestCase::test_table_width_zero", "test.py::TableOperationsTestCase::test_update_column", "test.py::TableOperationsTestCase::test_update_row", "test.py::TableOperationsTestCase::test_update_row_slice", "test.py::TableOperationsTestCase::test_wep_ellipsis", "test.py::TableOperationsTestCase::test_wep_strip", "test.py::TableOperationsTestCase::test_wep_wrap" ]
[]
MIT License
3,187
194
[ "beautifultable/beautifultable.py" ]
encode__starlette-92
bdf99f1f6173dc4fbe9ea323bf3f86905d479ac1
2018-10-08 23:42:41
27fc98b58b543392a1e6c2e8015f0c377cccd659
diff --git a/starlette/middleware/cors.py b/starlette/middleware/cors.py index e299e74..99b0687 100644 --- a/starlette/middleware/cors.py +++ b/starlette/middleware/cors.py @@ -3,6 +3,7 @@ from starlette.responses import PlainTextResponse from starlette.types import ASGIApp, ASGIInstance, Scope import functools import typing +import re ALL_METHODS = ("DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT") @@ -16,6 +17,7 @@ class CORSMiddleware: allow_methods: typing.Sequence[str] = ("GET",), allow_headers: typing.Sequence[str] = (), allow_credentials: bool = False, + allow_origin_regex: str = None, expose_headers: typing.Sequence[str] = (), max_age: int = 600, ): @@ -23,6 +25,10 @@ class CORSMiddleware: if "*" in allow_methods: allow_methods = ALL_METHODS + if allow_origin_regex is not None: + regex = re.compile(allow_origin_regex) + allow_origin_regex = regex + simple_headers = {} if "*" in allow_origins: simple_headers["Access-Control-Allow-Origin"] = "*" @@ -53,6 +59,7 @@ class CORSMiddleware: self.allow_headers = allow_headers self.allow_all_origins = "*" in allow_origins self.allow_all_headers = "*" in allow_headers + self.allow_origin_regex = allow_origin_regex self.simple_headers = simple_headers self.preflight_headers = preflight_headers @@ -66,12 +73,22 @@ class CORSMiddleware: if method == "OPTIONS" and "access-control-request-method" in headers: return self.preflight_response(request_headers=headers) else: - return functools.partial( - self.simple_response, scope=scope, origin=origin - ) + if self.is_allowed_origin(origin=origin): + return functools.partial( + self.simple_response, scope=scope, origin=origin + ) + return PlainTextResponse("Disallowed CORS origin", status_code=400) return self.app(scope) + def is_allowed_origin(self, origin): + if self.allow_origin_regex: + return self.allow_origin_regex.match(origin) + if self.allow_all_origins: + return True + + return origin in self.allow_origins + def preflight_response(self, request_headers): requested_origin = request_headers["origin"] requested_method = request_headers["access-control-request-method"] @@ -84,7 +101,7 @@ class CORSMiddleware: # If we only allow specific origins, then we have to mirror back # the Origin header in the response. if not self.allow_all_origins: - if requested_origin in self.allow_origins: + if self.is_allowed_origin(origin=requested_origin): headers["Access-Control-Allow-Origin"] = requested_origin else: failures.append("origin") @@ -125,7 +142,7 @@ class CORSMiddleware: # If we only allow specific origins, then we have to mirror back # the Origin header in the response. - if not self.allow_all_origins and origin in self.allow_origins: + if not self.allow_all_origins and self.is_allowed_origin(origin=origin): headers["Access-Control-Allow-Origin"] = origin headers.update(self.simple_headers) await send(message)
Add `allow_origin_regex` to CORSMiddleware. It'd be helpful if `CORSMiddleware` supported an `allow_origin_regex`, so that users could do... ```python # Enforce a subdomain CORS policy app.add_middleware(CORSMiddleware, allow_origin_regex="(http|https)://*.example.com") ``` Or... ```python # Enforce an HTTPS-only CORS policy. app.add_middleware(CORSMiddleware, allow_origin_regex="https://*") ``` The string should be compiled to a regex by the middleware and matches should be anchored to the start/end of the origin string.
encode/starlette
diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 07a22b0..6d7273d 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -153,3 +153,42 @@ def test_cors_disallowed_preflight(): response = client.options("/", headers=headers) assert response.status_code == 400 assert response.text == "Disallowed CORS origin, method, headers" + + +def test_cors_allow_origin_regex(): + app = Starlette() + + app.add_middleware( + CORSMiddleware, allow_headers=["X-Example"], allow_origin_regex="https://*" + ) + + @app.route("/") + def homepage(request): + return PlainTextResponse("Homepage", status_code=200) + + client = TestClient(app) + + # Test standard response + headers = {"Origin": "https://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 200 + assert response.text == "Homepage" + assert response.headers["access-control-allow-origin"] == "https://example.org" + + # Test disallowed origin + headers = {"Origin": "http://example.org"} + response = client.get("/", headers=headers) + assert response.status_code == 400 + assert response.text == "Disallowed CORS origin" + + # Test pre-flight response + headers = { + "Origin": "https://another.com", + "Access-Control-Request-Method": "GET", + "Access-Control-Request-Headers": "X-Example", + } + response = client.options("/", headers=headers) + assert response.status_code == 200 + assert response.text == "OK" + assert response.headers["access-control-allow-origin"] == "https://another.com" + assert response.headers["access-control-allow-headers"] == "X-Example"
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[full]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiofiles==24.1.0 babel==2.17.0 backrefs==5.8 black==25.1.0 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 codecov==2.1.13 colorama==0.4.6 coverage==7.8.0 exceptiongroup==1.2.2 ghp-import==2.1.0 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 Markdown==3.7 MarkupSafe==3.0.2 mergedeep==1.3.4 mkdocs==1.6.1 mkdocs-get-deps==0.2.0 mkdocs-material==9.6.10 mkdocs-material-extensions==1.3.1 mypy-extensions==1.0.0 packaging==24.2 paginate==0.5.7 pathspec==0.12.1 platformdirs==4.3.7 pluggy==1.5.0 Pygments==2.19.1 pymdown-extensions==10.14.3 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 PyYAML==6.0.2 pyyaml_env_tag==0.1 requests==2.32.3 six==1.17.0 -e git+https://github.com/encode/starlette.git@bdf99f1f6173dc4fbe9ea323bf3f86905d479ac1#egg=starlette tomli==2.2.1 typing_extensions==4.13.0 ujson==5.10.0 urllib3==2.3.0 watchdog==6.0.0 zipp==3.21.0
name: starlette channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - aiofiles==24.1.0 - babel==2.17.0 - backrefs==5.8 - black==25.1.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - codecov==2.1.13 - colorama==0.4.6 - coverage==7.8.0 - exceptiongroup==1.2.2 - ghp-import==2.1.0 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - markdown==3.7 - markupsafe==3.0.2 - mergedeep==1.3.4 - mkdocs==1.6.1 - mkdocs-get-deps==0.2.0 - mkdocs-material==9.6.10 - mkdocs-material-extensions==1.3.1 - mypy-extensions==1.0.0 - packaging==24.2 - paginate==0.5.7 - pathspec==0.12.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pygments==2.19.1 - pymdown-extensions==10.14.3 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - pyyaml-env-tag==0.1 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - typing-extensions==4.13.0 - ujson==5.10.0 - urllib3==2.3.0 - watchdog==6.0.0 - zipp==3.21.0 prefix: /opt/conda/envs/starlette
[ "tests/test_middleware.py::test_cors_allow_origin_regex" ]
[]
[ "tests/test_middleware.py::test_trusted_host_middleware", "tests/test_middleware.py::test_https_redirect_middleware", "tests/test_middleware.py::test_cors_allow_all", "tests/test_middleware.py::test_cors_allow_specific_origin", "tests/test_middleware.py::test_cors_disallowed_preflight" ]
[]
BSD 3-Clause "New" or "Revised" License
3,203
795
[ "starlette/middleware/cors.py" ]
Duke-GCB__bespin-cli-15
70450d7b00c477580d6851b8aaa65433a54cf415
2018-10-09 13:37:32
2cef15b8296373f564d5cdf3c34503c1ca7f1e29
diff --git a/bespin/argparser.py b/bespin/argparser.py index 5fc8fa3..f97d735 100644 --- a/bespin/argparser.py +++ b/bespin/argparser.py @@ -40,6 +40,8 @@ class ArgParser(object): jobs_subparser = jobs_parser.add_subparsers() list_jobs_parser = jobs_subparser.add_parser('list', description='list workflows') + list_jobs_parser.add_argument('-a', '--all', action='store_true', + help='show all workflow versions instead of just the most recent.') list_jobs_parser.set_defaults(func=self._run_list_workflows) def _create_job_parser(self, subparsers): @@ -79,8 +81,8 @@ class ArgParser(object): def _run_list_jobs(self, _): self.target_object.jobs_list() - def _run_list_workflows(self, _): - self.target_object.workflows_list() + def _run_list_workflows(self, args): + self.target_object.workflows_list(all_versions=args.all) def _run_init_job(self, args): self.target_object.init_job(args.tag, args.outfile) diff --git a/bespin/commands.py b/bespin/commands.py index 8f7271d..c8c1fb6 100644 --- a/bespin/commands.py +++ b/bespin/commands.py @@ -44,6 +44,7 @@ USER_PLACEHOLDER_DICT = { } } + class Commands(object): """ Commands run based on command line input. @@ -61,12 +62,13 @@ class Commands(object): config = ConfigFile().read_or_create_config() return BespinApi(config, user_agent_str=self.user_agent_str) - def workflows_list(self): + def workflows_list(self, all_versions): """ Print out a table of workflows/questionnaires + :param all_versions: bool: when true show all versions otherwise show most recent """ api = self._create_api() - workflow_data = WorkflowDetails(api) + workflow_data = WorkflowDetails(api, all_versions) print(Table(workflow_data.column_names, workflow_data.get_column_data())) def jobs_list(self): @@ -167,10 +169,11 @@ class WorkflowDetails(object): """ Creates column data based on workflows/questionnaires """ - TAG_COLUMN_NAME = "latest version tag" + TAG_COLUMN_NAME = "version tag" - def __init__(self, api): + def __init__(self, api, all_versions): self.api = api + self.all_versions = all_versions self.column_names = ["id", "name", self.TAG_COLUMN_NAME] def get_column_data(self): @@ -181,10 +184,13 @@ class WorkflowDetails(object): data = [] for workflow in self.api.workflows_list(): if len(workflow['versions']): - latest_version = workflow['versions'][-1] - for questionnaire in self.api.questionnaires_list(workflow_version=latest_version): - workflow[self.TAG_COLUMN_NAME] = questionnaire['tag'] - data.append(workflow) + versions = workflow['versions'] + if not self.all_versions: + versions = versions[-1:] + for version in versions: + for questionnaire in self.api.questionnaires_list(workflow_version=version): + workflow[self.TAG_COLUMN_NAME] = questionnaire['tag'] + data.append(dict(workflow)) return data
Allow listing all workflow versions Allow users to see all version of workflows so the can pick older tags. Initially we thought users could just change the `v#` portion of the tags, but due to changes in the suffix portion of tags this is not possible.
Duke-GCB/bespin-cli
diff --git a/bespin/test_argparse.py b/bespin/test_argparse.py index 1f1cd6e..1af15be 100644 --- a/bespin/test_argparse.py +++ b/bespin/test_argparse.py @@ -10,9 +10,17 @@ class ArgParserTestCase(TestCase): self.target_object = Mock() self.arg_parser = ArgParser(version_str='1.0', target_object=self.target_object) - def test_workflows_list(self): + def test_workflows_list_current_versions(self): self.arg_parser.parse_and_run_commands(["workflows", "list"]) - self.target_object.workflows_list.assert_called() + self.target_object.workflows_list.assert_called_with(all_versions=False) + + def test_workflows_list_all_versions(self): + self.arg_parser.parse_and_run_commands(["workflows", "list", "--all"]) + self.target_object.workflows_list.assert_called_with(all_versions=True) + + def test_workflows_list_all_versions_short_flag(self): + self.arg_parser.parse_and_run_commands(["workflows", "list", "-a"]) + self.target_object.workflows_list.assert_called_with(all_versions=True) def test_init_job(self): self.arg_parser.parse_and_run_commands(["jobs", "init", "--tag", "exome/v1/human"]) diff --git a/bespin/test_commands.py b/bespin/test_commands.py index e3756c8..5bd78a8 100644 --- a/bespin/test_commands.py +++ b/bespin/test_commands.py @@ -18,13 +18,30 @@ class CommandsTestCase(TestCase): @patch('bespin.commands.WorkflowDetails') @patch('bespin.commands.Table') @patch('bespin.commands.print') - def test_workflows_list(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api, mock_config_file): + def test_workflows_list_latest_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api, + mock_config_file): commands = Commands(self.version_str, self.user_agent_str) - commands.workflows_list() + commands.workflows_list(all_versions=False) workflow_details = mock_workflow_details.return_value mock_table.assert_called_with(workflow_details.column_names, workflow_details.get_column_data.return_value) mock_print.assert_called_with(mock_table.return_value) + mock_workflow_details.assert_called_with(mock_bespin_api.return_value, False) + + @patch('bespin.commands.ConfigFile') + @patch('bespin.commands.BespinApi') + @patch('bespin.commands.WorkflowDetails') + @patch('bespin.commands.Table') + @patch('bespin.commands.print') + def test_workflows_list_all_versions(self, mock_print, mock_table, mock_workflow_details, mock_bespin_api, + mock_config_file): + commands = Commands(self.version_str, self.user_agent_str) + commands.workflows_list(all_versions=True) + workflow_details = mock_workflow_details.return_value + mock_table.assert_called_with(workflow_details.column_names, + workflow_details.get_column_data.return_value) + mock_print.assert_called_with(mock_table.return_value) + mock_workflow_details.assert_called_with(mock_bespin_api.return_value, True) @patch('bespin.commands.ConfigFile') @patch('bespin.commands.BespinApi') @@ -156,9 +173,9 @@ class WorkflowDetailsTestCase(TestCase): mock_api.questionnaires_list.return_value = [ {'tag': 'exome/v2/human'} ] - details = WorkflowDetails(mock_api) + details = WorkflowDetails(mock_api, all_versions=False) expected_data = [{'id': 1, - 'latest version tag': 'exome/v2/human', + 'version tag': 'exome/v2/human', 'name': 'exome', 'versions': [1, 2]}] column_data = details.get_column_data() @@ -166,12 +183,50 @@ class WorkflowDetailsTestCase(TestCase): self.assertEqual(column_data, expected_data) mock_api.questionnaires_list.assert_called_with(workflow_version=2) - def test_ignores_workflows_without_versions(self): + mock_api.questionnaires_list.reset_mock() + mock_api.questionnaires_list.side_effect = [ + [{'tag': 'exome/v1/human'}], + [{'tag': 'exome/v2/human'}] + ] + details = WorkflowDetails(mock_api, all_versions=True) + expected_data = [ + { + 'id': 1, + 'version tag': 'exome/v1/human', + 'name': 'exome', + 'versions': [1, 2] + }, + { + 'id': 1, + 'version tag': 'exome/v2/human', + 'name': 'exome', + 'versions': [1, 2] + }, + ] + column_data = details.get_column_data() + self.assertEqual(len(column_data), 2) + self.assertEqual(column_data, expected_data) + mock_api.questionnaires_list.assert_has_calls([ + call(workflow_version=1), + call(workflow_version=2), + ]) + + def test_ignores_workflows_without_versions_when_latest(self): + mock_api = Mock() + mock_api.workflows_list.return_value = [ + {'id': 1, 'name': 'no-versions', 'versions': []}, + ] + details = WorkflowDetails(mock_api, all_versions=False) + column_data = details.get_column_data() + self.assertEqual(len(column_data), 0) + mock_api.questionnaires_list.assert_not_called() + + def test_ignores_workflows_without_versions_when_all(self): mock_api = Mock() mock_api.workflows_list.return_value = [ {'id': 1, 'name': 'no-versions', 'versions': []}, ] - details = WorkflowDetails(mock_api) + details = WorkflowDetails(mock_api, all_versions=True) column_data = details.get_column_data() self.assertEqual(len(column_data), 0) mock_api.questionnaires_list.assert_not_called()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 2 }
0.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "devRequirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
azure-common==1.1.28 azure-core==1.32.0 azure-identity==1.21.0 azure-mgmt-core==1.5.0 azure-mgmt-storage==22.1.1 azure-storage-blob==12.25.1 azure-storage-file-datalake==12.20.0 -e git+https://github.com/Duke-GCB/bespin-cli.git@70450d7b00c477580d6851b8aaa65433a54cf415#egg=bespin_cli certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 cryptography==44.0.2 DukeDSClient==4.0.0 exceptiongroup==1.2.2 future==1.0.0 idna==3.10 iniconfig==2.1.0 isodate==0.7.2 mock==2.0.0 msal==1.32.0 msal-extensions==1.3.1 msgraph-core==0.2.2 packaging==24.2 pbr==6.1.1 pluggy==1.5.0 pycparser==2.22 PyJWT==2.10.1 pytest==8.3.5 pytz==2025.2 PyYAML==6.0.2 requests==2.32.3 six==1.17.0 tabulate==0.9.0 tenacity==6.2.0 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0
name: bespin-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - azure-common==1.1.28 - azure-core==1.32.0 - azure-identity==1.21.0 - azure-mgmt-core==1.5.0 - azure-mgmt-storage==22.1.1 - azure-storage-blob==12.25.1 - azure-storage-file-datalake==12.20.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - dukedsclient==4.0.0 - exceptiongroup==1.2.2 - future==1.0.0 - idna==3.10 - iniconfig==2.1.0 - isodate==0.7.2 - mock==2.0.0 - msal==1.32.0 - msal-extensions==1.3.1 - msgraph-core==0.2.2 - packaging==24.2 - pbr==6.1.1 - pluggy==1.5.0 - pycparser==2.22 - pyjwt==2.10.1 - pytest==8.3.5 - pytz==2025.2 - pyyaml==6.0.2 - requests==2.32.3 - six==1.17.0 - tabulate==0.9.0 - tenacity==6.2.0 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 prefix: /opt/conda/envs/bespin-cli
[ "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_all_versions_short_flag", "bespin/test_argparse.py::ArgParserTestCase::test_workflows_list_current_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_all_versions", "bespin/test_commands.py::CommandsTestCase::test_workflows_list_latest_versions", "bespin/test_commands.py::WorkflowDetailsTestCase::test_get_column_data", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_all", "bespin/test_commands.py::WorkflowDetailsTestCase::test_ignores_workflows_without_versions_when_latest" ]
[ "bespin/test_commands.py::JobFileTestCase::test_yaml_str" ]
[ "bespin/test_argparse.py::ArgParserTestCase::test_cancel_job", "bespin/test_argparse.py::ArgParserTestCase::test_create_job", "bespin/test_argparse.py::ArgParserTestCase::test_delete_job", "bespin/test_argparse.py::ArgParserTestCase::test_init_job", "bespin/test_argparse.py::ArgParserTestCase::test_restart_job", "bespin/test_argparse.py::ArgParserTestCase::test_start_job", "bespin/test_argparse.py::ArgParserTestCase::test_start_job_with_optional_token", "bespin/test_commands.py::CommandsTestCase::test_cancel_job", "bespin/test_commands.py::CommandsTestCase::test_create_job", "bespin/test_commands.py::CommandsTestCase::test_delete_job", "bespin/test_commands.py::CommandsTestCase::test_init_job", "bespin/test_commands.py::CommandsTestCase::test_jobs_list", "bespin/test_commands.py::CommandsTestCase::test_restart_job", "bespin/test_commands.py::CommandsTestCase::test_start_job_no_token", "bespin/test_commands.py::CommandsTestCase::test_start_job_with_token", "bespin/test_commands.py::TableTestCase::test_str", "bespin/test_commands.py::JobFileTestCase::test_create_job", "bespin/test_commands.py::JobFileTestCase::test_create_user_job_order_json", "bespin/test_commands.py::JobFileTestCase::test_get_dds_files_details", "bespin/test_commands.py::JobFileLoaderTestCase::test_create_job_file", "bespin/test_commands.py::JobFileLoaderTestCase::test_validate_job_file_data_invalid_job_order_params", "bespin/test_commands.py::JobFileLoaderTestCase::test_validate_job_file_data_invalid_name_and_fund_code", "bespin/test_commands.py::JobFileLoaderTestCase::test_validate_job_file_data_ok", "bespin/test_commands.py::JobQuestionnaireTestCase::test_create_job_file_with_placeholders", "bespin/test_commands.py::JobQuestionnaireTestCase::test_create_placeholder_value", "bespin/test_commands.py::JobQuestionnaireTestCase::test_format_user_fields", "bespin/test_commands.py::JobOrderWalkerTestCase::test_format_file_path", "bespin/test_commands.py::JobOrderWalkerTestCase::test_walk", "bespin/test_commands.py::JobOrderPlaceholderCheckTestCase::test_walk", "bespin/test_commands.py::JobOrderFormatFilesTestCase::test_walk", "bespin/test_commands.py::JobOrderFileDetailsTestCase::test_walk", "bespin/test_commands.py::JobsListTestCase::test_column_names", "bespin/test_commands.py::JobsListTestCase::test_get_column_data", "bespin/test_commands.py::JobsListTestCase::test_get_elapsed_hours", "bespin/test_commands.py::JobsListTestCase::test_get_workflow_tag" ]
[]
MIT License
3,207
802
[ "bespin/argparser.py", "bespin/commands.py" ]
mozilla__bleach-410
a39f7d6742cca84a4bb095e097c47b1d3770e58b
2018-10-10 18:58:35
cabd665db0b0a51aa4c58aac2c47bd4bf76e9c73
diff --git a/bleach/linkifier.py b/bleach/linkifier.py index 6394c03..5d815f8 100644 --- a/bleach/linkifier.py +++ b/bleach/linkifier.py @@ -499,13 +499,11 @@ class LinkifyFilter(html5lib_shim.Filter): # the tokens we're going to yield in_a = False token_buffer = [] - continue - else: token_buffer.append(token) - continue + continue - elif token['type'] in ['StartTag', 'EmptyTag']: + if token['type'] in ['StartTag', 'EmptyTag']: if token['name'] in self.skip_tags: # Skip tags start a "special mode" where we don't linkify # anything until the end tag. diff --git a/bleach/sanitizer.py b/bleach/sanitizer.py index 262915a..9ba4c57 100644 --- a/bleach/sanitizer.py +++ b/bleach/sanitizer.py @@ -267,8 +267,8 @@ class BleachSanitizerFilter(html5lib_shim.SanitizerFilter): return super(BleachSanitizerFilter, self).__init__(source, **kwargs) - def __iter__(self): - for token in html5lib_shim.Filter.__iter__(self): + def sanitize_stream(self, token_iterator): + for token in token_iterator: ret = self.sanitize_token(token) if not ret: @@ -280,6 +280,40 @@ class BleachSanitizerFilter(html5lib_shim.SanitizerFilter): else: yield ret + def merge_characters(self, token_iterator): + """Merge consecutive Characters tokens in a stream""" + characters_buffer = [] + + for token in token_iterator: + if characters_buffer: + if token['type'] == 'Characters': + characters_buffer.append(token) + continue + else: + # Merge all the characters tokens together into one and then + # operate on it. + new_token = { + 'data': ''.join([char_token['data'] for char_token in characters_buffer]), + 'type': 'Characters' + } + characters_buffer = [] + yield new_token + + elif token['type'] == 'Characters': + characters_buffer.append(token) + continue + + yield token + + new_token = { + 'data': ''.join([char_token['data'] for char_token in characters_buffer]), + 'type': 'Characters' + } + yield new_token + + def __iter__(self): + return self.merge_characters(self.sanitize_stream(html5lib_shim.Filter.__iter__(self))) + def sanitize_token(self, token): """Sanitize a token either by HTML-encoding or dropping.
LinkifyFilter not working for URLs with ampersands Example with bleach 2.1.3: ``` from bleach import Cleaner from bleach.linkifier import LinkifyFilter url1 = 'http://a.co?b=1&c=2' url2 = 'http://a.co?b=1&amp;c=2' cleaner = Cleaner(filters=[LinkifyFilter]) cleaner.clean(url1) cleaner.clean(url2) ``` Both result in `<a href="http://a.co?b=1">http://a.co?b=1</a>&amp;c=2`
mozilla/bleach
diff --git a/tests/test_clean.py b/tests/test_clean.py index b543cdf..5322767 100644 --- a/tests/test_clean.py +++ b/tests/test_clean.py @@ -58,6 +58,7 @@ def test_html_is_lowercased(): '<a href="http://example.com">foo</a>' ) + def test_invalid_uri_does_not_raise_error(): assert clean('<a href="http://example.com]">text</a>') == '<a>text</a>' diff --git a/tests/test_linkify.py b/tests/test_linkify.py index 876cb84..eeea3e3 100644 --- a/tests/test_linkify.py +++ b/tests/test_linkify.py @@ -4,7 +4,8 @@ import pytest from six.moves.urllib_parse import quote_plus from bleach import linkify, DEFAULT_CALLBACKS as DC -from bleach.linkifier import Linker +from bleach.linkifier import Linker, LinkifyFilter +from bleach.sanitizer import Cleaner def test_empty(): @@ -656,3 +657,20 @@ class TestLinkify: with pytest.raises(TypeError): linkify(no_type) + + [email protected]('text, expected', [ + ('abc', 'abc'), + ('example.com', '<a href="http://example.com">example.com</a>'), + ( + 'http://example.com?b=1&c=2', + '<a href="http://example.com?b=1&amp;c=2">http://example.com?b=1&amp;c=2</a>' + ), + ( + 'link: https://example.com/watch#anchor', + 'link: <a href="https://example.com/watch#anchor">https://example.com/watch#anchor</a>' + ) +]) +def test_linkify_filter(text, expected): + cleaner = Cleaner(filters=[LinkifyFilter]) + assert cleaner.clean(text) == expected
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 -e git+https://github.com/mozilla/bleach.git@a39f7d6742cca84a4bb095e097c47b1d3770e58b#egg=bleach certifi==2021.5.30 cffi==1.15.1 charset-normalizer==2.0.12 colorama==0.4.5 cryptography==40.0.2 distlib==0.3.9 docutils==0.17.1 filelock==3.4.1 flake8==5.0.4 idna==3.10 imagesize==1.4.1 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 jeepney==0.7.1 Jinja2==3.0.3 keyring==23.4.1 MarkupSafe==2.0.1 mccabe==0.7.0 packaging==21.3 pkginfo==1.10.0 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pycparser==2.21 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytest-wholenodeid==0.2 pytz==2025.2 readme-renderer==34.0 requests==2.27.1 requests-toolbelt==1.0.0 rfc3986==1.5.0 SecretStorage==3.3.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==4.3.2 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 toml==0.10.2 tomli==1.2.3 tox==3.28.0 tqdm==4.64.1 twine==3.8.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.16.2 webencodings==0.5.1 zipp==3.6.0
name: bleach channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - cffi==1.15.1 - charset-normalizer==2.0.12 - colorama==0.4.5 - cryptography==40.0.2 - distlib==0.3.9 - docutils==0.17.1 - filelock==3.4.1 - flake8==5.0.4 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jeepney==0.7.1 - jinja2==3.0.3 - keyring==23.4.1 - markupsafe==2.0.1 - mccabe==0.7.0 - packaging==21.3 - pkginfo==1.10.0 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pycparser==2.21 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-wholenodeid==0.2 - pytz==2025.2 - readme-renderer==34.0 - requests==2.27.1 - requests-toolbelt==1.0.0 - rfc3986==1.5.0 - secretstorage==3.3.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==4.3.2 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - tqdm==4.64.1 - twine==3.8.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.16.2 - webencodings==0.5.1 - zipp==3.6.0 prefix: /opt/conda/envs/bleach
[ "tests/test_linkify.py::test_linkify_filter[http://example.com?b=1&c=2-<a" ]
[]
[ "tests/test_clean.py::test_clean_idempotent", "tests/test_clean.py::test_only_text_is_cleaned", "tests/test_clean.py::test_empty", "tests/test_clean.py::test_content_has_no_html", "tests/test_clean.py::test_content_has_allowed_html[an", "tests/test_clean.py::test_content_has_allowed_html[another", "tests/test_clean.py::test_html_is_lowercased", "tests/test_clean.py::test_invalid_uri_does_not_raise_error", "tests/test_clean.py::test_comments[<!--", "tests/test_clean.py::test_comments[<!--open", "tests/test_clean.py::test_comments[<!--comment-->text-True-text]", "tests/test_clean.py::test_comments[<!--comment-->text-False-<!--comment-->text]", "tests/test_clean.py::test_comments[text<!--", "tests/test_clean.py::test_comments[text<!--comment-->-True-text]", "tests/test_clean.py::test_comments[text<!--comment-->-False-text<!--comment-->]", "tests/test_clean.py::test_invalid_char_in_tag", "tests/test_clean.py::test_unclosed_tag", "tests/test_clean.py::test_nested_script_tag", "tests/test_clean.py::test_bare_entities_get_escaped_correctly[an", "tests/test_clean.py::test_bare_entities_get_escaped_correctly[tag", "tests/test_clean.py::test_character_entities_handling[&amp;-&amp;]", "tests/test_clean.py::test_character_entities_handling[&nbsp;-&nbsp;]", "tests/test_clean.py::test_character_entities_handling[&nbsp;", "tests/test_clean.py::test_character_entities_handling[&lt;em&gt;strong&lt;/em&gt;-&lt;em&gt;strong&lt;/em&gt;]", "tests/test_clean.py::test_character_entities_handling[&amp;is", "tests/test_clean.py::test_character_entities_handling[cool", "tests/test_clean.py::test_character_entities_handling[&&amp;", "tests/test_clean.py::test_character_entities_handling[&amp;", "tests/test_clean.py::test_character_entities_handling[this", "tests/test_clean.py::test_character_entities_handling[http://example.com?active=true&current=true-http://example.com?active=true&amp;current=true]", "tests/test_clean.py::test_character_entities_handling[<a", "tests/test_clean.py::test_character_entities_handling[&xx;-&xx;]", "tests/test_clean.py::test_character_entities_handling[&#39;-&#39;]", "tests/test_clean.py::test_character_entities_handling[&#34;-&#34;]", "tests/test_clean.py::test_character_entities_handling[&#123;-&#123;]", "tests/test_clean.py::test_character_entities_handling[&#x0007b;-&#x0007b;]", "tests/test_clean.py::test_character_entities_handling[&#x0007B;-&#x0007B;]", "tests/test_clean.py::test_character_entities_handling[&#-&amp;#]", "tests/test_clean.py::test_character_entities_handling[&#<-&amp;#&lt;]", "tests/test_clean.py::test_character_entities_handling[&#39;&#34;-&#39;&#34;]", "tests/test_clean.py::test_stripping_tags[a", "tests/test_clean.py::test_stripping_tags[<p><a", "tests/test_clean.py::test_stripping_tags[<p><span>multiply", "tests/test_clean.py::test_stripping_tags[<ul><li><script></li></ul>-kwargs4-<ul><li></li></ul>]", "tests/test_clean.py::test_stripping_tags[<isindex>-kwargs6-]", "tests/test_clean.py::test_stripping_tags[Yeah", "tests/test_clean.py::test_stripping_tags[<sarcasm>-kwargs8-]", "tests/test_clean.py::test_stripping_tags[</sarcasm>-kwargs9-]", "tests/test_clean.py::test_stripping_tags[</", "tests/test_clean.py::test_stripping_tags[Foo", "tests/test_clean.py::test_stripping_tags[Favorite", "tests/test_clean.py::test_stripping_tags[</3-kwargs14-&lt;/3]", "tests/test_clean.py::test_escaping_tags[<img", "tests/test_clean.py::test_escaping_tags[<script>safe()</script>-&lt;script&gt;safe()&lt;/script&gt;]", "tests/test_clean.py::test_escaping_tags[<style>body{}</style>-&lt;style&gt;body{}&lt;/style&gt;]", "tests/test_clean.py::test_escaping_tags[<ul><li><script></li></ul>-<ul><li>&lt;script&gt;</li></ul>]", "tests/test_clean.py::test_escaping_tags[<isindex>-&lt;isindex&gt;]", "tests/test_clean.py::test_escaping_tags[<sarcasm/>-&lt;sarcasm/&gt;]", "tests/test_clean.py::test_escaping_tags[<sarcasm>-&lt;sarcasm&gt;]", "tests/test_clean.py::test_escaping_tags[</sarcasm>-&lt;/sarcasm&gt;]", "tests/test_clean.py::test_escaping_tags[</", "tests/test_clean.py::test_escaping_tags[</3-&lt;/3]", "tests/test_clean.py::test_escaping_tags[<[email protected]>-&lt;[email protected]&gt;]", "tests/test_clean.py::test_escaping_tags[Favorite", "tests/test_clean.py::test_stripping_tags_is_safe[<scri<script>pt>alert(1)</scr</script>ipt>-pt&gt;alert(1)ipt&gt;]", "tests/test_clean.py::test_stripping_tags_is_safe[<scri<scri<script>pt>pt>alert(1)</script>-pt&gt;pt&gt;alert(1)]", "tests/test_clean.py::test_allowed_styles", "tests/test_clean.py::test_href_with_wrong_tag", "tests/test_clean.py::test_disallowed_attr", "tests/test_clean.py::test_unquoted_attr_values_are_quoted", "tests/test_clean.py::test_unquoted_event_handler_attr_value", "tests/test_clean.py::test_invalid_filter_attr", "tests/test_clean.py::test_poster_attribute", "tests/test_clean.py::test_attributes_callable", "tests/test_clean.py::test_attributes_wildcard", "tests/test_clean.py::test_attributes_wildcard_callable", "tests/test_clean.py::test_attributes_tag_callable", "tests/test_clean.py::test_attributes_tag_list", "tests/test_clean.py::test_attributes_list", "tests/test_clean.py::test_uri_value_allowed_protocols[<a", "tests/test_clean.py::test_svg_attr_val_allows_ref", "tests/test_clean.py::test_svg_allow_local_href[<svg><pattern", "tests/test_clean.py::test_svg_allow_local_href_nonlocal[<svg><pattern", "tests/test_clean.py::test_invisible_characters[1\\x0723-1?23]", "tests/test_clean.py::test_invisible_characters[1\\x0823-1?23]", "tests/test_clean.py::test_invisible_characters[1\\x0b23-1?23]", "tests/test_clean.py::test_invisible_characters[1\\x0c23-1?23]", "tests/test_clean.py::test_invisible_characters[import", "tests/test_clean.py::test_nonexistent_namespace", "tests/test_clean.py::test_regressions[1.test]", "tests/test_clean.py::test_regressions[2.test]", "tests/test_clean.py::test_regressions[3.test]", "tests/test_clean.py::test_regressions[4.test]", "tests/test_clean.py::test_regressions[5.test]", "tests/test_clean.py::test_regressions[6.test]", "tests/test_clean.py::test_regressions[7.test]", "tests/test_clean.py::test_regressions[8.test]", "tests/test_clean.py::test_regressions[9.test]", "tests/test_clean.py::test_regressions[10.test]", "tests/test_clean.py::test_regressions[11.test]", "tests/test_clean.py::test_regressions[12.test]", "tests/test_clean.py::test_regressions[13.test]", "tests/test_clean.py::test_regressions[14.test]", "tests/test_clean.py::test_regressions[15.test]", "tests/test_clean.py::test_regressions[16.test]", "tests/test_clean.py::test_regressions[17.test]", "tests/test_clean.py::test_regressions[18.test]", "tests/test_clean.py::test_regressions[19.test]", "tests/test_clean.py::test_regressions[20.test]", "tests/test_clean.py::TestCleaner::test_basics", "tests/test_clean.py::TestCleaner::test_filters", "tests/test_linkify.py::test_empty", "tests/test_linkify.py::test_simple_link", "tests/test_linkify.py::test_trailing_slash", "tests/test_linkify.py::test_mangle_link", "tests/test_linkify.py::test_mangle_text", "tests/test_linkify.py::test_email_link[a", "tests/test_linkify.py::test_email_link[aussie", "tests/test_linkify.py::test_email_link[email", "tests/test_linkify.py::test_email_link[<br>[email protected]<br><a", "tests/test_linkify.py::test_email_link[mailto", "tests/test_linkify.py::test_email_link[\"\\\\\\n\"@opa.ru-True-\"\\\\\\n\"@opa.ru]", "tests/test_linkify.py::test_email_link_escaping[\"james\"@example.com-<a", "tests/test_linkify.py::test_email_link_escaping[\"j'ames\"@example.com-<a", "tests/test_linkify.py::test_email_link_escaping[\"ja>mes\"@example.com-<a", "tests/test_linkify.py::test_prevent_links[callback0-a", "tests/test_linkify.py::test_prevent_links[callback1-a", "tests/test_linkify.py::test_prevent_links[callback2-a", "tests/test_linkify.py::test_prevent_links[callback3-a", "tests/test_linkify.py::test_prevent_links[callback4-a", "tests/test_linkify.py::test_prevent_links[callback5-a", "tests/test_linkify.py::test_set_attrs", "tests/test_linkify.py::test_only_proto_links", "tests/test_linkify.py::test_stop_email", "tests/test_linkify.py::test_tlds[example.com-<a", "tests/test_linkify.py::test_tlds[example.co-<a", "tests/test_linkify.py::test_tlds[example.co.uk-<a", "tests/test_linkify.py::test_tlds[example.edu-<a", "tests/test_linkify.py::test_tlds[example.xxx-<a", "tests/test_linkify.py::test_tlds[bit.ly/fun-<a", "tests/test_linkify.py::test_tlds[example.yyy-example.yyy]", "tests/test_linkify.py::test_tlds[brie-brie]", "tests/test_linkify.py::test_escaping", "tests/test_linkify.py::test_nofollow_off", "tests/test_linkify.py::test_link_in_html", "tests/test_linkify.py::test_links_https", "tests/test_linkify.py::test_add_rel_nofollow", "tests/test_linkify.py::test_url_with_path", "tests/test_linkify.py::test_link_ftp", "tests/test_linkify.py::test_link_query", "tests/test_linkify.py::test_link_fragment", "tests/test_linkify.py::test_link_entities", "tests/test_linkify.py::test_escaped_html", "tests/test_linkify.py::test_link_http_complete", "tests/test_linkify.py::test_non_url", "tests/test_linkify.py::test_javascript_url", "tests/test_linkify.py::test_unsafe_url", "tests/test_linkify.py::test_skip_tags", "tests/test_linkify.py::test_libgl", "tests/test_linkify.py::test_end_of_sentence[example.com-.]", "tests/test_linkify.py::test_end_of_sentence[example.com-...]", "tests/test_linkify.py::test_end_of_sentence[ex.com/foo-.]", "tests/test_linkify.py::test_end_of_sentence[ex.com/foo-....]", "tests/test_linkify.py::test_end_of_clause", "tests/test_linkify.py::test_sarcasm", "tests/test_linkify.py::test_wrapping_parentheses[(example.com)-expected_data0]", "tests/test_linkify.py::test_wrapping_parentheses[(example.com/)-expected_data1]", "tests/test_linkify.py::test_wrapping_parentheses[(example.com/foo)-expected_data2]", "tests/test_linkify.py::test_wrapping_parentheses[(((example.com/))))-expected_data3]", "tests/test_linkify.py::test_wrapping_parentheses[example.com/))-expected_data4]", "tests/test_linkify.py::test_wrapping_parentheses[(foo", "tests/test_linkify.py::test_wrapping_parentheses[http://en.wikipedia.org/wiki/Test_(assessment)-expected_data7]", "tests/test_linkify.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/Test_(assessment))-expected_data8]", "tests/test_linkify.py::test_wrapping_parentheses[((http://en.wikipedia.org/wiki/Test_(assessment))-expected_data9]", "tests/test_linkify.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/Test_(assessment)))-expected_data10]", "tests/test_linkify.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/)Test_(assessment-expected_data11]", "tests/test_linkify.py::test_wrapping_parentheses[hello", "tests/test_linkify.py::test_parentheses_with_removing", "tests/test_linkify.py::test_ports[http://foo.com:8000-expected_data0]", "tests/test_linkify.py::test_ports[http://foo.com:8000/-expected_data1]", "tests/test_linkify.py::test_ports[http://bar.com:xkcd-expected_data2]", "tests/test_linkify.py::test_ports[http://foo.com:81/bar-expected_data3]", "tests/test_linkify.py::test_ports[http://foo.com:-expected_data4]", "tests/test_linkify.py::test_ports[http://foo.com:\\u0663\\u0669/-expected_data5]", "tests/test_linkify.py::test_ports[http://foo.com:\\U0001d7e0\\U0001d7d8/-expected_data6]", "tests/test_linkify.py::test_ignore_bad_protocols", "tests/test_linkify.py::test_link_emails_and_urls", "tests/test_linkify.py::test_links_case_insensitive", "tests/test_linkify.py::test_elements_inside_links", "tests/test_linkify.py::test_drop_link_tags", "tests/test_linkify.py::test_naughty_unescaping[&lt;br&gt;-&lt;br&gt;]", "tests/test_linkify.py::test_naughty_unescaping[&lt;br&gt;", "tests/test_linkify.py::test_hang", "tests/test_linkify.py::test_hyphen_in_mail", "tests/test_linkify.py::test_url_re_arg", "tests/test_linkify.py::test_email_re_arg", "tests/test_linkify.py::test_linkify_idempotent", "tests/test_linkify.py::TestLinkify::test_no_href_links", "tests/test_linkify.py::TestLinkify::test_rel_already_there", "tests/test_linkify.py::TestLinkify::test_only_text_is_linkified", "tests/test_linkify.py::test_linkify_filter[abc-abc]", "tests/test_linkify.py::test_linkify_filter[example.com-<a", "tests/test_linkify.py::test_linkify_filter[link:" ]
[]
Apache License 2.0
3,210
674
[ "bleach/linkifier.py", "bleach/sanitizer.py" ]